diff --git a/go.mod b/go.mod index 0f7fcf5ed4..dec80fdc3d 100644 --- a/go.mod +++ b/go.mod @@ -1,8 +1,7 @@ module sigs.k8s.io/security-profiles-operator go 1.23.0 - -toolchain go1.23.3 +toolchain go1.23.6 require ( dario.cat/mergo v1.0.1 @@ -28,7 +27,7 @@ require ( github.com/prometheus/client_golang v1.21.0 github.com/prometheus/client_model v0.6.1 github.com/seccomp/libseccomp-golang v0.10.0 - github.com/sigstore/cosign/v2 v2.4.1 + github.com/sigstore/cosign/v2 v2.4.3 github.com/stretchr/testify v1.10.0 github.com/urfave/cli/v2 v2.27.5 golang.org/x/mod v0.23.0 @@ -51,12 +50,11 @@ require ( require ( cel.dev/expr v0.19.1 // indirect - cloud.google.com/go/auth v0.13.0 // indirect - cloud.google.com/go/auth/oauth2adapt v0.2.6 // indirect + cloud.google.com/go/auth v0.14.1 // indirect + cloud.google.com/go/auth/oauth2adapt v0.2.7 // indirect cloud.google.com/go/compute/metadata v0.6.0 // indirect - cuelabs.dev/go/oci/ociregistry v0.0.0-20240404174027-a39bec0462d2 // indirect - cuelang.org/go v0.9.2 // indirect - filippo.io/edwards25519 v1.1.0 // indirect + cuelabs.dev/go/oci/ociregistry v0.0.0-20241125120445-2c00c104c6e1 // indirect + cuelang.org/go v0.12.0 // indirect github.com/AliyunContainerService/ack-ram-tool/pkg/credentials/provider v0.14.0 // indirect github.com/Azure/azure-sdk-for-go v68.0.0+incompatible // indirect github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect @@ -72,7 +70,7 @@ require ( github.com/OneOfOne/xxhash v1.2.8 // indirect github.com/ProtonMail/go-crypto v0.0.0-20230923063757-afb1ddc0824c // indirect github.com/ThalesIgnite/crypto11 v1.2.5 // indirect - github.com/agnivade/levenshtein v1.1.1 // indirect + github.com/agnivade/levenshtein v1.2.0 // indirect github.com/alibabacloud-go/alibabacloud-gateway-spi v0.0.4 // indirect github.com/alibabacloud-go/cr-20160607 v1.0.1 // indirect github.com/alibabacloud-go/cr-20181201 v1.0.10 // indirect @@ -86,28 +84,28 @@ require ( github.com/aliyun/credentials-go v1.3.2 // indirect github.com/antlr4-go/antlr/v4 v4.13.1 // indirect github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect - github.com/aws/aws-sdk-go-v2 v1.32.7 // indirect - github.com/aws/aws-sdk-go-v2/config v1.28.7 // indirect - github.com/aws/aws-sdk-go-v2/credentials v1.17.48 // indirect - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.22 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.26 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.26 // indirect - github.com/aws/aws-sdk-go-v2/internal/ini v1.8.1 // indirect - github.com/aws/aws-sdk-go-v2/service/ecr v1.20.2 // indirect - github.com/aws/aws-sdk-go-v2/service/ecrpublic v1.18.2 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.1 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.7 // indirect - github.com/aws/aws-sdk-go-v2/service/sso v1.24.8 // indirect - github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.7 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.33.3 // indirect - github.com/aws/smithy-go v1.22.1 // indirect - github.com/awslabs/amazon-ecr-credential-helper/ecr-login v0.0.0-20231024185945-8841054dbdb8 // indirect + github.com/aws/aws-sdk-go-v2 v1.36.1 // indirect + github.com/aws/aws-sdk-go-v2/config v1.29.6 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.17.59 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.28 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.32 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.32 // indirect + github.com/aws/aws-sdk-go-v2/internal/ini v1.8.2 // indirect + github.com/aws/aws-sdk-go-v2/service/ecr v1.40.3 // indirect + github.com/aws/aws-sdk-go-v2/service/ecrpublic v1.31.2 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.2 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.13 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.24.15 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.14 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.33.14 // indirect + github.com/aws/smithy-go v1.22.2 // indirect + github.com/awslabs/amazon-ecr-credential-helper/ecr-login v0.9.1 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/blang/semver v3.5.1+incompatible // indirect - github.com/buildkite/agent/v3 v3.81.0 // indirect - github.com/buildkite/go-pipeline v0.13.1 // indirect - github.com/buildkite/interpolate v0.1.3 // indirect - github.com/buildkite/roko v1.2.0 // indirect + github.com/buildkite/agent/v3 v3.92.1 // indirect + github.com/buildkite/go-pipeline v0.13.3 // indirect + github.com/buildkite/interpolate v0.1.5 // indirect + github.com/buildkite/roko v1.3.1 // indirect github.com/cenkalti/backoff/v4 v4.3.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/chrismellard/docker-credential-acr-env v0.0.0-20230304212654-82a0ddb27589 // indirect @@ -130,7 +128,7 @@ require ( github.com/docker/docker-credential-helpers v0.8.2 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/emicklei/go-restful/v3 v3.12.1 // indirect - github.com/emicklei/proto v1.12.1 // indirect + github.com/emicklei/proto v1.13.4 // indirect github.com/evanphx/json-patch/v5 v5.9.11 // indirect github.com/fatih/color v1.18.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect @@ -151,7 +149,7 @@ require ( github.com/go-openapi/strfmt v0.23.0 // indirect github.com/go-openapi/swag v0.23.0 // indirect github.com/go-openapi/validate v0.24.0 // indirect - github.com/go-piv/piv-go v1.11.0 // indirect + github.com/go-piv/piv-go/v2 v2.3.0 // indirect github.com/gobuffalo/flect v1.0.3 // indirect github.com/gobwas/glob v0.2.3 // indirect github.com/godbus/dbus/v5 v5.1.0 // indirect @@ -161,12 +159,12 @@ require ( github.com/golang/snappy v0.0.4 // indirect github.com/google/btree v1.1.3 // indirect github.com/google/cel-go v0.22.1 // indirect - github.com/google/certificate-transparency-go v1.2.1 // indirect + github.com/google/certificate-transparency-go v1.3.1 // indirect github.com/google/gnostic-models v0.6.9 // indirect github.com/google/go-github/v55 v55.0.0 // indirect github.com/google/go-querystring v1.1.0 // indirect github.com/google/gofuzz v1.2.0 // indirect - github.com/google/s2a-go v0.1.8 // indirect + github.com/google/s2a-go v0.1.9 // indirect github.com/google/uuid v1.6.0 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.4 // indirect github.com/googleapis/gax-go/v2 v2.14.1 // indirect @@ -179,20 +177,19 @@ require ( github.com/in-toto/in-toto-golang v0.9.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jedisct1/go-minisign v0.0.0-20230811132847-661be99b8267 // indirect - github.com/jmespath/go-jmespath v0.4.1-0.20220621161143-b0104c826a24 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/compress v1.17.11 // indirect github.com/letsencrypt/boulder v0.0.0-20240620165639-de9c06129bec // indirect github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de // indirect - github.com/magiconair/properties v1.8.7 // indirect + github.com/magiconair/properties v1.8.9 // indirect github.com/mailru/easyjson v0.9.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/miekg/pkcs11 v1.1.1 // indirect github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/mitchellh/go-wordwrap v1.0.1 // indirect - github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/mitchellh/mapstructure v1.5.1-0.20231216201459-8508981c8b6c // indirect github.com/moby/sys/mountinfo v0.7.2 // indirect github.com/moby/sys/userns v0.1.0 // indirect github.com/moby/term v0.5.2 // indirect @@ -203,18 +200,18 @@ require ( github.com/nozzle/throttler v0.0.0-20180817012639-2ea982251481 // indirect github.com/oklog/ulid v1.3.1 // indirect github.com/oleiade/reflections v1.1.0 // indirect - github.com/open-policy-agent/opa v0.68.0 // indirect + github.com/open-policy-agent/opa v1.1.0 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opentracing/opentracing-go v1.2.0 // indirect github.com/pborman/uuid v1.2.1 // indirect - github.com/pelletier/go-toml/v2 v2.2.2 // indirect + github.com/pelletier/go-toml/v2 v2.2.3 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/common v0.62.0 // indirect github.com/prometheus/procfs v0.15.1 // indirect - github.com/protocolbuffers/txtpbfmt v0.0.0-20231025115547-084445ff1adf // indirect + github.com/protocolbuffers/txtpbfmt v0.0.0-20241112170944-20d2c9ebc01d // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect - github.com/rogpeppe/go-internal v1.13.1 // indirect + github.com/rogpeppe/go-internal v1.13.2-0.20241226121412-a5dc8ff20d0a // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/sagikazarmark/locafero v0.4.0 // indirect github.com/sagikazarmark/slog-shim v0.1.0 // indirect @@ -222,64 +219,63 @@ require ( github.com/secure-systems-lab/go-securesystemslib v0.9.0 // indirect github.com/segmentio/ksuid v1.0.4 // indirect github.com/shibumi/go-pathspec v1.3.0 // indirect - github.com/sigstore/fulcio v1.6.4 // indirect - github.com/sigstore/protobuf-specs v0.3.3 // indirect - github.com/sigstore/rekor v1.3.8 // indirect - github.com/sigstore/sigstore v1.8.12 // indirect - github.com/sigstore/sigstore-go v0.6.1 // indirect - github.com/sigstore/timestamp-authority v1.2.2 // indirect + github.com/sigstore/fulcio v1.6.6 // indirect + github.com/sigstore/protobuf-specs v0.4.0 // indirect + github.com/sigstore/rekor v1.3.9 // indirect + github.com/sigstore/sigstore v1.8.15 // indirect + github.com/sigstore/sigstore-go v0.7.0 // indirect + github.com/sigstore/timestamp-authority v1.2.4 // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 // indirect github.com/sourcegraph/conc v0.3.0 // indirect github.com/spf13/afero v1.11.0 // indirect github.com/spf13/cast v1.7.0 // indirect - github.com/spf13/cobra v1.8.1 // indirect + github.com/spf13/cobra v1.9.1 // indirect github.com/spf13/pflag v1.0.6 // indirect github.com/spf13/viper v1.19.0 // indirect - github.com/spiffe/go-spiffe/v2 v2.3.0 // indirect + github.com/spiffe/go-spiffe/v2 v2.5.0 // indirect github.com/stoewer/go-strcase v1.3.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect github.com/tchap/go-patricia/v2 v2.3.2 // indirect github.com/thales-e-security/pool v0.0.2 // indirect github.com/theupdateframework/go-tuf v0.7.0 // indirect - github.com/theupdateframework/go-tuf/v2 v2.0.1 // indirect + github.com/theupdateframework/go-tuf/v2 v2.0.2 // indirect github.com/titanous/rocacheck v0.0.0-20171023193734-afe73141d399 // indirect github.com/tjfoc/gmsm v1.4.1 // indirect github.com/transparency-dev/merkle v0.0.2 // indirect github.com/vbatts/tar-split v0.11.7 // indirect github.com/x448/float16 v0.8.4 // indirect - github.com/xanzy/go-gitlab v0.109.0 // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect github.com/yashtewari/glob-intersection v0.2.0 // indirect - github.com/zeebo/errs v1.3.0 // indirect + github.com/zeebo/errs v1.4.0 // indirect + gitlab.com/gitlab-org/api/client-go v0.123.0 // indirect go.mongodb.org/mongo-driver v1.14.0 // indirect go.opentelemetry.io/auto/sdk v1.1.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0 // indirect - go.opentelemetry.io/otel v1.33.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.33.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.33.0 // indirect - go.opentelemetry.io/otel/metric v1.33.0 // indirect - go.opentelemetry.io/otel/sdk v1.33.0 // indirect - go.opentelemetry.io/otel/trace v1.33.0 // indirect - go.opentelemetry.io/proto/otlp v1.4.0 // indirect - go.step.sm/crypto v0.56.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0 // indirect + go.opentelemetry.io/otel v1.34.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.34.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.34.0 // indirect + go.opentelemetry.io/otel/metric v1.34.0 // indirect + go.opentelemetry.io/otel/sdk v1.34.0 // indirect + go.opentelemetry.io/otel/trace v1.34.0 // indirect + go.opentelemetry.io/proto/otlp v1.5.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.27.0 // indirect golang.org/x/crypto v0.33.0 // indirect golang.org/x/exp v0.0.0-20250103183323-7d7fa50e5329 // indirect - golang.org/x/oauth2 v0.25.0 // indirect + golang.org/x/oauth2 v0.26.0 // indirect golang.org/x/sys v0.30.0 // indirect golang.org/x/term v0.29.0 // indirect golang.org/x/text v0.22.0 // indirect - golang.org/x/time v0.9.0 // indirect + golang.org/x/time v0.10.0 // indirect golang.org/x/tools v0.29.0 // indirect gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect - google.golang.org/api v0.216.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20241219192143-6b3ec007d9bb // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20250102185135-69823020774d // indirect + google.golang.org/api v0.221.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20250115164207-1a7da9e5054f // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20250207221924-e9438ea467c6 // indirect gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/ini.v1 v1.67.0 // indirect diff --git a/go.sum b/go.sum index c157aeb5ee..ce5b2b8ced 100644 --- a/go.sum +++ b/go.sum @@ -3,22 +3,22 @@ cel.dev/expr v0.19.1/go.mod h1:MrpN08Q+lEBs+bGYdLxxHkZoUSsCp0nSKTs0nTymJgw= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.116.0 h1:B3fRrSDkLRt5qSHWe40ERJvhvnQwdZiHu0bJOpldweE= cloud.google.com/go v0.116.0/go.mod h1:cEPSRWPzZEswwdr9BxE6ChEn01dWlTaF05LiC2Xs70U= -cloud.google.com/go/auth v0.13.0 h1:8Fu8TZy167JkW8Tj3q7dIkr2v4cndv41ouecJx0PAHs= -cloud.google.com/go/auth v0.13.0/go.mod h1:COOjD9gwfKNKz+IIduatIhYJQIc0mG3H102r/EMxX6Q= -cloud.google.com/go/auth/oauth2adapt v0.2.6 h1:V6a6XDu2lTwPZWOawrAa9HUK+DB2zfJyTuciBG5hFkU= -cloud.google.com/go/auth/oauth2adapt v0.2.6/go.mod h1:AlmsELtlEBnaNTL7jCj8VQFLy6mbZv0s4Q7NGBeQ5E8= +cloud.google.com/go/auth v0.14.1 h1:AwoJbzUdxA/whv1qj3TLKwh3XX5sikny2fc40wUl+h0= +cloud.google.com/go/auth v0.14.1/go.mod h1:4JHUxlGXisL0AW8kXPtUF6ztuOksyfUQNFjfsOCXkPM= +cloud.google.com/go/auth/oauth2adapt v0.2.7 h1:/Lc7xODdqcEw8IrZ9SvwnlLX6j9FHQM74z6cBk9Rw6M= +cloud.google.com/go/auth/oauth2adapt v0.2.7/go.mod h1:NTbTTzfvPl1Y3V1nPpOgl2w6d/FjO7NNUQaWSox6ZMc= cloud.google.com/go/compute/metadata v0.6.0 h1:A6hENjEsCDtC1k8byVsgwvVcioamEHvZ4j01OwKxG9I= cloud.google.com/go/compute/metadata v0.6.0/go.mod h1:FjyFAW1MW0C203CEOMDTu3Dk1FlqW3Rga40jzHL4hfg= cloud.google.com/go/iam v1.2.2 h1:ozUSofHUGf/F4tCNy/mu9tHLTaxZFLOUiKzjcgWHGIA= cloud.google.com/go/iam v1.2.2/go.mod h1:0Ys8ccaZHdI1dEUilwzqng/6ps2YB6vRsjIe00/+6JY= -cloud.google.com/go/kms v1.20.4 h1:CJ0hMpOg1ANN9tx/a/GPJ+Uxudy8k6f3fvGFuTHiE5A= -cloud.google.com/go/kms v1.20.4/go.mod h1:gPLsp1r4FblUgBYPOcvI/bUPpdMg2Jm1ZVKU4tQUfcc= +cloud.google.com/go/kms v1.20.5 h1:aQQ8esAIVZ1atdJRxihhdxGQ64/zEbJoJnCz/ydSmKg= +cloud.google.com/go/kms v1.20.5/go.mod h1:C5A8M1sv2YWYy1AE6iSrnddSG9lRGdJq5XEdBy28Lmw= cloud.google.com/go/longrunning v0.6.2 h1:xjDfh1pQcWPEvnfjZmwjKQEcHnpz6lHjfy7Fo0MK+hc= cloud.google.com/go/longrunning v0.6.2/go.mod h1:k/vIs83RN4bE3YCswdXC5PFfWVILjm3hpEUlSko4PiI= -cuelabs.dev/go/oci/ociregistry v0.0.0-20240404174027-a39bec0462d2 h1:BnG6pr9TTr6CYlrJznYUDj6V7xldD1W+1iXPum0wT/w= -cuelabs.dev/go/oci/ociregistry v0.0.0-20240404174027-a39bec0462d2/go.mod h1:pK23AUVXuNzzTpfMCA06sxZGeVQ/75FdVtW249de9Uo= -cuelang.org/go v0.9.2 h1:pfNiry2PdRBr02G/aKm5k2vhzmqbAOoaB4WurmEbWvs= -cuelang.org/go v0.9.2/go.mod h1:qpAYsLOf7gTM1YdEg6cxh553uZ4q9ZDWlPbtZr9q1Wk= +cuelabs.dev/go/oci/ociregistry v0.0.0-20241125120445-2c00c104c6e1 h1:mRwydyTyhtRX2wXS3mqYWzR2qlv6KsmoKXmlz5vInjg= +cuelabs.dev/go/oci/ociregistry v0.0.0-20241125120445-2c00c104c6e1/go.mod h1:5A4xfTzHTXfeVJBU6RAUf+QrlfTCW+017q/QiW+sMLg= +cuelang.org/go v0.12.0 h1:q4W5I+RtDIA27rslQyyt6sWkXX0YS9qm43+U1/3e0kU= +cuelang.org/go v0.12.0/go.mod h1:B4+kjvGGQnbkz+GuAv1dq/R308gTkp0sO28FdMrJ2Kw= dario.cat/mergo v1.0.1 h1:Ra4+bf83h2ztPIQYNP99R6m+Y7KfnARDfID+a+vLl4s= dario.cat/mergo v1.0.1/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk= filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= @@ -29,10 +29,10 @@ github.com/AliyunContainerService/ack-ram-tool/pkg/credentials/provider v0.14.0 github.com/AliyunContainerService/ack-ram-tool/pkg/credentials/provider v0.14.0/go.mod h1:tlqp9mUGbsP+0z3Q+c0Q5MgSdq/OMwQhm5bffR3Q3ss= github.com/Azure/azure-sdk-for-go v68.0.0+incompatible h1:fcYLmCpyNYRnvJbPerq7U0hS+6+I79yEDJBqVNcqUzU= github.com/Azure/azure-sdk-for-go v68.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.16.0 h1:JZg6HRh6W6U4OLl6lk7BZ7BLisIzM9dG1R50zUk9C/M= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.16.0/go.mod h1:YL1xnZ6QejvQHWJrX/AvhFl4WW4rqHVoKspWNVwFk0M= -github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.0 h1:B/dfvscEQtew9dVuoxqxrUKKv8Ih2f55PydknDamU+g= -github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.0/go.mod h1:fiPSssYvltE08HJchL04dOy+RD4hgrjph0cwGGMntdI= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.0 h1:g0EZJwz7xkXQiZAI5xi9f3WWFYBlX1CPTrR+NDToRkQ= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.0/go.mod h1:XCW7KnZet0Opnr7HccfUw1PLc4CjHqpcaxW8DHklNkQ= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.1 h1:1mvYtZfWQAnwNah/C+Z+Jb9rQH95LPE2vlmMuWAHJk8= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.1/go.mod h1:75I/mXtme1JyWFtz8GocPHVFyH421IBoZErnO16dd0k= github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 h1:ywEEhmNahHBihViHepv3xPBn1663uRv2t2q/ESv9seY= github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0/go.mod h1:iZDifYGJTIgIIkYRNWPENUnqx6bJ2xnSDFI2tjwZNuY= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.3.0 h1:7rKG7UmnrxX4N53TFhkYqjc+kVUZuw0fL8I3Fh+Ld9E= @@ -64,8 +64,8 @@ github.com/Azure/go-autorest/logger v0.2.1 h1:IG7i4p/mDa2Ce4TRyAO8IHnVhAVF3RFU+Z github.com/Azure/go-autorest/logger v0.2.1/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8= github.com/Azure/go-autorest/tracing v0.6.0 h1:TYi4+3m5t6K48TGI9AUdb+IzbnSxvnvUMfuitfgcfuo= github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU= -github.com/AzureAD/microsoft-authentication-library-for-go v1.3.1 h1:gUDtaZk8heteyfdmv+pcfHvhR9llnh7c7GMwZ8RVG04= -github.com/AzureAD/microsoft-authentication-library-for-go v1.3.1/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= +github.com/AzureAD/microsoft-authentication-library-for-go v1.3.2 h1:kYRSnvJju5gYVyhkij+RTJ/VR6QIUaCfWeaFm2ycsjQ= +github.com/AzureAD/microsoft-authentication-library-for-go v1.3.2/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= @@ -77,8 +77,8 @@ github.com/ThalesIgnite/crypto11 v1.2.5 h1:1IiIIEqYmBvUYFeMnHqRft4bwf/O36jryEUpY github.com/ThalesIgnite/crypto11 v1.2.5/go.mod h1:ILDKtnCKiQ7zRoNxcp36Y1ZR8LBPmR2E23+wTQe/MlE= github.com/acobaugh/osrelease v0.1.0 h1:Yb59HQDGGNhCj4suHaFQQfBps5wyoKLSSX/J/+UifRE= github.com/acobaugh/osrelease v0.1.0/go.mod h1:4bFEs0MtgHNHBrmHCt67gNisnabCRAlzdVasCEGHTWY= -github.com/agnivade/levenshtein v1.1.1 h1:QY8M92nrzkmr798gCo3kmMyqXFzdQVpxLlGPRBij0P8= -github.com/agnivade/levenshtein v1.1.1/go.mod h1:veldBMzWxcCG2ZvUTKD2kJNRdCk5hVbJomOvKkmgYbo= +github.com/agnivade/levenshtein v1.2.0 h1:U9L4IOT0Y3i0TIlUIDJ7rVUziKi/zPbrJGaFrtYH3SY= +github.com/agnivade/levenshtein v1.2.0/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU= github.com/alessio/shellescape v1.4.1 h1:V7yhSDDn8LP4lc4jS8pFkt0zCnzVJlG5JXy9BVKJUX0= github.com/alessio/shellescape v1.4.1/go.mod h1:PZAiSCk0LJaZkiCSkPv8qIobYglO3FPpyFjDCtHLS30= github.com/alibabacloud-go/alibabacloud-gateway-spi v0.0.2/go.mod h1:sCavSAvdzOjul4cEqeVtvlSaSScfNsTQ+46HwlTL1hc= @@ -131,60 +131,56 @@ github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE= github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= -github.com/aws/aws-sdk-go v1.55.5 h1:KKUZBfBoyqy5d3swXyiC7Q76ic40rYcbqH7qjh59kzU= -github.com/aws/aws-sdk-go v1.55.5/go.mod h1:eRwEWoyTWFMVYVQzKMNHWP5/RV4xIUGMQfXQHfHkpNU= -github.com/aws/aws-sdk-go-v2 v1.21.2/go.mod h1:ErQhvNuEMhJjweavOYhxVkn2RUx7kQXVATHrjKtxIpM= -github.com/aws/aws-sdk-go-v2 v1.32.7 h1:ky5o35oENWi0JYWUZkB7WYvVPP+bcRF5/Iq7JWSb5Rw= -github.com/aws/aws-sdk-go-v2 v1.32.7/go.mod h1:P5WJBrYqqbWVaOxgH0X/FYYD47/nooaPOZPlQdmiN2U= -github.com/aws/aws-sdk-go-v2/config v1.28.7 h1:GduUnoTXlhkgnxTD93g1nv4tVPILbdNQOzav+Wpg7AE= -github.com/aws/aws-sdk-go-v2/config v1.28.7/go.mod h1:vZGX6GVkIE8uECSUHB6MWAUsd4ZcG2Yq/dMa4refR3M= -github.com/aws/aws-sdk-go-v2/credentials v1.17.48 h1:IYdLD1qTJ0zanRavulofmqut4afs45mOWEI+MzZtTfQ= -github.com/aws/aws-sdk-go-v2/credentials v1.17.48/go.mod h1:tOscxHN3CGmuX9idQ3+qbkzrjVIx32lqDSU1/0d/qXs= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.22 h1:kqOrpojG71DxJm/KDPO+Z/y1phm1JlC8/iT+5XRmAn8= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.22/go.mod h1:NtSFajXVVL8TA2QNngagVZmUtXciyrHOt7xgz4faS/M= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.43/go.mod h1:auo+PiyLl0n1l8A0e8RIeR8tOzYPfZZH/JNlrJ8igTQ= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.26 h1:I/5wmGMffY4happ8NOCuIUEWGUvvFp5NSeQcXl9RHcI= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.26/go.mod h1:FR8f4turZtNy6baO0KJ5FJUmXH/cSkI9fOngs0yl6mA= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.37/go.mod h1:Qe+2KtKml+FEsQF/DHmDV+xjtche/hwoF75EG4UlHW8= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.26 h1:zXFLuEuMMUOvEARXFUVJdfqZ4bvvSgdGRq/ATcrQxzM= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.26/go.mod h1:3o2Wpy0bogG1kyOPrgkXA8pgIfEEv0+m19O9D5+W8y8= -github.com/aws/aws-sdk-go-v2/internal/ini v1.8.1 h1:VaRN3TlFdd6KxX1x3ILT5ynH6HvKgqdiXoTxAF4HQcQ= -github.com/aws/aws-sdk-go-v2/internal/ini v1.8.1/go.mod h1:FbtygfRFze9usAadmnGJNc8KsP346kEe+y2/oyhGAGc= -github.com/aws/aws-sdk-go-v2/service/ecr v1.20.2 h1:y6LX9GUoEA3mO0qpFl1ZQHj1rFyPWVphlzebiSt2tKE= -github.com/aws/aws-sdk-go-v2/service/ecr v1.20.2/go.mod h1:Q0LcmaN/Qr8+4aSBrdrXXePqoX0eOuYpJLbYpilmWnA= -github.com/aws/aws-sdk-go-v2/service/ecrpublic v1.18.2 h1:PpbXaecV3sLAS6rjQiaKw4/jyq3Z8gNzmoJupHAoBp0= -github.com/aws/aws-sdk-go-v2/service/ecrpublic v1.18.2/go.mod h1:fUHpGXr4DrXkEDpGAjClPsviWf+Bszeb0daKE0blxv8= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.1 h1:iXtILhvDxB6kPvEXgsDhGaZCSC6LQET5ZHSdJozeI0Y= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.1/go.mod h1:9nu0fVANtYiAePIBh2/pFUSwtJ402hLnp854CNoDOeE= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.7 h1:8eUsivBQzZHqe/3FE+cqwfH+0p5Jo8PFM/QYQSmeZ+M= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.7/go.mod h1:kLPQvGUmxn/fqiCrDeohwG33bq2pQpGeY62yRO6Nrh0= -github.com/aws/aws-sdk-go-v2/service/kms v1.37.8 h1:KbLZjYqhQ9hyB4HwXiheiflTlYQa0+Fz0Ms/rh5f3mk= -github.com/aws/aws-sdk-go-v2/service/kms v1.37.8/go.mod h1:ANs9kBhK4Ghj9z1W+bsr3WsNaPF71qkgd6eE6Ekol/Y= -github.com/aws/aws-sdk-go-v2/service/sso v1.24.8 h1:CvuUmnXI7ebaUAhbJcDy9YQx8wHR69eZ9I7q5hszt/g= -github.com/aws/aws-sdk-go-v2/service/sso v1.24.8/go.mod h1:XDeGv1opzwm8ubxddF0cgqkZWsyOtw4lr6dxwmb6YQg= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.7 h1:F2rBfNAL5UyswqoeWv9zs74N/NanhK16ydHW1pahX6E= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.7/go.mod h1:JfyQ0g2JG8+Krq0EuZNnRwX0mU0HrwY/tG6JNfcqh4k= -github.com/aws/aws-sdk-go-v2/service/sts v1.33.3 h1:Xgv/hyNgvLda/M9l9qxXc4UFSgppnRczLxlMs5Ae/QY= -github.com/aws/aws-sdk-go-v2/service/sts v1.33.3/go.mod h1:5Gn+d+VaaRgsjewpMvGazt0WfcFO+Md4wLOuBfGR9Bc= -github.com/aws/smithy-go v1.15.0/go.mod h1:Tg+OJXh4MB2R/uN61Ko2f6hTZwB/ZYGOtib8J3gBHzA= -github.com/aws/smithy-go v1.22.1 h1:/HPHZQ0g7f4eUeK6HKglFz8uwVfZKgoI25rb/J+dnro= -github.com/aws/smithy-go v1.22.1/go.mod h1:irrKGvNn1InZwb2d7fkIRNucdfwR8R+Ts3wxYa/cJHg= -github.com/awslabs/amazon-ecr-credential-helper/ecr-login v0.0.0-20231024185945-8841054dbdb8 h1:SoFYaT9UyGkR0+nogNyD/Lj+bsixB+SNuAS4ABlEs6M= -github.com/awslabs/amazon-ecr-credential-helper/ecr-login v0.0.0-20231024185945-8841054dbdb8/go.mod h1:2JF49jcDOrLStIXN/j/K1EKRq8a8R2qRnlZA6/o/c7c= +github.com/aws/aws-sdk-go v1.55.6 h1:cSg4pvZ3m8dgYcgqB97MrcdjUmZ1BeMYKUxMMB89IPk= +github.com/aws/aws-sdk-go v1.55.6/go.mod h1:eRwEWoyTWFMVYVQzKMNHWP5/RV4xIUGMQfXQHfHkpNU= +github.com/aws/aws-sdk-go-v2 v1.36.1 h1:iTDl5U6oAhkNPba0e1t1hrwAo02ZMqbrGq4k5JBWM5E= +github.com/aws/aws-sdk-go-v2 v1.36.1/go.mod h1:5PMILGVKiW32oDzjj6RU52yrNrDPUHcbZQYr1sM7qmM= +github.com/aws/aws-sdk-go-v2/config v1.29.6 h1:fqgqEKK5HaZVWLQoLiC9Q+xDlSp+1LYidp6ybGE2OGg= +github.com/aws/aws-sdk-go-v2/config v1.29.6/go.mod h1:Ft+WLODzDQmCTHDvqAH1JfC2xxbZ0MxpZAcJqmE1LTQ= +github.com/aws/aws-sdk-go-v2/credentials v1.17.59 h1:9btwmrt//Q6JcSdgJOLI98sdr5p7tssS9yAsGe8aKP4= +github.com/aws/aws-sdk-go-v2/credentials v1.17.59/go.mod h1:NM8fM6ovI3zak23UISdWidyZuI1ghNe2xjzUZAyT+08= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.28 h1:KwsodFKVQTlI5EyhRSugALzsV6mG/SGrdjlMXSZSdso= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.28/go.mod h1:EY3APf9MzygVhKuPXAc5H+MkGb8k/DOSQjWS0LgkKqI= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.32 h1:BjUcr3X3K0wZPGFg2bxOWW3VPN8rkE3/61zhP+IHviA= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.32/go.mod h1:80+OGC/bgzzFFTUmcuwD0lb4YutwQeKLFpmt6hoWapU= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.32 h1:m1GeXHVMJsRsUAqG6HjZWx9dj7F5TR+cF1bjyfYyBd4= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.32/go.mod h1:IitoQxGfaKdVLNg0hD8/DXmAqNy0H4K2H2Sf91ti8sI= +github.com/aws/aws-sdk-go-v2/internal/ini v1.8.2 h1:Pg9URiobXy85kgFev3og2CuOZ8JZUBENF+dcgWBaYNk= +github.com/aws/aws-sdk-go-v2/internal/ini v1.8.2/go.mod h1:FbtygfRFze9usAadmnGJNc8KsP346kEe+y2/oyhGAGc= +github.com/aws/aws-sdk-go-v2/service/ecr v1.40.3 h1:a+210FCU/pR5hhKRaskRfX/ogcyyzFBrehcTk5DTAyU= +github.com/aws/aws-sdk-go-v2/service/ecr v1.40.3/go.mod h1:dtD3a4sjUjVL86e0NUvaqdGvds5ED6itUiZPDaT+Gh8= +github.com/aws/aws-sdk-go-v2/service/ecrpublic v1.31.2 h1:E6/Myrj9HgLF22medmDrKmbpm4ULsa+cIBNx3phirBk= +github.com/aws/aws-sdk-go-v2/service/ecrpublic v1.31.2/go.mod h1:OQ8NALFcchBJ/qruak6zKUQodovnTKKaReTuCkc5/9Y= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.2 h1:D4oz8/CzT9bAEYtVhSBmFj2dNOtaHOtMKc2vHBwYizA= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.2/go.mod h1:Za3IHqTQ+yNcRHxu1OFucBh0ACZT4j4VQFF0BqpZcLY= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.13 h1:SYVGSFQHlchIcy6e7x12bsrxClCXSP5et8cqVhL8cuw= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.13/go.mod h1:kizuDaLX37bG5WZaoxGPQR/LNFXpxp0vsUnqfkWXfNE= +github.com/aws/aws-sdk-go-v2/service/kms v1.37.18 h1:pi9M/9n1PLayBXjia7LfwgXwcpFdFO7Q2cqKOZa1ZmM= +github.com/aws/aws-sdk-go-v2/service/kms v1.37.18/go.mod h1:vZXvmzfhdsPj/axc8+qk/2fSCP4hGyaZ1MAduWEHAxM= +github.com/aws/aws-sdk-go-v2/service/sso v1.24.15 h1:/eE3DogBjYlvlbhd2ssWyeuovWunHLxfgw3s/OJa4GQ= +github.com/aws/aws-sdk-go-v2/service/sso v1.24.15/go.mod h1:2PCJYpi7EKeA5SkStAmZlF6fi0uUABuhtF8ILHjGc3Y= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.14 h1:M/zwXiL2iXUrHputuXgmO94TVNmcenPHxgLXLutodKE= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.14/go.mod h1:RVwIw3y/IqxC2YEXSIkAzRDdEU1iRabDPaYjpGCbCGQ= +github.com/aws/aws-sdk-go-v2/service/sts v1.33.14 h1:TzeR06UCMUq+KA3bDkujxK1GVGy+G8qQN/QVYzGLkQE= +github.com/aws/aws-sdk-go-v2/service/sts v1.33.14/go.mod h1:dspXf/oYWGWo6DEvj98wpaTeqt5+DMidZD0A9BYTizc= +github.com/aws/smithy-go v1.22.2 h1:6D9hW43xKFrRx/tXXfAlIZc4JI+yQe6snnWcQyxSyLQ= +github.com/aws/smithy-go v1.22.2/go.mod h1:irrKGvNn1InZwb2d7fkIRNucdfwR8R+Ts3wxYa/cJHg= +github.com/awslabs/amazon-ecr-credential-helper/ecr-login v0.9.1 h1:50sS0RWhGpW/yZx2KcDNEb1u1MANv5BMEkJgcieEDTA= +github.com/awslabs/amazon-ecr-credential-helper/ecr-login v0.9.1/go.mod h1:ErZOtbzuHabipRTDTor0inoRlYwbsV1ovwSxjGs/uJo= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/blang/semver v3.5.1+incompatible h1:cQNTCjp13qL8KC3Nbxr/y2Bqb63oX6wdnnjpJbkM4JQ= github.com/blang/semver v3.5.1+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk= github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM= github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= -github.com/buildkite/agent/v3 v3.81.0 h1:JVfkng2XnsXesFXwiFwLJFkuzVu4zvoJCvedfoIXD6E= -github.com/buildkite/agent/v3 v3.81.0/go.mod h1:edJeyycODRxaFvpT22rDGwaQ5oa4eB8GjtbjgX5VpFw= -github.com/buildkite/go-pipeline v0.13.1 h1:Y9p8pQIwPtauVwNrcmTDH6+XK7jE1nLuvWVaK8oymA8= -github.com/buildkite/go-pipeline v0.13.1/go.mod h1:2HHqlSFTYgHFhzedJu0LhLs9n5c9XkYnHiQFVN5HE4U= -github.com/buildkite/interpolate v0.1.3 h1:OFEhqji1rNTRg0u9DsSodg63sjJQEb1uWbENq9fUOBM= -github.com/buildkite/interpolate v0.1.3/go.mod h1:UNVe6A+UfiBNKbhAySrBbZFZFxQ+DXr9nWen6WVt/A8= -github.com/buildkite/roko v1.2.0 h1:hbNURz//dQqNl6Eo9awjQOVOZwSDJ8VEbBDxSfT9rGQ= -github.com/buildkite/roko v1.2.0/go.mod h1:23R9e6nHxgedznkwwfmqZ6+0VJZJZ2Sg/uVcp2cP46I= +github.com/buildkite/agent/v3 v3.92.1 h1:6HLdDbU5z6ZyJ3TCt/UQEcLv2nhg/gdS4ApnsrUwhOE= +github.com/buildkite/agent/v3 v3.92.1/go.mod h1:mUNebi1cYh66iBjqVdJTgEn+sm53x8zC/XQQfpZSk9A= +github.com/buildkite/go-pipeline v0.13.3 h1:llI7sAdZ7sqYE7r8ePlmDADRhJ1K0Kua2+gv74Z9+Es= +github.com/buildkite/go-pipeline v0.13.3/go.mod h1:1uC2XdHkTV1G5jYv9K8omERIwrsYbBruBrPx1Zu1uFw= +github.com/buildkite/interpolate v0.1.5 h1:v2Ji3voik69UZlbfoqzx+qfcsOKLA61nHdU79VV+tPU= +github.com/buildkite/interpolate v0.1.5/go.mod h1:dHnrwHew5O8VNOAgMDpwRlFnhL5VSN6M1bHVmRZ9Ccc= +github.com/buildkite/roko v1.3.1 h1:t7K30ceLLYn6k7hQP4oq1c7dVlhgD5nRcuSRDEEnY1s= +github.com/buildkite/roko v1.3.1/go.mod h1:23R9e6nHxgedznkwwfmqZ6+0VJZJZ2Sg/uVcp2cP46I= github.com/bwesterb/go-ristretto v1.2.3/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0= github.com/bytecodealliance/wasmtime-go/v3 v3.0.2 h1:3uZCA/BLTIu+DqCfguByNMJa2HVHpXvjfy0Dy7g6fuA= github.com/bytecodealliance/wasmtime-go/v3 v3.0.2/go.mod h1:RnUjnIXxEJcL6BgCvNyzCCRzZcxCgsZCi+RNlvYor5Q= @@ -193,8 +189,6 @@ github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyY github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cert-manager/cert-manager v1.17.1 h1:Aig+lWMoLsmpGd9TOlTvO4t0Ah3D+/vGB37x/f+ZKt0= github.com/cert-manager/cert-manager v1.17.1/go.mod h1:zeG4D+AdzqA7hFMNpYCJgcQ2VOfFNBa+Jzm3kAwiDU4= -github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= -github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= 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/chrismellard/docker-credential-acr-env v0.0.0-20230304212654-82a0ddb27589 h1:krfRl01rzPzxSxyLyrChD+U+MzsBXbm0OwYYB67uF+4= @@ -224,7 +218,6 @@ github.com/coreos/go-oidc/v3 v3.12.0 h1:sJk+8G2qq94rDI6ehZ71Bol3oUHy63qNYmkiSjrc github.com/coreos/go-oidc/v3 v3.12.0/go.mod h1:gE3LgjOgFoHi9a4ce4/tJczr0Ai2/BoDhf0r5lltWI0= github.com/coreos/go-systemd/v22 v22.5.0 h1:RrqgGjYQKalulkV8NGVIfkXQf6YYmOyiJKk8iXXhfZs= github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= -github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/cpuguy83/go-md2man/v2 v2.0.6 h1:XJtiaUW6dEEqVuZiMTn1ldk455QWwEIsMIJlo5vtkx0= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/creack/pty v1.1.19 h1:tUN6H7LWqNx4hQVxomd0CVsDwaDr9gaRQaI4GpSmrsA= @@ -241,12 +234,12 @@ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1 github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/depcheck-test/depcheck-test v0.0.0-20220607135614-199033aaa936 h1:foGzavPWwtoyBvjWyKJYDYsyzy+23iBV7NKTwdk+LRY= github.com/depcheck-test/depcheck-test v0.0.0-20220607135614-199033aaa936/go.mod h1:ttKPnOepYt4LLzD+loXQ1rT6EmpyIYHro7TAJuIIlHo= -github.com/dgraph-io/badger/v3 v3.2103.5 h1:ylPa6qzbjYRQMU6jokoj4wzcaweHylt//CH0AKt0akg= -github.com/dgraph-io/badger/v3 v3.2103.5/go.mod h1:4MPiseMeDQ3FNCYwRbbcBOGJLf5jsE0PPFzRiKjtcdw= -github.com/dgraph-io/ristretto v0.1.1 h1:6CWw5tJNgpegArSHpNHJKldNeq03FQCwYvfMVWajOK8= -github.com/dgraph-io/ristretto v0.1.1/go.mod h1:S1GPSBCYCIhmVNfcth17y2zZtQT6wzkzgwUve0VDWWA= -github.com/dgryski/trifles v0.0.0-20200323201526-dd97f9abfb48 h1:fRzb/w+pyskVMQ+UbP35JkH8yB7MYb4q/qhBarqZE6g= -github.com/dgryski/trifles v0.0.0-20200323201526-dd97f9abfb48/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA= +github.com/dgraph-io/badger/v4 v4.5.1 h1:7DCIXrQjo1LKmM96YD+hLVJ2EEsyyoWxJfpdd56HLps= +github.com/dgraph-io/badger/v4 v4.5.1/go.mod h1:qn3Be0j3TfV4kPbVoK0arXCD1/nr1ftth6sbL5jxdoA= +github.com/dgraph-io/ristretto/v2 v2.1.0 h1:59LjpOJLNDULHh8MC4UaegN52lC4JnO2dITsie/Pa8I= +github.com/dgraph-io/ristretto/v2 v2.1.0/go.mod h1:uejeqfYXpUomfse0+lO+13ATz4TypQYLJZzBSAemuB4= +github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54 h1:SG7nF6SRlWhcT7cNTs5R6Hk4V2lcmLz2NsG2VnInyNo= +github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA= github.com/digitorus/pkcs7 v0.0.0-20230713084857-e76b763bdc49/go.mod h1:SKVExuS+vpu2l9IoOc0RwqE7NYnb0JlcFHFnEJkVDzc= github.com/digitorus/pkcs7 v0.0.0-20230818184609-3a137a874352 h1:ge14PCmCvPjpMQMIAH7uKg0lrtNSOdpYsRXlwk3QbaE= github.com/digitorus/pkcs7 v0.0.0-20230818184609-3a137a874352/go.mod h1:SKVExuS+vpu2l9IoOc0RwqE7NYnb0JlcFHFnEJkVDzc= @@ -264,8 +257,8 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/emicklei/go-restful/v3 v3.12.1 h1:PJMDIM/ak7btuL8Ex0iYET9hxM3CI2sjZtzpL63nKAU= github.com/emicklei/go-restful/v3 v3.12.1/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= -github.com/emicklei/proto v1.12.1 h1:6n/Z2pZAnBwuhU66Gs8160B8rrrYKo7h2F2sCOnNceE= -github.com/emicklei/proto v1.12.1/go.mod h1:rn1FgRS/FANiZdD2djyH7TMA9jdRDcYQ9IEN9yvjX0A= +github.com/emicklei/proto v1.13.4 h1:myn1fyf8t7tAqIzV91Tj9qXpvyXXGXk8OS2H6IBSc9g= +github.com/emicklei/proto v1.13.4/go.mod h1:rn1FgRS/FANiZdD2djyH7TMA9jdRDcYQ9IEN9yvjX0A= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= @@ -326,8 +319,8 @@ github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+Gr github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ= github.com/go-openapi/validate v0.24.0 h1:LdfDKwNbpB6Vn40xhTdNZAnfLECL81w+VX3BumrGD58= github.com/go-openapi/validate v0.24.0/go.mod h1:iyeX1sEufmv3nPbBdX3ieNviWnOZaJ1+zquzJEf2BAQ= -github.com/go-piv/piv-go v1.11.0 h1:5vAaCdRTFSIW4PeqMbnsDlUZ7odMYWnHBDGdmtU/Zhg= -github.com/go-piv/piv-go v1.11.0/go.mod h1:NZ2zmjVkfFaL/CF8cVQ/pXdXtuj110zEKGdJM6fJZZM= +github.com/go-piv/piv-go/v2 v2.3.0 h1:kKkrYlgLQTMPA6BiSL25A7/x4CEh2YCG7rtb/aTkx+g= +github.com/go-piv/piv-go/v2 v2.3.0/go.mod h1:ShZi74nnrWNQEdWzRUd/3cSig3uNOcEZp+EWl0oewnI= github.com/go-quicktest/qt v1.101.0 h1:O1K29Txy5P2OK0dGo59b7b0LR6wKfIhttaAhHUyn7eI= github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow= github.com/go-rod/rod v0.116.2 h1:A5t2Ky2A+5eD/ZJQr1EfsQSe5rms5Xof/qj296e+ZqA= @@ -357,8 +350,6 @@ github.com/golang-jwt/jwt/v4 v4.5.1/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/glog v1.2.3 h1:oDTdz9f5VGVVNGu/Q7UXKWYsD0873HXLHdJUNBsSEKM= -github.com/golang/glog v1.2.3/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w= github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= @@ -381,10 +372,10 @@ github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= github.com/google/cel-go v0.22.1 h1:AfVXx3chM2qwoSbM7Da8g8hX8OVSkBFwX+rz2+PcK40= github.com/google/cel-go v0.22.1/go.mod h1:BuznPXXfQDpXKWQ9sPW3TzlAJN5zzFe+i9tIs0yC4s8= -github.com/google/certificate-transparency-go v1.2.1 h1:4iW/NwzqOqYEEoCBEFP+jPbBXbLqMpq3CifMyOnDUME= -github.com/google/certificate-transparency-go v1.2.1/go.mod h1:bvn/ytAccv+I6+DGkqpvSsEdiVGramgaSC6RD3tEmeE= -github.com/google/flatbuffers v2.0.8+incompatible h1:ivUb1cGomAB101ZM1T0nOiWz9pSrTMoa9+EiY7igmkM= -github.com/google/flatbuffers v2.0.8+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= +github.com/google/certificate-transparency-go v1.3.1 h1:akbcTfQg0iZlANZLn0L9xOeWtyCIdeoYhKrqi5iH3Go= +github.com/google/certificate-transparency-go v1.3.1/go.mod h1:gg+UQlx6caKEDQ9EElFOujyxEQEfOiQzAt6782Bvi8k= +github.com/google/flatbuffers v24.12.23+incompatible h1:ubBKR94NR4pXUCY/MUsRVzd9umNW7ht7EG9hHfS9FX8= +github.com/google/flatbuffers v24.12.23+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= github.com/google/gnostic-models v0.6.9 h1:MU/8wDLif2qCXZmzncUQ/BOfxWfthHi63KqpoNbWqVw= github.com/google/gnostic-models v0.6.9/go.mod h1:CiWsm0s6BSQd1hRn8/QmxqB6BesYcbSZxsz9b0KuDBw= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= @@ -393,7 +384,6 @@ github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= @@ -409,8 +399,8 @@ github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/ github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad h1:a6HEuzUHeKH6hwfN/ZoQgRgVIWFJljSWa/zetS2WTvg= github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= -github.com/google/s2a-go v0.1.8 h1:zZDs9gcbt9ZPLV0ndSyQk6Kacx2g/X+SKYovpnz3SMM= -github.com/google/s2a-go v0.1.8/go.mod h1:6iNWHTpQ+nfNRN5E00MSdfDwVesa8hhS32PhPO8deJA= +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/tink/go v1.7.0 h1:6Eox8zONGebBFcCBqkVmt60LaWZa6xg1cl/DwAh/J1w= github.com/google/tink/go v1.7.0/go.mod h1:GAUOd+QE3pgj9q8VKIGTCP33c/B7eb4NhxLcgTJZStM= github.com/google/trillian v1.7.1 h1:+zX8jLM3524bAMPS+VxaDIDgsMv3/ty6DuLWerHXcek= @@ -453,8 +443,8 @@ github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/hashicorp/hcl v1.0.1-vault-5 h1:kI3hhbbyzr4dldA8UdTb7ZlVVlI2DACdCfz31RPDgJM= github.com/hashicorp/hcl v1.0.1-vault-5/go.mod h1:XYhtn6ijBSAj6n4YqAaf7RBPS4I06AItNorpy+MoQNM= -github.com/hashicorp/vault/api v1.15.0 h1:O24FYQCWwhwKnF7CuSqP30S51rTV7vz1iACXE/pj5DA= -github.com/hashicorp/vault/api v1.15.0/go.mod h1:+5YTO09JGn0u+b6ySD/LLVf8WkJCPLAL2Vkmrn2+CM8= +github.com/hashicorp/vault/api v1.16.0 h1:nbEYGJiAPGzT9U4oWgaaB0g+Rj8E59QuHKyA5LhwQN4= +github.com/hashicorp/vault/api v1.16.0/go.mod h1:KhuUhzOD8lDSk29AtzNjgAu2kxRA9jL9NAbkFlqvkBA= github.com/howeyc/gopass v0.0.0-20210920133722-c8aef6fb66ef h1:A9HsByNhogrvm9cWb28sjiS3i7tcKCkflWFEkHfuAgM= github.com/howeyc/gopass v0.0.0-20210920133722-c8aef6fb66ef/go.mod h1:lADxMC39cJJqL93Duh1xhAs4I2Zs8mKS89XWXFGp9cs= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= @@ -465,15 +455,22 @@ github.com/in-toto/in-toto-golang v0.9.0 h1:tHny7ac4KgtsfrG6ybU8gVOZux2H8jN05AXJ github.com/in-toto/in-toto-golang v0.9.0/go.mod h1:xsBVrVsHNsB61++S6Dy2vWosKhuA3lUTQd+eF9HdeMo= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/jackc/pgerrcode v0.0.0-20240316143900-6e2875d9b438 h1:Dj0L5fhJ9F82ZJyVOmBx6msDp/kfd1t9GRfny/mfJA0= +github.com/jackc/pgerrcode v0.0.0-20240316143900-6e2875d9b438/go.mod h1:a/s9Lp5W7n/DD0VrVoyJ00FbP2ytTPDVOivvn2bMlds= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.7.2 h1:mLoDLV6sonKlvjIEsV56SkWNCnuNv531l94GaIzO+XI= +github.com/jackc/pgx/v5 v5.7.2/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jedisct1/go-minisign v0.0.0-20230811132847-661be99b8267 h1:TMtDYDHKYY15rFihtRfck/bfFqNfvcabqvXAFQfAUpY= github.com/jedisct1/go-minisign v0.0.0-20230811132847-661be99b8267/go.mod h1:h1nSAbGFqGVzn6Jyl1R/iCcBUHN4g+gW1u9CoBTrb9E= github.com/jellydator/ttlcache/v3 v3.3.0 h1:BdoC9cE81qXfrxeb9eoJi9dWrdhSuwXMAnHTbnBm4Wc= github.com/jellydator/ttlcache/v3 v3.3.0/go.mod h1:bj2/e0l4jRnQdrnSTaGTsh4GSXvMjQcy41i7th0GVGw= -github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= github.com/jmespath/go-jmespath v0.4.1-0.20220621161143-b0104c826a24 h1:liMMTbpW34dhU4az1GN0pTPADwNmvoRSeoZ6PItiqnY= github.com/jmespath/go-jmespath v0.4.1-0.20220621161143-b0104c826a24/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= -github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= -github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= github.com/jmhodges/clock v1.2.0 h1:eq4kys+NI0PLngzaHEe7AmPT90XMGIEySD1JfV1PDIs= github.com/jmhodges/clock v1.2.0/go.mod h1:qKjhA7x7u/lQpPB1XAqX1b1lCI/w3/fNuYpI/ZjLynI= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= @@ -501,8 +498,8 @@ github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de h1:9TO3cAIGXtEhnIaL+V+BEER86oLrvS+kWobKpbJuye0= github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de/go.mod h1:zAbeS9B/r2mtpb6U+EI2rYA5OAXxsYw6wTamcNW+zcE= -github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= -github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= +github.com/magiconair/properties v1.8.9 h1:nWcCbLq1N2v/cpNsy5WvQ37Fb+YElfq20WJ/a8RkpQM= +github.com/magiconair/properties v1.8.9/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= github.com/mailru/easyjson v0.9.0 h1:PrnmzHw7262yW8sTBwxi1PdJA3Iw/EKBa8psRf7d9a4= github.com/mailru/easyjson v0.9.0/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= @@ -521,8 +518,8 @@ github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= -github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= -github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/mitchellh/mapstructure v1.5.1-0.20231216201459-8508981c8b6c h1:cqn374mizHuIWj+OSJCajGr/phAmuMug9qIX3l9CflE= +github.com/mitchellh/mapstructure v1.5.1-0.20231216201459-8508981c8b6c/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/moby/sys/mountinfo v0.7.2 h1:1shs6aH5s4o5H2zQLn796ADW1wMrIwHsyJ2v9KouLrg= github.com/moby/sys/mountinfo v0.7.2/go.mod h1:1YOa8w8Ih7uW0wALDUgT1dTTSBrZ+HiBLGws92L2RU4= github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g= @@ -567,8 +564,8 @@ github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAl github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro= github.com/onsi/gomega v1.36.2 h1:koNYke6TVk6ZmnyHrCXba/T/MoLBXFjeC1PtvYgw0A8= github.com/onsi/gomega v1.36.2/go.mod h1:DdwyADRjrc825LhMEkD76cHR5+pUnjhUN8GlHlRPHzY= -github.com/open-policy-agent/opa v0.68.0 h1:Jl3U2vXRjwk7JrHmS19U3HZO5qxQRinQbJ2eCJYSqJQ= -github.com/open-policy-agent/opa v0.68.0/go.mod h1:5E5SvaPwTpwt2WM177I9Z3eT7qUpmOGjk1ZdHs+TZ4w= +github.com/open-policy-agent/opa v1.1.0 h1:HMz2evdEMTyNqtdLjmu3Vyx06BmhNYAx67Yz3Ll9q2s= +github.com/open-policy-agent/opa v1.1.0/go.mod h1:T1pASQ1/vwfTa+e2fYcfpLCvWgYtqtiUv+IuA/dLPQs= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug= @@ -587,8 +584,8 @@ github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+ github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= github.com/pborman/uuid v1.2.1 h1:+ZZIw58t/ozdjRaXh/3awHfmWRbzYxJoAdNJxe/3pvw= github.com/pborman/uuid v1.2.1/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= -github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= -github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= +github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= +github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= github.com/pjbgf/go-apparmor v0.1.3-0.20241107184909-1375e5e7aa89 h1:wBXahBOWK72QV3tnaMNtbAGnOAH0a/n0lpgxruYirWs= github.com/pjbgf/go-apparmor v0.1.3-0.20241107184909-1375e5e7aa89/go.mod h1:AXUw6FFDoh4deKxcQ883jqJMnEnA/b1oU5nU29i2lPA= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= @@ -611,12 +608,12 @@ github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I= github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= -github.com/protocolbuffers/txtpbfmt v0.0.0-20231025115547-084445ff1adf h1:014O62zIzQwvoD7Ekj3ePDF5bv9Xxy0w6AZk0qYbjUk= -github.com/protocolbuffers/txtpbfmt v0.0.0-20231025115547-084445ff1adf/go.mod h1:jgxiZysxFPM+iWKwQwPR+y+Jvo54ARd4EisXxKYpB5c= +github.com/protocolbuffers/txtpbfmt v0.0.0-20241112170944-20d2c9ebc01d h1:HWfigq7lB31IeJL8iy7jkUmU/PG1Sr8jVGhS749dbUA= +github.com/protocolbuffers/txtpbfmt v0.0.0-20241112170944-20d2c9ebc01d/go.mod h1:jgxiZysxFPM+iWKwQwPR+y+Jvo54ARd4EisXxKYpB5c= github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM= github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= -github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= -github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= +github.com/rogpeppe/go-internal v1.13.2-0.20241226121412-a5dc8ff20d0a h1:w3tdWGKbLGBPtR/8/oO74W6hmz0qE5q0z9aqSAewaaM= +github.com/rogpeppe/go-internal v1.13.2-0.20241226121412-a5dc8ff20d0a/go.mod h1:S8kfXMp+yh77OxPD4fdM6YUknrZpQxLhvxzS4gDHENY= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/go-glob v1.0.0 h1:iQh3xXAumdQ+4Ufa5b25cRpC5TYKlno6hsv6Cb3pkBk= @@ -641,34 +638,32 @@ github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8= github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I= github.com/shibumi/go-pathspec v1.3.0 h1:QUyMZhFo0Md5B8zV8x2tesohbb5kfbpTi9rBnKh5dkI= github.com/shibumi/go-pathspec v1.3.0/go.mod h1:Xutfslp817l2I1cZvgcfeMQJG5QnU2lh5tVaaMCl3jE= -github.com/sigstore/cosign/v2 v2.4.1 h1:b8UXEfJFks3hmTwyxrRNrn6racpmccUycBHxDMkEPvU= -github.com/sigstore/cosign/v2 v2.4.1/go.mod h1:GvzjBeUKigI+XYnsoVQDmMAsMMc6engxztRSuxE+x9I= -github.com/sigstore/fulcio v1.6.4 h1:d86obfxUAG3Y6CYwOx1pdwCZwKmROB6w6927pKOVIRY= -github.com/sigstore/fulcio v1.6.4/go.mod h1:Y6bn3i3KGhXpaHsAtYP3Z4Np0+VzCo1fLv8Ci6mbPDs= -github.com/sigstore/protobuf-specs v0.3.3 h1:RMZQgXTD/pF7KW6b5NaRLYxFYZ/wzx44PQFXN2PEo5g= -github.com/sigstore/protobuf-specs v0.3.3/go.mod h1:vIhZ6Uor1a38+wvRrKcqL2PtYNlgoIW9lhzYzkyy4EU= -github.com/sigstore/rekor v1.3.8 h1:B8kJI8mpSIXova4Jxa6vXdJyysRxFGsEsLKBDl0rRjA= -github.com/sigstore/rekor v1.3.8/go.mod h1:/dHFYKSuxEygfDRnEwyJ+ZD6qoVYNXQdi1mJrKvKWsI= -github.com/sigstore/sigstore v1.8.12 h1:S8xMVZbE2z9ZBuQUEG737pxdLjnbOIcFi5v9UFfkJFc= -github.com/sigstore/sigstore v1.8.12/go.mod h1:+PYQAa8rfw0QdPpBcT+Gl3egKD9c+TUgAlF12H3Nmjo= -github.com/sigstore/sigstore-go v0.6.1 h1:tGkkv1oDIER+QYU5MrjqlttQOVDWfSkmYwMqkJhB/cg= -github.com/sigstore/sigstore-go v0.6.1/go.mod h1:Xe5GHmUeACRFbomUWzVkf/xYCn8xVifb9DgqJrV2dIw= -github.com/sigstore/sigstore/pkg/signature/kms/aws v1.8.12 h1:EC3UmIaa7nV9sCgSpVevmvgvTYTkMqyrRbj5ojPp7tE= -github.com/sigstore/sigstore/pkg/signature/kms/aws v1.8.12/go.mod h1:aw60vs3crnQdM/DYH+yF2P0MVKtItwAX34nuaMrY7Lk= -github.com/sigstore/sigstore/pkg/signature/kms/azure v1.8.12 h1:FPpliDTywSy0woLHMAdmTSZ5IS/lVBZ0dY0I+2HmnSY= -github.com/sigstore/sigstore/pkg/signature/kms/azure v1.8.12/go.mod h1:NkPiz4XA0JcBSXzJUrjMj7Xi7oSTew1Ip3Zmt56mHlw= -github.com/sigstore/sigstore/pkg/signature/kms/gcp v1.8.12 h1:kweBChR6M9FEvmxN3BMEcl7SNnwxTwKF7THYFKLOE5U= -github.com/sigstore/sigstore/pkg/signature/kms/gcp v1.8.12/go.mod h1:6+d+A6oYt1W5OgtzgEVb21V7tAZ/C2Ihtzc5MNJbayY= -github.com/sigstore/sigstore/pkg/signature/kms/hashivault v1.8.12 h1:jvY1B9bjP+tKzdKDyuq5K7O19CG2IKzGJNTy5tuL2Gs= -github.com/sigstore/sigstore/pkg/signature/kms/hashivault v1.8.12/go.mod h1:2uEeOb8xE2RC6OvzxKux1wkS39Zv8gA27z92m49xUTc= -github.com/sigstore/timestamp-authority v1.2.2 h1:X4qyutnCQqJ0apMewFyx+3t7Tws00JQ/JonBiu3QvLE= -github.com/sigstore/timestamp-authority v1.2.2/go.mod h1:nEah4Eq4wpliDjlY342rXclGSO7Kb9hoRrl9tqLW13A= +github.com/sigstore/cosign/v2 v2.4.3 h1:UAU/6Z33gVBCV01b2l1fdvMml9IJTrsDiYQDB5K+sQI= +github.com/sigstore/cosign/v2 v2.4.3/go.mod h1:6vZ2vHarfJB3N4FHYV/5M1qdHiWi2PM1c8ogNPCe2jA= +github.com/sigstore/fulcio v1.6.6 h1:XaMYX6TNT+8n7Npe8D94nyZ7/ERjEsNGFC+REdi/wzw= +github.com/sigstore/fulcio v1.6.6/go.mod h1:BhQ22lwaebDgIxVBEYOOqLRcN5+xOV+C9bh/GUXRhOk= +github.com/sigstore/protobuf-specs v0.4.0 h1:yoZbdh0kZYKOSiVbYyA8J3f2wLh5aUk2SQB7LgAfIdU= +github.com/sigstore/protobuf-specs v0.4.0/go.mod h1:FKW5NYhnnFQ/Vb9RKtQk91iYd0MKJ9AxyqInEwU6+OI= +github.com/sigstore/rekor v1.3.9 h1:sUjRpKVh/hhgqGMs0t+TubgYsksArZ6poLEC3MsGAzU= +github.com/sigstore/rekor v1.3.9/go.mod h1:xThNUhm6eNEmkJ/SiU/FVU7pLY2f380fSDZFsdDWlcM= +github.com/sigstore/sigstore v1.8.15 h1:9HHnZmxjPQSTPXTCZc25HDxxSTWwsGMh/ZhWZZ39maU= +github.com/sigstore/sigstore v1.8.15/go.mod h1:+Wa5mrG6A+Gss516YC9owy10q3IazqIRe0y1EoQRHHM= +github.com/sigstore/sigstore-go v0.7.0 h1:bIGPc2IbnbxnzlqQcKlh1o96bxVJ4yRElpP1gHrOH48= +github.com/sigstore/sigstore-go v0.7.0/go.mod h1:4RrCK+i+jhx7lyOG2Vgef0/kFLbKlDI1hrioUYvkxxA= +github.com/sigstore/sigstore/pkg/signature/kms/aws v1.8.15 h1:g/hPoaemFv/6ZJIRyb5I1lA4qU9PZwCTu/GkvFV5jEw= +github.com/sigstore/sigstore/pkg/signature/kms/aws v1.8.15/go.mod h1:n2yKi/b29+JB54PyONruHvvha4zugC7jzr+A16cNLvw= +github.com/sigstore/sigstore/pkg/signature/kms/azure v1.8.15 h1:K2GstKWXftcpmg/wHfcJFYKWuj+YRSoTgwxm3ox2FjE= +github.com/sigstore/sigstore/pkg/signature/kms/azure v1.8.15/go.mod h1:tOSdKYXCkplk54FSR/58UYQm1S/GlQK4Y1GgMhiq40U= +github.com/sigstore/sigstore/pkg/signature/kms/gcp v1.8.15 h1:ThpZMfR2TecI6Ji7s/nFlcCIkwXYhZUYziJdZs3pOaw= +github.com/sigstore/sigstore/pkg/signature/kms/gcp v1.8.15/go.mod h1:x+4wvq6tzIQRZaSdMS6/VT9nuCoepypozfzP4Tqwnqw= +github.com/sigstore/sigstore/pkg/signature/kms/hashivault v1.8.15 h1:mR+VaOSx2sUpaE8lXarinHcT8UXi+fKE4ESNBzDRAtQ= +github.com/sigstore/sigstore/pkg/signature/kms/hashivault v1.8.15/go.mod h1:6olKNL2BGrsZPLbO/7kiJzZPxU74270nDI5G3HSSykw= +github.com/sigstore/timestamp-authority v1.2.4 h1:RjXZxOWorEiem/uSr0pFHVtQpyzpcFxgugo5jVqm3mw= +github.com/sigstore/timestamp-authority v1.2.4/go.mod h1:ExrbobKdEuwuBptZIiKp1IaVBRiUeKbiuSyZTO8Okik= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 h1:JIAuq3EEf9cgbU6AtGPK4CTG3Zf6CKMNqf0MHTggAUA= github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966/go.mod h1:sUM3LWHvSMaG192sy56D9F7CNvL7jUJVXoqM1QKLnog= -github.com/smallstep/assert v0.0.0-20200723003110-82e2b9b3b262 h1:unQFBIznI+VYD1/1fApl1A+9VcBk+9dcqGfnePY87LY= -github.com/smallstep/assert v0.0.0-20200723003110-82e2b9b3b262/go.mod h1:MyOHs9Po2fbM1LHej6sBUT8ozbxmMOFG+E+rx/GSGuc= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/assertions v1.1.0/go.mod h1:tcbTF8ujkAEcZ8TElKY+i30BzYlVhC/LOxJk7iOWnoo= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= @@ -679,23 +674,21 @@ github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= github.com/spf13/cast v1.7.0 h1:ntdiHjuueXFgm5nzDRdOS4yfT43P5Fnud6DH50rz/7w= github.com/spf13/cast v1.7.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= -github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= -github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= +github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo= +github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= -github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI= github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg= -github.com/spiffe/go-spiffe/v2 v2.3.0 h1:g2jYNb/PDMB8I7mBGL2Zuq/Ur6hUhoroxGQFyD6tTj8= -github.com/spiffe/go-spiffe/v2 v2.3.0/go.mod h1:Oxsaio7DBgSNqhAO9i/9tLClaVlfRok7zvJnTV8ZyIY= +github.com/spiffe/go-spiffe/v2 v2.5.0 h1:N2I01KCUkv1FAjZXJMwh95KK1ZIQLYbPfhaxw8WS0hE= +github.com/spiffe/go-spiffe/v2 v2.5.0/go.mod h1:P+NxobPc6wXhVtINNtFjNWGBTreew1GBUCwT2wPmb7g= github.com/stoewer/go-strcase v1.3.0 h1:g0eASXYtp+yvN9fK8sH94oCIk0fau9uV1/ZdJ0AVEzs= github.com/stoewer/go-strcase v1.3.0/go.mod h1:fAH5hQ5pehh+j3nZfvwdk2RgEgQjAoM8wodgtPmh1xo= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= @@ -705,8 +698,6 @@ github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1F github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= -github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= @@ -721,8 +712,14 @@ github.com/thales-e-security/pool v0.0.2 h1:RAPs4q2EbWsTit6tpzuvTFlgFRJ3S8Evf5gt github.com/thales-e-security/pool v0.0.2/go.mod h1:qtpMm2+thHtqhLzTwgDBj/OuNnMpupY8mv0Phz0gjhU= github.com/theupdateframework/go-tuf v0.7.0 h1:CqbQFrWo1ae3/I0UCblSbczevCCbS31Qvs5LdxRWqRI= github.com/theupdateframework/go-tuf v0.7.0/go.mod h1:uEB7WSY+7ZIugK6R1hiBMBjQftaFzn7ZCDJcp1tCUug= -github.com/theupdateframework/go-tuf/v2 v2.0.1 h1:11p9tXpq10KQEujxjcIjDSivMKCMLguls7erXHZnxJQ= -github.com/theupdateframework/go-tuf/v2 v2.0.1/go.mod h1:baB22nBHeHBCeuGZcIlctNq4P61PcOdyARlplg5xmLA= +github.com/theupdateframework/go-tuf/v2 v2.0.2 h1:PyNnjV9BJNzN1ZE6BcWK+5JbF+if370jjzO84SS+Ebo= +github.com/theupdateframework/go-tuf/v2 v2.0.2/go.mod h1:baB22nBHeHBCeuGZcIlctNq4P61PcOdyARlplg5xmLA= +github.com/tink-crypto/tink-go-awskms/v2 v2.1.0 h1:N9UxlsOzu5mttdjhxkDLbzwtEecuXmlxZVo/ds7JKJI= +github.com/tink-crypto/tink-go-awskms/v2 v2.1.0/go.mod h1:PxSp9GlOkKL9rlybW804uspnHuO9nbD98V/fDX4uSis= +github.com/tink-crypto/tink-go-gcpkms/v2 v2.2.0 h1:3B9i6XBXNTRspfkTC0asN5W0K6GhOSgcujNiECNRNb0= +github.com/tink-crypto/tink-go-gcpkms/v2 v2.2.0/go.mod h1:jY5YN2BqD/KSCHM9SqZPIpJNG/u3zwfLXHgws4x2IRw= +github.com/tink-crypto/tink-go/v2 v2.3.0 h1:4/TA0lw0lA/iVKBL9f8R5eP7397bfc4antAMXF5JRhs= +github.com/tink-crypto/tink-go/v2 v2.3.0/go.mod h1:kfPOtXIadHlekBTeBtJrHWqoGL+Fm3JQg0wtltPuxLU= github.com/titanous/rocacheck v0.0.0-20171023193734-afe73141d399 h1:e/5i7d4oYZ+C1wj2THlRK+oAhjeS/TRQwMfkIuet3w0= github.com/titanous/rocacheck v0.0.0-20171023193734-afe73141d399/go.mod h1:LdwHTNJT99C5fTAzDz0ud328OgXz+gierycbcIx2fRs= github.com/tjfoc/gmsm v1.3.2/go.mod h1:HaUcFuY0auTiaHB9MHFGCPx5IaLhTUd2atbCFBQXn9w= @@ -736,8 +733,6 @@ github.com/vbatts/tar-split v0.11.7 h1:ixZ93pO/GmvaZw4Vq9OwmfZK/kc2zKdPfu0B+gYqs github.com/vbatts/tar-split v0.11.7/go.mod h1:eF6B6i6ftWQcDqEn3/iGFRFRo8cBIMSJVOpnNdfTMFA= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= -github.com/xanzy/go-gitlab v0.109.0 h1:RcRme5w8VpLXTSTTMZdVoQWY37qTJWg+gwdQl4aAttE= -github.com/xanzy/go-gitlab v0.109.0/go.mod h1:wKNKh3GkYDMOsGmnfuX+ITCmDuSDWFO0G+C4AygL9RY= github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= @@ -762,8 +757,10 @@ github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9dec github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/zalando/go-keyring v0.2.3 h1:v9CUu9phlABObO4LPWycf+zwMG7nlbb3t/B5wa97yms= github.com/zalando/go-keyring v0.2.3/go.mod h1:HL4k+OXQfJUWaMnqyuSOc0drfGPX2b51Du6K+MRgZMk= -github.com/zeebo/errs v1.3.0 h1:hmiaKqgYZzcVgRL1Vkc1Mn2914BbzB0IBxs+ebeutGs= -github.com/zeebo/errs v1.3.0/go.mod h1:sgbWHsvVuTPHcqJJGQ1WhI5KbWlHYz+2+2C/LSEtCw4= +github.com/zeebo/errs v1.4.0 h1:XNdoD/RRMKP7HD0UhJnIzUy74ISdGGxURlYG8HSWSfM= +github.com/zeebo/errs v1.4.0/go.mod h1:sgbWHsvVuTPHcqJJGQ1WhI5KbWlHYz+2+2C/LSEtCw4= +gitlab.com/gitlab-org/api/client-go v0.123.0 h1:W3LZ5QNyiSCJA0Zchkwz8nQIUzOuDoSWMZtRDT5DjPI= +gitlab.com/gitlab-org/api/client-go v0.123.0/go.mod h1:Jh0qjLILEdbO6z/OY94RD+3NDQRUKiuFSFYozN6cpKM= go.mongodb.org/mongo-driver v1.14.0 h1:P98w8egYRjYe3XDjxhYJagTokP/H6HzlsnojRgZRd80= go.mongodb.org/mongo-driver v1.14.0/go.mod h1:Vzb0Mk/pa7e6cWw85R4F/endUC3u0U9jGcNU603k65c= go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= @@ -772,26 +769,26 @@ go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJyS go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.58.0 h1:PS8wXpbyaDJQ2VDHHncMe9Vct0Zn1fEjpsjrLxGJoSc= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.58.0/go.mod h1:HDBUsEjOuRC0EzKZ1bSaRGZWUBAzo+MhAcUUORSr4D0= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0 h1:yd02MEjBdJkG3uabWP9apV+OuWRIXGDuJEUJbOHmCFU= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0/go.mod h1:umTcuxiv1n/s/S6/c2AT/g2CQ7u5C59sHDNmfSwgz7Q= -go.opentelemetry.io/otel v1.33.0 h1:/FerN9bax5LoK51X/sI0SVYrjSE0/yUL7DpxW4K3FWw= -go.opentelemetry.io/otel v1.33.0/go.mod h1:SUUkR6csvUQl+yjReHu5uM3EtVV7MBm5FHKRlNx4I8I= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.33.0 h1:Vh5HayB/0HHfOQA7Ctx69E/Y/DcQSMPpKANYVMQ7fBA= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.33.0/go.mod h1:cpgtDBaqD/6ok/UG0jT15/uKjAY8mRA53diogHBg3UI= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.33.0 h1:5pojmb1U1AogINhN3SurB+zm/nIcusopeBNp42f45QM= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.33.0/go.mod h1:57gTHJSE5S1tqg+EKsLPlTWhpHMsWlVmer+LA926XiA= -go.opentelemetry.io/otel/metric v1.33.0 h1:r+JOocAyeRVXD8lZpjdQjzMadVZp2M4WmQ+5WtEnklQ= -go.opentelemetry.io/otel/metric v1.33.0/go.mod h1:L9+Fyctbp6HFTddIxClbQkjtubW6O9QS3Ann/M82u6M= -go.opentelemetry.io/otel/sdk v1.33.0 h1:iax7M131HuAm9QkZotNHEfstof92xM+N8sr3uHXc2IM= -go.opentelemetry.io/otel/sdk v1.33.0/go.mod h1:A1Q5oi7/9XaMlIWzPSxLRWOI8nG3FnzHJNbiENQuihM= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0 h1:CV7UdSGJt/Ao6Gp4CXckLxVRRsRgDHoI8XjbL3PDl8s= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0/go.mod h1:FRmFuRJfag1IZ2dPkHnEoSFVgTVPUd2qf5Vi69hLb8I= +go.opentelemetry.io/otel v1.34.0 h1:zRLXxLCgL1WyKsPVrgbSdMN4c0FMkDAskSTQP+0hdUY= +go.opentelemetry.io/otel v1.34.0/go.mod h1:OWFPOQ+h4G8xpyjgqo4SxJYdDQ/qmRH+wivy7zzx9oI= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.34.0 h1:OeNbIYk/2C15ckl7glBlOBp5+WlYsOElzTNmiPW/x60= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.34.0/go.mod h1:7Bept48yIeqxP2OZ9/AqIpYS94h2or0aB4FypJTc8ZM= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.34.0 h1:tgJ0uaNS4c98WRNUEx5U3aDlrDOI5Rs+1Vifcw4DJ8U= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.34.0/go.mod h1:U7HYyW0zt/a9x5J1Kjs+r1f/d4ZHnYFclhYY2+YbeoE= +go.opentelemetry.io/otel/metric v1.34.0 h1:+eTR3U0MyfWjRDhmFMxe2SsW64QrZ84AOhvqS7Y+PoQ= +go.opentelemetry.io/otel/metric v1.34.0/go.mod h1:CEDrp0fy2D0MvkXE+dPV7cMi8tWZwX3dmaIhwPOaqHE= +go.opentelemetry.io/otel/sdk v1.34.0 h1:95zS4k/2GOy069d321O8jWgYsW3MzVV+KuSPKp7Wr1A= +go.opentelemetry.io/otel/sdk v1.34.0/go.mod h1:0e/pNiaMAqaykJGKbi+tSjWfNNHMTxoC9qANsCzbyxU= go.opentelemetry.io/otel/sdk/metric v1.32.0 h1:rZvFnvmvawYb0alrYkjraqJq0Z4ZUJAiyYCU9snn1CU= go.opentelemetry.io/otel/sdk/metric v1.32.0/go.mod h1:PWeZlq0zt9YkYAp3gjKZ0eicRYvOh1Gd+X99x6GHpCQ= -go.opentelemetry.io/otel/trace v1.33.0 h1:cCJuF7LRjUFso9LPnEAHJDB2pqzp+hbO8eu1qqW2d/s= -go.opentelemetry.io/otel/trace v1.33.0/go.mod h1:uIcdVUZMpTAmz0tI1z04GoVSezK37CbGV4fr1f2nBck= -go.opentelemetry.io/proto/otlp v1.4.0 h1:TA9WRvW6zMwP+Ssb6fLoUIuirti1gGbP28GcKG1jgeg= -go.opentelemetry.io/proto/otlp v1.4.0/go.mod h1:PPBWZIP98o2ElSqI35IHfu7hIhSwvc5N38Jw8pXuGFY= -go.step.sm/crypto v0.56.0 h1:KcFfV76cI9Xaw8bdSc9x55skyuSdcHcTdL37vvVZnvY= -go.step.sm/crypto v0.56.0/go.mod h1:snWNloxY9s1W+HsFqcviq55nvzbqqX6LxVt0Vktv5mw= +go.opentelemetry.io/otel/trace v1.34.0 h1:+ouXS2V8Rd4hp4580a8q23bg0azF2nI8cqLYnC8mh/k= +go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h0M2jHBhmSfRE= +go.opentelemetry.io/proto/otlp v1.5.0 h1:xJvq7gMzB31/d406fB8U5CBdyQGw4P399D1aQWU/3i4= +go.opentelemetry.io/proto/otlp v1.5.0/go.mod h1:keN8WnHxOy8PG0rQZjJJ5A2ebUoafqWp0eVQ4yIXvJ4= +go.step.sm/crypto v0.57.0 h1:YjoRQDaJYAxHLVwjst0Bl0xcnoKzVwuHCJtEo2VSHYU= +go.step.sm/crypto v0.57.0/go.mod h1:+Lwp5gOVPaTa3H/Ul/TzGbxQPXZZcKIUGMS0lG6n9Go= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= @@ -855,8 +852,8 @@ golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8= golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.25.0 h1:CY4y7XT9v0cRI9oupztF8AgiIu99L/ksR/Xp/6jrZ70= -golang.org/x/oauth2 v0.25.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= +golang.org/x/oauth2 v0.26.0 h1:afQXWNNaeC4nvZ0Ed9XvCCzXM6UHJG7iCg0W4fPqSBE= +golang.org/x/oauth2 v0.26.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -926,8 +923,8 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= -golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY= -golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/time v0.10.0 h1:3usCWA8tQn0L8+hFJQNgzpWbd89begxN66o1Ojdn5L4= +golang.org/x/time v0.10.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= @@ -951,18 +948,18 @@ golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= gomodules.xyz/jsonpatch/v2 v2.4.0 h1:Ci3iUJyx9UeRx7CeFN8ARgGbkESwJK+KB9lLcWxY/Zw= gomodules.xyz/jsonpatch/v2 v2.4.0/go.mod h1:AH3dM2RI6uoBZxn3LVrfvJ3E0/9dG4cSrbuBJT4moAY= -google.golang.org/api v0.216.0 h1:xnEHy+xWFrtYInWPy8OdGFsyIfWJjtVnO39g7pz2BFY= -google.golang.org/api v0.216.0/go.mod h1:K9wzQMvWi47Z9IU7OgdOofvZuw75Ge3PPITImZR/UyI= +google.golang.org/api v0.221.0 h1:qzaJfLhDsbMeFee8zBRdt/Nc+xmOuafD/dbdgGfutOU= +google.golang.org/api v0.221.0/go.mod h1:7sOU2+TL4TxUTdbi0gWgAIg7tH5qBXxoyhtL+9x3biQ= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20241118233622-e639e219e697 h1:ToEetK57OidYuqD4Q5w+vfEnPvPpuTwedCNVohYJfNk= google.golang.org/genproto v0.0.0-20241118233622-e639e219e697/go.mod h1:JJrvXBWRZaFMxBufik1a4RpFw4HhgVtBBWQeQgUj2cc= -google.golang.org/genproto/googleapis/api v0.0.0-20241219192143-6b3ec007d9bb h1:B7GIB7sr443wZ/EAEl7VZjmh1V6qzkt5V+RYcUYtS1U= -google.golang.org/genproto/googleapis/api v0.0.0-20241219192143-6b3ec007d9bb/go.mod h1:E5//3O5ZIG2l71Xnt+P/CYUY8Bxs8E7WMoZ9tlcMbAY= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250102185135-69823020774d h1:xJJRGY7TJcvIlpSrN3K6LAWgNFUILlO+OMAqtg9aqnw= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250102185135-69823020774d/go.mod h1:3ENsm/5D1mzDyhpzeRi1NR784I0BcofWBoSc5QqqMK4= +google.golang.org/genproto/googleapis/api v0.0.0-20250115164207-1a7da9e5054f h1:gap6+3Gk41EItBuyi4XX/bp4oqJ3UwuIMl25yGinuAA= +google.golang.org/genproto/googleapis/api v0.0.0-20250115164207-1a7da9e5054f/go.mod h1:Ic02D47M+zbarjYYUlK57y316f2MoN0gjAwI3f2S95o= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250207221924-e9438ea467c6 h1:2duwAxN2+k0xLNpjnHTXoMUgnv6VPSp5fiqTuwSxjmI= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250207221924-e9438ea467c6/go.mod h1:8BS3B93F/U1juMFq9+EDk+qOT5CO1R9IzXxG3PTqiRk= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= @@ -1005,8 +1002,8 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= -gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU= -gotest.tools/v3 v3.5.1/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU= +gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q= +gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= k8s.io/api v0.32.2 h1:bZrMLEkgizC24G9eViHGOPbW+aRo9duEISRIJKfdJuw= diff --git a/vendor/cloud.google.com/go/auth/CHANGES.md b/vendor/cloud.google.com/go/auth/CHANGES.md index 39a47c85eb..18131a9c70 100644 --- a/vendor/cloud.google.com/go/auth/CHANGES.md +++ b/vendor/cloud.google.com/go/auth/CHANGES.md @@ -1,5 +1,26 @@ # Changelog +## [0.14.1](https://github.com/googleapis/google-cloud-go/compare/auth/v0.14.0...auth/v0.14.1) (2025-01-24) + + +### Documentation + +* **auth:** Add warning about externally-provided credentials ([#11462](https://github.com/googleapis/google-cloud-go/issues/11462)) ([49fb6ff](https://github.com/googleapis/google-cloud-go/commit/49fb6ff4d754895f82c9c4d502fc7547d3b5a941)) + +## [0.14.0](https://github.com/googleapis/google-cloud-go/compare/auth/v0.13.0...auth/v0.14.0) (2025-01-08) + + +### Features + +* **auth:** Add universe domain support to idtoken ([#11059](https://github.com/googleapis/google-cloud-go/issues/11059)) ([72add7e](https://github.com/googleapis/google-cloud-go/commit/72add7e9f8f455af695e8ef79212a4bd3122fb3a)) + + +### Bug Fixes + +* **auth/oauth2adapt:** Update golang.org/x/net to v0.33.0 ([e9b0b69](https://github.com/googleapis/google-cloud-go/commit/e9b0b69644ea5b276cacff0a707e8a5e87efafc9)) +* **auth:** Fix copy of delegates in impersonate.NewIDTokenCredentials ([#11386](https://github.com/googleapis/google-cloud-go/issues/11386)) ([ff7ef8e](https://github.com/googleapis/google-cloud-go/commit/ff7ef8e7ade7171bce3e4f30ff10a2e9f6c27ca0)), refs [#11379](https://github.com/googleapis/google-cloud-go/issues/11379) +* **auth:** Update golang.org/x/net to v0.33.0 ([e9b0b69](https://github.com/googleapis/google-cloud-go/commit/e9b0b69644ea5b276cacff0a707e8a5e87efafc9)) + ## [0.13.0](https://github.com/googleapis/google-cloud-go/compare/auth/v0.12.1...auth/v0.13.0) (2024-12-13) diff --git a/vendor/cloud.google.com/go/auth/credentials/detect.go b/vendor/cloud.google.com/go/auth/credentials/detect.go index a1b5a93188..b84a90a830 100644 --- a/vendor/cloud.google.com/go/auth/credentials/detect.go +++ b/vendor/cloud.google.com/go/auth/credentials/detect.go @@ -149,10 +149,26 @@ type DetectOptions struct { // CredentialsFile overrides detection logic and sources a credential file // from the provided filepath. If provided, CredentialsJSON must not be. // Optional. + // + // Important: If you accept a credential configuration (credential + // JSON/File/Stream) from an external source for authentication to Google + // Cloud Platform, you must validate it before providing it to any Google + // API or library. Providing an unvalidated credential configuration to + // Google APIs can compromise the security of your systems and data. For + // more information, refer to [Validate credential configurations from + // external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials). CredentialsFile string // CredentialsJSON overrides detection logic and uses the JSON bytes as the // source for the credential. If provided, CredentialsFile must not be. // Optional. + // + // Important: If you accept a credential configuration (credential + // JSON/File/Stream) from an external source for authentication to Google + // Cloud Platform, you must validate it before providing it to any Google + // API or library. Providing an unvalidated credential configuration to + // Google APIs can compromise the security of your systems and data. For + // more information, refer to [Validate credential configurations from + // external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials). CredentialsJSON []byte // UseSelfSignedJWT directs service account based credentials to create a // self-signed JWT with the private key found in the file, skipping any diff --git a/vendor/cloud.google.com/go/auth/credentials/idtoken/file.go b/vendor/cloud.google.com/go/auth/credentials/idtoken/file.go index 2cde8164d2..87fab751fb 100644 --- a/vendor/cloud.google.com/go/auth/credentials/idtoken/file.go +++ b/vendor/cloud.google.com/go/auth/credentials/idtoken/file.go @@ -22,6 +22,7 @@ import ( "cloud.google.com/go/auth" "cloud.google.com/go/auth/credentials/impersonate" + intimpersonate "cloud.google.com/go/auth/credentials/internal/impersonate" "cloud.google.com/go/auth/internal" "cloud.google.com/go/auth/internal/credsfile" "github.com/googleapis/gax-go/v2/internallog" @@ -44,38 +45,31 @@ func credsFromDefault(creds *auth.Credentials, opts *Options) (*auth.Credentials if err != nil { return nil, err } - opts2LO := &auth.Options2LO{ - Email: f.ClientEmail, - PrivateKey: []byte(f.PrivateKey), - PrivateKeyID: f.PrivateKeyID, - TokenURL: f.TokenURL, - UseIDToken: true, - Logger: internallog.New(opts.Logger), - } - if opts2LO.TokenURL == "" { - opts2LO.TokenURL = jwtTokenURL - } - - var customClaims map[string]interface{} - if opts != nil { - customClaims = opts.CustomClaims - } - if customClaims == nil { - customClaims = make(map[string]interface{}) - } - customClaims["target_audience"] = opts.Audience - - opts2LO.PrivateClaims = customClaims - tp, err := auth.New2LOTokenProvider(opts2LO) - if err != nil { - return nil, err + var tp auth.TokenProvider + if resolveUniverseDomain(f) == internal.DefaultUniverseDomain { + tp, err = new2LOTokenProvider(f, opts) + if err != nil { + return nil, err + } + } else { + // In case of non-GDU universe domain, use IAM. + tp = intimpersonate.IDTokenIAMOptions{ + Client: opts.client(), + Logger: internallog.New(opts.Logger), + // Pass the credentials universe domain to configure the endpoint. + UniverseDomain: auth.CredentialsPropertyFunc(creds.UniverseDomain), + ServiceAccountEmail: f.ClientEmail, + GenerateIDTokenRequest: intimpersonate.GenerateIDTokenRequest{ + Audience: opts.Audience, + }, + } } tp = auth.NewCachedTokenProvider(tp, nil) return auth.NewCredentials(&auth.CredentialsOptions{ TokenProvider: tp, JSON: b, - ProjectIDProvider: internal.StaticCredentialsProperty(f.ProjectID), - UniverseDomainProvider: internal.StaticCredentialsProperty(f.UniverseDomain), + ProjectIDProvider: auth.CredentialsPropertyFunc(creds.ProjectID), + UniverseDomainProvider: auth.CredentialsPropertyFunc(creds.UniverseDomain), }), nil case credsfile.ImpersonatedServiceAccountKey, credsfile.ExternalAccountKey: type url struct { @@ -110,3 +104,39 @@ func credsFromDefault(creds *auth.Credentials, opts *Options) (*auth.Credentials return nil, fmt.Errorf("idtoken: unsupported credentials type: %v", t) } } + +func new2LOTokenProvider(f *credsfile.ServiceAccountFile, opts *Options) (auth.TokenProvider, error) { + opts2LO := &auth.Options2LO{ + Email: f.ClientEmail, + PrivateKey: []byte(f.PrivateKey), + PrivateKeyID: f.PrivateKeyID, + TokenURL: f.TokenURL, + UseIDToken: true, + Logger: internallog.New(opts.Logger), + } + if opts2LO.TokenURL == "" { + opts2LO.TokenURL = jwtTokenURL + } + + var customClaims map[string]interface{} + if opts != nil { + customClaims = opts.CustomClaims + } + if customClaims == nil { + customClaims = make(map[string]interface{}) + } + customClaims["target_audience"] = opts.Audience + + opts2LO.PrivateClaims = customClaims + return auth.New2LOTokenProvider(opts2LO) +} + +// resolveUniverseDomain returns the default service domain for a given +// Cloud universe. This is the universe domain configured for the credentials, +// which will be used in endpoint. +func resolveUniverseDomain(f *credsfile.ServiceAccountFile) string { + if f.UniverseDomain != "" { + return f.UniverseDomain + } + return internal.DefaultUniverseDomain +} diff --git a/vendor/cloud.google.com/go/auth/credentials/idtoken/idtoken.go b/vendor/cloud.google.com/go/auth/credentials/idtoken/idtoken.go index 2e9a5d3ede..9c84636941 100644 --- a/vendor/cloud.google.com/go/auth/credentials/idtoken/idtoken.go +++ b/vendor/cloud.google.com/go/auth/credentials/idtoken/idtoken.go @@ -78,14 +78,35 @@ type Options struct { // CredentialsFile sources a JSON credential file from the provided // filepath. If provided, do not provide CredentialsJSON. Optional. + // + // Important: If you accept a credential configuration (credential + // JSON/File/Stream) from an external source for authentication to Google + // Cloud Platform, you must validate it before providing it to any Google + // API or library. Providing an unvalidated credential configuration to + // Google APIs can compromise the security of your systems and data. For + // more information, refer to [Validate credential configurations from + // external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials). CredentialsFile string // CredentialsJSON sources a JSON credential file from the provided bytes. // If provided, do not provide CredentialsJSON. Optional. + // + // Important: If you accept a credential configuration (credential + // JSON/File/Stream) from an external source for authentication to Google + // Cloud Platform, you must validate it before providing it to any Google + // API or library. Providing an unvalidated credential configuration to + // Google APIs can compromise the security of your systems and data. For + // more information, refer to [Validate credential configurations from + // external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials). CredentialsJSON []byte // Client configures the underlying client used to make network requests // when fetching tokens. If provided this should be a fully-authenticated // client. Optional. Client *http.Client + // UniverseDomain is the default service domain for a given Cloud universe. + // The default value is "googleapis.com". This is the universe domain + // configured for the client, which will be compared to the universe domain + // that is separately configured for the credentials. Optional. + UniverseDomain string // Logger is used for debug logging. If provided, logging will be enabled // at the loggers configured level. By default logging is disabled unless // enabled by setting GOOGLE_SDK_GO_LOGGING_LEVEL in which case a default diff --git a/vendor/cloud.google.com/go/auth/credentials/impersonate/idtoken.go b/vendor/cloud.google.com/go/auth/credentials/impersonate/idtoken.go index 835b8f8d2d..6c470822bd 100644 --- a/vendor/cloud.google.com/go/auth/credentials/impersonate/idtoken.go +++ b/vendor/cloud.google.com/go/auth/credentials/impersonate/idtoken.go @@ -15,17 +15,13 @@ package impersonate import ( - "bytes" - "context" - "encoding/json" "errors" - "fmt" "log/slog" "net/http" - "time" "cloud.google.com/go/auth" "cloud.google.com/go/auth/credentials" + "cloud.google.com/go/auth/credentials/internal/impersonate" "cloud.google.com/go/auth/httptransport" "cloud.google.com/go/auth/internal" "github.com/googleapis/gax-go/v2/internallog" @@ -57,6 +53,11 @@ type IDTokenOptions struct { // when fetching tokens. If provided this should be a fully-authenticated // client. Optional. Client *http.Client + // UniverseDomain is the default service domain for a given Cloud universe. + // The default value is "googleapis.com". This is the universe domain + // configured for the client, which will be compared to the universe domain + // that is separately configured for the credentials. Optional. + UniverseDomain string // Logger is used for debug logging. If provided, logging will be enabled // at the loggers configured level. By default logging is disabled unless // enabled by setting GOOGLE_SDK_GO_LOGGING_LEVEL in which case a default @@ -90,14 +91,12 @@ func NewIDTokenCredentials(opts *IDTokenOptions) (*auth.Credentials, error) { if err := opts.validate(); err != nil { return nil, err } - client := opts.Client creds := opts.Credentials logger := internallog.New(opts.Logger) if client == nil { var err error if creds == nil { - // TODO: test not signed jwt more creds, err = credentials.DetectDefault(&credentials.DetectOptions{ Scopes: []string{defaultScope}, UseSelfSignedJWT: true, @@ -108,89 +107,35 @@ func NewIDTokenCredentials(opts *IDTokenOptions) (*auth.Credentials, error) { } } client, err = httptransport.NewClient(&httptransport.Options{ - Credentials: creds, - Logger: logger, + Credentials: creds, + UniverseDomain: opts.UniverseDomain, + Logger: logger, }) if err != nil { return nil, err } } - itp := impersonatedIDTokenProvider{ - client: client, - targetPrincipal: opts.TargetPrincipal, - audience: opts.Audience, - includeEmail: opts.IncludeEmail, - logger: logger, - } + universeDomainProvider := resolveUniverseDomainProvider(creds) + var delegates []string for _, v := range opts.Delegates { - itp.delegates = append(itp.delegates, formatIAMServiceAccountName(v)) + delegates = append(delegates, internal.FormatIAMServiceAccountResource(v)) } - var udp auth.CredentialsPropertyProvider - if creds != nil { - udp = auth.CredentialsPropertyFunc(creds.UniverseDomain) + iamOpts := impersonate.IDTokenIAMOptions{ + Client: client, + Logger: logger, + // Pass the credentials universe domain provider to configure the endpoint. + UniverseDomain: universeDomainProvider, + ServiceAccountEmail: opts.TargetPrincipal, + GenerateIDTokenRequest: impersonate.GenerateIDTokenRequest{ + Audience: opts.Audience, + IncludeEmail: opts.IncludeEmail, + Delegates: delegates, + }, } return auth.NewCredentials(&auth.CredentialsOptions{ - TokenProvider: auth.NewCachedTokenProvider(itp, nil), - UniverseDomainProvider: udp, + TokenProvider: auth.NewCachedTokenProvider(iamOpts, nil), + UniverseDomainProvider: universeDomainProvider, }), nil } - -type generateIDTokenRequest struct { - Audience string `json:"audience"` - IncludeEmail bool `json:"includeEmail"` - Delegates []string `json:"delegates,omitempty"` -} - -type generateIDTokenResponse struct { - Token string `json:"token"` -} - -type impersonatedIDTokenProvider struct { - client *http.Client - logger *slog.Logger - - targetPrincipal string - audience string - includeEmail bool - delegates []string -} - -func (i impersonatedIDTokenProvider) Token(ctx context.Context) (*auth.Token, error) { - genIDTokenReq := generateIDTokenRequest{ - Audience: i.audience, - IncludeEmail: i.includeEmail, - Delegates: i.delegates, - } - bodyBytes, err := json.Marshal(genIDTokenReq) - if err != nil { - return nil, fmt.Errorf("impersonate: unable to marshal request: %w", err) - } - - url := fmt.Sprintf("%s/v1/%s:generateIdToken", iamCredentialsEndpoint, formatIAMServiceAccountName(i.targetPrincipal)) - req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(bodyBytes)) - if err != nil { - return nil, fmt.Errorf("impersonate: unable to create request: %w", err) - } - req.Header.Set("Content-Type", "application/json") - i.logger.DebugContext(ctx, "impersonated idtoken request", "request", internallog.HTTPRequest(req, bodyBytes)) - resp, body, err := internal.DoRequest(i.client, req) - if err != nil { - return nil, fmt.Errorf("impersonate: unable to generate ID token: %w", err) - } - i.logger.DebugContext(ctx, "impersonated idtoken response", "response", internallog.HTTPResponse(resp, body)) - if c := resp.StatusCode; c < 200 || c > 299 { - return nil, fmt.Errorf("impersonate: status code %d: %s", c, body) - } - - var generateIDTokenResp generateIDTokenResponse - if err := json.Unmarshal(body, &generateIDTokenResp); err != nil { - return nil, fmt.Errorf("impersonate: unable to parse response: %w", err) - } - return &auth.Token{ - Value: generateIDTokenResp.Token, - // Generated ID tokens are good for one hour. - Expiry: time.Now().Add(1 * time.Hour), - }, nil -} diff --git a/vendor/cloud.google.com/go/auth/credentials/impersonate/impersonate.go b/vendor/cloud.google.com/go/auth/credentials/impersonate/impersonate.go index 715b6b569d..7d8efd54ef 100644 --- a/vendor/cloud.google.com/go/auth/credentials/impersonate/impersonate.go +++ b/vendor/cloud.google.com/go/auth/credentials/impersonate/impersonate.go @@ -34,7 +34,6 @@ import ( var ( universeDomainPlaceholder = "UNIVERSE_DOMAIN" - iamCredentialsEndpoint = "https://iamcredentials.googleapis.com" iamCredentialsUniverseDomainEndpoint = "https://iamcredentials.UNIVERSE_DOMAIN" oauth2Endpoint = "https://oauth2.googleapis.com" errMissingTargetPrincipal = errors.New("impersonate: target service account must be provided") @@ -109,7 +108,7 @@ func NewCredentials(opts *CredentialsOptions) (*auth.Credentials, error) { logger: logger, } for _, v := range opts.Delegates { - its.delegates = append(its.delegates, formatIAMServiceAccountName(v)) + its.delegates = append(its.delegates, internal.FormatIAMServiceAccountResource(v)) } its.scopes = make([]string, len(opts.Scopes)) copy(its.scopes, opts.Scopes) @@ -215,10 +214,6 @@ func (o *CredentialsOptions) validate() error { return nil } -func formatIAMServiceAccountName(name string) string { - return fmt.Sprintf("projects/-/serviceAccounts/%s", name) -} - type generateAccessTokenRequest struct { Delegates []string `json:"delegates,omitempty"` Lifetime string `json:"lifetime,omitempty"` @@ -231,7 +226,8 @@ type generateAccessTokenResponse struct { } type impersonatedTokenProvider struct { - client *http.Client + client *http.Client + // universeDomain is used for endpoint construction. universeDomainProvider auth.CredentialsPropertyProvider logger *slog.Logger @@ -257,7 +253,7 @@ func (i impersonatedTokenProvider) Token(ctx context.Context) (*auth.Token, erro return nil, err } endpoint := strings.Replace(iamCredentialsUniverseDomainEndpoint, universeDomainPlaceholder, universeDomain, 1) - url := fmt.Sprintf("%s/v1/%s:generateAccessToken", endpoint, formatIAMServiceAccountName(i.targetPrincipal)) + url := fmt.Sprintf("%s/v1/%s:generateAccessToken", endpoint, internal.FormatIAMServiceAccountResource(i.targetPrincipal)) req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(b)) if err != nil { return nil, fmt.Errorf("impersonate: unable to create request: %w", err) diff --git a/vendor/cloud.google.com/go/auth/credentials/impersonate/user.go b/vendor/cloud.google.com/go/auth/credentials/impersonate/user.go index be21d22076..e5e1d65028 100644 --- a/vendor/cloud.google.com/go/auth/credentials/impersonate/user.go +++ b/vendor/cloud.google.com/go/auth/credentials/impersonate/user.go @@ -31,6 +31,10 @@ import ( "github.com/googleapis/gax-go/v2/internallog" ) +var ( + iamCredentialsEndpoint = "https://iamcredentials.googleapis.com" +) + // user provides an auth flow for domain-wide delegation, setting // CredentialsConfig.Subject to be the impersonated user. func user(opts *CredentialsOptions, client *http.Client, lifetime time.Duration, isStaticToken bool, universeDomainProvider auth.CredentialsPropertyProvider) (auth.TokenProvider, error) { @@ -47,7 +51,7 @@ func user(opts *CredentialsOptions, client *http.Client, lifetime time.Duration, } u.delegates = make([]string, len(opts.Delegates)) for i, v := range opts.Delegates { - u.delegates[i] = formatIAMServiceAccountName(v) + u.delegates[i] = internal.FormatIAMServiceAccountResource(v) } u.scopes = make([]string, len(opts.Scopes)) copy(u.scopes, opts.Scopes) @@ -143,7 +147,7 @@ func (u userTokenProvider) signJWT(ctx context.Context) (string, error) { if err != nil { return "", fmt.Errorf("impersonate: unable to marshal request: %w", err) } - reqURL := fmt.Sprintf("%s/v1/%s:signJwt", iamCredentialsEndpoint, formatIAMServiceAccountName(u.targetPrincipal)) + reqURL := fmt.Sprintf("%s/v1/%s:signJwt", iamCredentialsEndpoint, internal.FormatIAMServiceAccountResource(u.targetPrincipal)) req, err := http.NewRequestWithContext(ctx, "POST", reqURL, bytes.NewReader(bodyBytes)) if err != nil { return "", fmt.Errorf("impersonate: unable to create request: %w", err) diff --git a/vendor/cloud.google.com/go/auth/credentials/internal/impersonate/idtoken.go b/vendor/cloud.google.com/go/auth/credentials/internal/impersonate/idtoken.go new file mode 100644 index 0000000000..705462c161 --- /dev/null +++ b/vendor/cloud.google.com/go/auth/credentials/internal/impersonate/idtoken.go @@ -0,0 +1,105 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package impersonate + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "log/slog" + "net/http" + "strings" + "time" + + "cloud.google.com/go/auth" + "cloud.google.com/go/auth/internal" + "github.com/googleapis/gax-go/v2/internallog" +) + +var ( + universeDomainPlaceholder = "UNIVERSE_DOMAIN" + iamCredentialsUniverseDomainEndpoint = "https://iamcredentials.UNIVERSE_DOMAIN" +) + +// IDTokenIAMOptions provides configuration for [IDTokenIAMOptions.Token]. +type IDTokenIAMOptions struct { + // Client is required. + Client *http.Client + // Logger is required. + Logger *slog.Logger + UniverseDomain auth.CredentialsPropertyProvider + ServiceAccountEmail string + GenerateIDTokenRequest +} + +// GenerateIDTokenRequest holds the request to the IAM generateIdToken RPC. +type GenerateIDTokenRequest struct { + Audience string `json:"audience"` + IncludeEmail bool `json:"includeEmail"` + // Delegates are the ordered, fully-qualified resource name for service + // accounts in a delegation chain. Each service account must be granted + // roles/iam.serviceAccountTokenCreator on the next service account in the + // chain. The delegates must have the following format: + // projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}. The - wildcard + // character is required; replacing it with a project ID is invalid. + // Optional. + Delegates []string `json:"delegates,omitempty"` +} + +// GenerateIDTokenResponse holds the response from the IAM generateIdToken RPC. +type GenerateIDTokenResponse struct { + Token string `json:"token"` +} + +// Token call IAM generateIdToken with the configuration provided in [IDTokenIAMOptions]. +func (o IDTokenIAMOptions) Token(ctx context.Context) (*auth.Token, error) { + universeDomain, err := o.UniverseDomain.GetProperty(ctx) + if err != nil { + return nil, err + } + endpoint := strings.Replace(iamCredentialsUniverseDomainEndpoint, universeDomainPlaceholder, universeDomain, 1) + url := fmt.Sprintf("%s/v1/%s:generateIdToken", endpoint, internal.FormatIAMServiceAccountResource(o.ServiceAccountEmail)) + + bodyBytes, err := json.Marshal(o.GenerateIDTokenRequest) + if err != nil { + return nil, fmt.Errorf("impersonate: unable to marshal request: %w", err) + } + + req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(bodyBytes)) + if err != nil { + return nil, fmt.Errorf("impersonate: unable to create request: %w", err) + } + req.Header.Set("Content-Type", "application/json") + o.Logger.DebugContext(ctx, "impersonated idtoken request", "request", internallog.HTTPRequest(req, bodyBytes)) + resp, body, err := internal.DoRequest(o.Client, req) + if err != nil { + return nil, fmt.Errorf("impersonate: unable to generate ID token: %w", err) + } + o.Logger.DebugContext(ctx, "impersonated idtoken response", "response", internallog.HTTPResponse(resp, body)) + if c := resp.StatusCode; c < 200 || c > 299 { + return nil, fmt.Errorf("impersonate: status code %d: %s", c, body) + } + + var tokenResp GenerateIDTokenResponse + if err := json.Unmarshal(body, &tokenResp); err != nil { + return nil, fmt.Errorf("impersonate: unable to parse response: %w", err) + } + return &auth.Token{ + Value: tokenResp.Token, + // Generated ID tokens are good for one hour. + Expiry: time.Now().Add(1 * time.Hour), + }, nil +} diff --git a/vendor/cloud.google.com/go/auth/internal/internal.go b/vendor/cloud.google.com/go/auth/internal/internal.go index 6f4ef43bba..6a8eab6eb9 100644 --- a/vendor/cloud.google.com/go/auth/internal/internal.go +++ b/vendor/cloud.google.com/go/auth/internal/internal.go @@ -217,3 +217,9 @@ func getMetadataUniverseDomain(ctx context.Context, client *metadata.Client) (st } return "", err } + +// FormatIAMServiceAccountResource sets a service account name in an IAM resource +// name. +func FormatIAMServiceAccountResource(name string) string { + return fmt.Sprintf("projects/-/serviceAccounts/%s", name) +} diff --git a/vendor/cloud.google.com/go/auth/oauth2adapt/CHANGES.md b/vendor/cloud.google.com/go/auth/oauth2adapt/CHANGES.md index a1ef292379..d9044f1a94 100644 --- a/vendor/cloud.google.com/go/auth/oauth2adapt/CHANGES.md +++ b/vendor/cloud.google.com/go/auth/oauth2adapt/CHANGES.md @@ -1,5 +1,12 @@ # Changelog +## [0.2.7](https://github.com/googleapis/google-cloud-go/compare/auth/oauth2adapt/v0.2.6...auth/oauth2adapt/v0.2.7) (2025-01-09) + + +### Bug Fixes + +* **auth/oauth2adapt:** Update golang.org/x/net to v0.33.0 ([e9b0b69](https://github.com/googleapis/google-cloud-go/commit/e9b0b69644ea5b276cacff0a707e8a5e87efafc9)) + ## [0.2.6](https://github.com/googleapis/google-cloud-go/compare/auth/oauth2adapt/v0.2.5...auth/oauth2adapt/v0.2.6) (2024-11-21) diff --git a/vendor/cuelabs.dev/go/oci/ociregistry/error.go b/vendor/cuelabs.dev/go/oci/ociregistry/error.go index f41c90d367..b274a412d7 100644 --- a/vendor/cuelabs.dev/go/oci/ociregistry/error.go +++ b/vendor/cuelabs.dev/go/oci/ociregistry/error.go @@ -233,6 +233,16 @@ func (e *httpError) ResponseBody() []byte { return e.body } +// WriteError marshals the given error as JSON using [MarshalError] and +// then writes it to w. It returns the error returned from w.Write. +func WriteError(w http.ResponseWriter, err error) error { + data, httpStatus := MarshalError(err) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(httpStatus) + _, err = w.Write(data) + return err +} + // MarshalError marshals the given error as JSON according // to the OCI distribution specification. It also returns // the associated HTTP status code, or [http.StatusInternalServerError] diff --git a/vendor/cuelabs.dev/go/oci/ociregistry/interface.go b/vendor/cuelabs.dev/go/oci/ociregistry/interface.go index f110e81702..ade311d76a 100644 --- a/vendor/cuelabs.dev/go/oci/ociregistry/interface.go +++ b/vendor/cuelabs.dev/go/oci/ociregistry/interface.go @@ -60,7 +60,7 @@ import ( "context" "io" - "github.com/opencontainers/go-digest" + "cuelabs.dev/go/oci/ociregistry/ociref" ocispec "github.com/opencontainers/image-spec/specs-go/v1" ) @@ -81,7 +81,7 @@ type ReadWriter interface { } type ( - Digest = digest.Digest + Digest = ociref.Digest Descriptor = ocispec.Descriptor Manifest = ocispec.Manifest ) diff --git a/vendor/cuelabs.dev/go/oci/ociregistry/internal/ocirequest/request.go b/vendor/cuelabs.dev/go/oci/ociregistry/internal/ocirequest/request.go index 1bb19b5817..99b281574b 100644 --- a/vendor/cuelabs.dev/go/oci/ociregistry/internal/ocirequest/request.go +++ b/vendor/cuelabs.dev/go/oci/ociregistry/internal/ocirequest/request.go @@ -24,6 +24,7 @@ import ( "unicode/utf8" "cuelabs.dev/go/oci/ociregistry" + "cuelabs.dev/go/oci/ociregistry/ociref" ) // ParseError represents an error that can happen when parsing. @@ -225,7 +226,7 @@ func parse(method string, u *url.URL) (*Request, error) { } if ok { rreq.Repo = uploadPath - if !ociregistry.IsValidRepoName(rreq.Repo) { + if !ociref.IsValidRepository(rreq.Repo) { return nil, ociregistry.ErrNameInvalid } if method != "POST" { @@ -234,7 +235,7 @@ func parse(method string, u *url.URL) (*Request, error) { if d := urlq.Get("mount"); d != "" { // end-11 rreq.Digest = d - if !ociregistry.IsValidDigest(rreq.Digest) { + if !ociref.IsValidDigest(rreq.Digest) { return nil, ociregistry.ErrDigestInvalid } rreq.FromRepo = urlq.Get("from") @@ -246,7 +247,7 @@ func parse(method string, u *url.URL) (*Request, error) { rreq.Digest = "" return &rreq, nil } - if !ociregistry.IsValidRepoName(rreq.FromRepo) { + if !ociref.IsValidRepository(rreq.FromRepo) { return nil, ociregistry.ErrNameInvalid } rreq.Kind = ReqBlobMount @@ -255,7 +256,7 @@ func parse(method string, u *url.URL) (*Request, error) { if d := urlq.Get("digest"); d != "" { // end-4b rreq.Digest = d - if !ociregistry.IsValidDigest(d) { + if !ociref.IsValidDigest(d) { return nil, ErrBadlyFormedDigest } rreq.Kind = ReqBlobUploadBlob @@ -276,10 +277,10 @@ func parse(method string, u *url.URL) (*Request, error) { switch lastButOne { case "blobs": rreq.Repo = path - if !ociregistry.IsValidDigest(last) { + if !ociref.IsValidDigest(last) { return nil, ErrBadlyFormedDigest } - if !ociregistry.IsValidRepoName(rreq.Repo) { + if !ociref.IsValidRepository(rreq.Repo) { return nil, ociregistry.ErrNameInvalid } rreq.Digest = last @@ -302,7 +303,7 @@ func parse(method string, u *url.URL) (*Request, error) { return nil, ErrNotFound } rreq.Repo = repo - if !ociregistry.IsValidRepoName(rreq.Repo) { + if !ociref.IsValidRepository(rreq.Repo) { return nil, ociregistry.ErrNameInvalid } uploadID64 := last @@ -326,7 +327,7 @@ func parse(method string, u *url.URL) (*Request, error) { case "PUT": rreq.Kind = ReqBlobCompleteUpload rreq.Digest = urlq.Get("digest") - if !ociregistry.IsValidDigest(rreq.Digest) { + if !ociref.IsValidDigest(rreq.Digest) { return nil, ErrBadlyFormedDigest } default: @@ -335,13 +336,13 @@ func parse(method string, u *url.URL) (*Request, error) { return &rreq, nil case "manifests": rreq.Repo = path - if !ociregistry.IsValidRepoName(rreq.Repo) { + if !ociref.IsValidRepository(rreq.Repo) { return nil, ociregistry.ErrNameInvalid } switch { - case ociregistry.IsValidDigest(last): + case ociref.IsValidDigest(last): rreq.Digest = last - case ociregistry.IsValidTag(last): + case ociref.IsValidTag(last): rreq.Tag = last default: return nil, ErrNotFound @@ -371,20 +372,20 @@ func parse(method string, u *url.URL) (*Request, error) { return nil, ErrMethodNotAllowed } rreq.Repo = path - if !ociregistry.IsValidRepoName(rreq.Repo) { + if !ociref.IsValidRepository(rreq.Repo) { return nil, ociregistry.ErrNameInvalid } rreq.Kind = ReqTagsList return &rreq, nil case "referrers": - if !ociregistry.IsValidDigest(last) { + if !ociref.IsValidDigest(last) { return nil, ErrBadlyFormedDigest } if method != "GET" { return nil, ErrMethodNotAllowed } rreq.Repo = path - if !ociregistry.IsValidRepoName(rreq.Repo) { + if !ociref.IsValidRepository(rreq.Repo) { return nil, ociregistry.ErrNameInvalid } // TODO is there any kind of pagination for referrers? diff --git a/vendor/cuelabs.dev/go/oci/ociregistry/ociauth/authfile.go b/vendor/cuelabs.dev/go/oci/ociregistry/ociauth/authfile.go index d9c6b684da..a1c36eaaae 100644 --- a/vendor/cuelabs.dev/go/oci/ociregistry/ociauth/authfile.go +++ b/vendor/cuelabs.dev/go/oci/ociregistry/ociauth/authfile.go @@ -10,7 +10,7 @@ import ( "os/exec" "path/filepath" "runtime" - "sort" + "slices" "strings" ) @@ -265,7 +265,7 @@ func decodeConfigFile(data []byte) (configData, error) { ac = ac1 } ac.derivedFrom = append(ac.derivedFrom, addr) - sort.Strings(ac.derivedFrom) + slices.Sort(ac.derivedFrom) f.Auths[addr1] = ac } return f, nil diff --git a/vendor/cuelabs.dev/go/oci/ociregistry/ociclient/client.go b/vendor/cuelabs.dev/go/oci/ociregistry/ociclient/client.go index bc78b328f6..5c3a39f2ed 100644 --- a/vendor/cuelabs.dev/go/oci/ociregistry/ociclient/client.go +++ b/vendor/cuelabs.dev/go/oci/ociregistry/ociclient/client.go @@ -35,6 +35,7 @@ import ( "cuelabs.dev/go/oci/ociregistry" "cuelabs.dev/go/oci/ociregistry/internal/ocirequest" "cuelabs.dev/go/oci/ociregistry/ociauth" + "cuelabs.dev/go/oci/ociregistry/ociref" ) // debug enables logging. @@ -166,7 +167,7 @@ func descriptorFromResponse(resp *http.Response, knownDigest digest.Digest, requ } digest := digest.Digest(resp.Header.Get("Docker-Content-Digest")) if digest != "" { - if !ociregistry.IsValidDigest(string(digest)) { + if !ociref.IsValidDigest(string(digest)) { return ociregistry.Descriptor{}, fmt.Errorf("bad digest %q found in response", digest) } } else { diff --git a/vendor/cuelabs.dev/go/oci/ociregistry/ociref/reference.go b/vendor/cuelabs.dev/go/oci/ociregistry/ociref/reference.go index 650b041a0d..3002b70f48 100644 --- a/vendor/cuelabs.dev/go/oci/ociregistry/ociref/reference.go +++ b/vendor/cuelabs.dev/go/oci/ociregistry/ociref/reference.go @@ -19,8 +19,9 @@ import ( "fmt" "regexp" "strings" + "sync" - "cuelabs.dev/go/oci/ociregistry" + "github.com/opencontainers/go-digest" ) // The following regular expressions derived from code in the @@ -91,17 +92,23 @@ const ( repoName = pathComponent + `(?:` + `/` + pathComponent + `)*` ) -var referencePat = regexp.MustCompile( - `^(?:` + - `(?:` + `(` + domainAndPort + `)` + `/` + `)?` + // capture 1: host - `(` + repoName + `)` + // capture 2: repository name - `(?:` + `:([^@]+))?` + // capture 3: tag; rely on Go logic to test validity. - `(?:` + `@(.+))?` + // capture 4: digest; rely on go-digest to find issues - `)$`, -) - -var hostPat = regexp.MustCompile(`^(?:` + domainAndPort + `)$`) -var repoPat = regexp.MustCompile(`^(?:` + repoName + `)$`) +var referencePat = sync.OnceValue(func() *regexp.Regexp { + return regexp.MustCompile( + `^(?:` + + `(?:` + `(` + domainAndPort + `)` + `/` + `)?` + // capture 1: host + `(` + repoName + `)` + // capture 2: repository name + `(?:` + `:([^@]+))?` + // capture 3: tag; rely on Go logic to test validity. + `(?:` + `@(.+))?` + // capture 4: digest; rely on go-digest to find issues + `)$`, + ) +}) + +var hostPat = sync.OnceValue(func() *regexp.Regexp { + return regexp.MustCompile(`^(?:` + domainAndPort + `)$`) +}) +var repoPat = sync.OnceValue(func() *regexp.Regexp { + return regexp.MustCompile(`^(?:` + repoName + `)$`) +}) // Reference represents an entry in an OCI repository. type Reference struct { @@ -120,18 +127,20 @@ type Reference struct { // Digest holds the DIGEST part of an @DIGEST reference // or of a :TAG@DIGEST reference. - Digest ociregistry.Digest + Digest Digest } +type Digest = digest.Digest + // IsValidHost reports whether s is a valid host (or host:port) part of a reference string. func IsValidHost(s string) bool { - return hostPat.MatchString(s) + return hostPat().MatchString(s) } // IsValidHost reports whether s is a valid repository part // of a reference string. func IsValidRepository(s string) bool { - return repoPat.MatchString(s) + return repoPat().MatchString(s) } // IsValidTag reports whether s is a valid reference tag. @@ -139,6 +148,12 @@ func IsValidTag(s string) bool { return checkTag(s) == nil } +// IsValidDigest reports whether the digest d is well formed. +func IsValidDigest(d string) bool { + _, err := digest.Parse(d) + return err == nil +} + // Parse parses a reference string that must include // a host name (or host:port pair) component. // @@ -165,12 +180,12 @@ func Parse(refStr string) (Reference, error) { // Unlike "docker pull" however, there is no default registry: when // presented with a bare repository name, the Host field will be empty. func ParseRelative(refStr string) (Reference, error) { - m := referencePat.FindStringSubmatch(refStr) + m := referencePat().FindStringSubmatch(refStr) if m == nil { return Reference{}, fmt.Errorf("invalid reference syntax (%q)", refStr) } var ref Reference - ref.Host, ref.Repository, ref.Tag, ref.Digest = m[1], m[2], m[3], ociregistry.Digest(m[4]) + ref.Host, ref.Repository, ref.Tag, ref.Digest = m[1], m[2], m[3], Digest(m[4]) // Check lengths and digest: we don't check these as part of the regexp // because it's more efficient to do it in Go and we get // nicer error messages as a result. diff --git a/vendor/cuelabs.dev/go/oci/ociregistry/valid.go b/vendor/cuelabs.dev/go/oci/ociregistry/valid.go index 7486fa195a..bf53bc3ea0 100644 --- a/vendor/cuelabs.dev/go/oci/ociregistry/valid.go +++ b/vendor/cuelabs.dev/go/oci/ociregistry/valid.go @@ -1,30 +1,28 @@ package ociregistry import ( - "regexp" - - "github.com/opencontainers/go-digest" -) - -var ( - tagPattern = regexp.MustCompile(`^[a-zA-Z0-9_][a-zA-Z0-9._-]{0,127}$`) - repoNamePattern = regexp.MustCompile(`^[a-z0-9]+([._-][a-z0-9]+)*(/[a-z0-9]+([._-][a-z0-9]+)*)*$`) + "cuelabs.dev/go/oci/ociregistry/ociref" ) // IsValidRepoName reports whether the given repository // name is valid according to the specification. +// +// Deprecated: use [ociref.IsValidRepository]. func IsValidRepoName(repoName string) bool { - return repoNamePattern.MatchString(repoName) + return ociref.IsValidRepository(repoName) } // IsValidTag reports whether the digest d is valid // according to the specification. +// +// Deprecated: use [ociref.IsValidTag]. func IsValidTag(tag string) bool { - return tagPattern.MatchString(tag) + return ociref.IsValidTag(tag) } // IsValidDigest reports whether the digest d is well formed. +// +// Deprecated: use [ociref.IsValidDigest]. func IsValidDigest(d string) bool { - _, err := digest.Parse(d) - return err == nil + return ociref.IsValidDigest(d) } diff --git a/vendor/cuelang.org/go/cue/ast/ast.go b/vendor/cuelang.org/go/cue/ast/ast.go index b47a33d852..b66749f5ab 100644 --- a/vendor/cuelang.org/go/cue/ast/ast.go +++ b/vendor/cuelang.org/go/cue/ast/ast.go @@ -176,10 +176,10 @@ func (c *comments) SetComments(cgs []*CommentGroup) { *c.groups = cgs } -// A Comment node represents a single //-style or /*-style comment. +// A Comment node represents a single //-style comment. type Comment struct { Slash token.Pos // position of "/" starting the comment - Text string // comment text (excluding '\n' for //-style comments) + Text string // comment text excluding '\n' } func (c *Comment) Comments() []*CommentGroup { return nil } @@ -226,7 +226,7 @@ func stripTrailingWhitespace(s string) string { } // Text returns the text of the comment. -// Comment markers (//, /*, and */), the first space of a line comment, and +// Comment markers ("//"), the first space of a line comment, and // leading and trailing empty lines are removed. Multiple empty lines are // reduced to one, and trailing space on lines is trimmed. Unless the result // is empty, it is newline-terminated. @@ -243,17 +243,10 @@ func (g *CommentGroup) Text() string { for _, c := range comments { // Remove comment markers. // The parser has given us exactly the comment text. - switch c[1] { - case '/': - //-style comment (no newline at the end) - c = c[2:] - // strip first space - required for Example tests - if len(c) > 0 && c[0] == ' ' { - c = c[1:] - } - case '*': - /*-style comment */ - c = c[2 : len(c)-2] + c = c[2:] + // strip first space - required for Example tests + if len(c) > 0 && c[0] == ' ' { + c = c[1:] } // Split on newlines. @@ -952,10 +945,6 @@ func (d *EmbedDecl) End() token.Pos { return d.Expr.End() } // Files and packages // A File node represents a CUE source file. -// -// The Comments list contains all comments in the source file in order of -// appearance, including the comments that are pointed to from other nodes -// via Doc and Comment fields. type File struct { Filename string Decls []Decl // top-level declarations; or nil @@ -1006,6 +995,9 @@ func (f *File) PackageName() string { for _, d := range f.Decls { switch x := d.(type) { case *Package: + if x.Name.Name == "_" { + return "" + } return x.Name.Name case *CommentGroup, *Attribute: default: diff --git a/vendor/cuelang.org/go/cue/ast/astutil/apply.go b/vendor/cuelang.org/go/cue/ast/astutil/apply.go index 08bb236a65..1f71faf106 100644 --- a/vendor/cuelang.org/go/cue/ast/astutil/apply.go +++ b/vendor/cuelang.org/go/cue/ast/astutil/apply.go @@ -46,6 +46,9 @@ type Cursor interface { // Import reports an opaque identifier that refers to the given package. It // may only be called if the input to apply was an ast.File. If the import // does not exist, it will be added. + // + // Deprecated: use [ast.NewImport] as an [ast.Ident.Node], and then + // [Sanitize]. Import(path string) *ast.Ident // Replace replaces the current Node with n. @@ -120,6 +123,8 @@ func (c *cursor) Parent() Cursor { return c.parent } func (c *cursor) Index() int { return c.index } func (c *cursor) Node() ast.Node { return c.node } +// Deprecated: use [ast.NewImport] as an [ast.Ident.Node], and then +// [Sanitize]. func (c *cursor) Import(importPath string) *ast.Ident { info := fileInfo(c) if info == nil { @@ -471,8 +476,7 @@ func (f *applier) After(c Cursor) bool { func (f *applier) visitComments(p Cursor, pos int8) { c := &f.current - for i := 0; i < len(c.cg); i++ { - cg := c.cg[i] + for i, cg := range c.cg { if cg.Position == pos { continue } diff --git a/vendor/cuelang.org/go/cue/ast/astutil/sanitize.go b/vendor/cuelang.org/go/cue/ast/astutil/sanitize.go index c0cfee8d8e..98f9fc8209 100644 --- a/vendor/cuelang.org/go/cue/ast/astutil/sanitize.go +++ b/vendor/cuelang.org/go/cue/ast/astutil/sanitize.go @@ -168,15 +168,28 @@ func (z *sanitizer) markUsed(s *scope, n *ast.Ident) bool { } func (z *sanitizer) cleanImports() { - z.file.VisitImports(func(d *ast.ImportDecl) { - k := 0 - for _, s := range d.Specs { - if _, ok := z.referenced[s]; ok { - d.Specs[k] = s - k++ + var fileImports []*ast.ImportSpec + z.file.VisitImports(func(decl *ast.ImportDecl) { + newLen := 0 + for _, spec := range decl.Specs { + if _, ok := z.referenced[spec]; ok { + fileImports = append(fileImports, spec) + decl.Specs[newLen] = spec + newLen++ } } - d.Specs = d.Specs[:k] + decl.Specs = decl.Specs[:newLen] + }) + z.file.Imports = fileImports + // Ensure that the first import always starts a new section + // so that if the file has a comment, it won't be associated with + // the import comment rather than the file. + first := true + z.file.VisitImports(func(decl *ast.ImportDecl) { + if first { + ast.SetRelPos(decl, token.NewSection) + first = false + } }) } diff --git a/vendor/cuelang.org/go/cue/ast/ident.go b/vendor/cuelang.org/go/cue/ast/ident.go index 66f814c813..8e84aef3f9 100644 --- a/vendor/cuelang.org/go/cue/ast/ident.go +++ b/vendor/cuelang.org/go/cue/ast/ident.go @@ -130,5 +130,5 @@ func LabelName(l Label) (name string, isIdent bool, err error) { } // ErrIsExpression reports whether a label is an expression. -// This error is never returned directly. Use errors.Is. +// This error is never returned directly. Use [errors.Is]. var ErrIsExpression = errors.New("not a concrete label") diff --git a/vendor/cuelang.org/go/cue/attribute.go b/vendor/cuelang.org/go/cue/attribute.go index c73e3d4f12..2311d78fd8 100644 --- a/vendor/cuelang.org/go/cue/attribute.go +++ b/vendor/cuelang.org/go/cue/attribute.go @@ -49,6 +49,7 @@ func newAttr(k internal.AttrKind, a *ast.Attribute) Attribute { x := internal.ParseAttrBody(a.Pos().Add(len(key)+1), body) x.Name = key x.Kind = k + x.Pos = a.Pos() return Attribute{x} } @@ -210,13 +211,5 @@ func (a *Attribute) Flag(pos int, key string) (bool, error) { // and reports the value if found. It reports an error if the attribute is // invalid or if the first pos-1 entries are not defined. func (a *Attribute) Lookup(pos int, key string) (val string, found bool, err error) { - val, found, err = a.attr.Lookup(pos, key) - - // TODO: remove at some point. This is an ugly hack to simulate the old - // behavior of protobufs. - if !found && a.attr.Name == "protobuf" && key == "type" { - val, err = a.String(1) - found = err == nil - } - return val, found, err + return a.attr.Lookup(pos, key) } diff --git a/vendor/cuelang.org/go/cue/build.go b/vendor/cuelang.org/go/cue/build.go index 8d5a3f7919..f8621ce8b2 100644 --- a/vendor/cuelang.org/go/cue/build.go +++ b/vendor/cuelang.org/go/cue/build.go @@ -124,11 +124,12 @@ func Build(instances []*build.Instance) []*Instance { panic("cue: list of instances must not be empty") } var r Runtime - a, _ := r.build(instances) + a, _ := r.BuildInstances(instances) return a } -func (r *hiddenRuntime) build(instances []*build.Instance) ([]*Instance, error) { +// Deprecated: use [Context.BuildInstances]. The use of [Instance] is being phased out. +func (r *hiddenRuntime) BuildInstances(instances []*build.Instance) ([]*Instance, error) { index := r.runtime() loaded := []*Instance{} diff --git a/vendor/cuelang.org/go/cue/build/context.go b/vendor/cuelang.org/go/cue/build/context.go index dc1e347c93..c8eadbf294 100644 --- a/vendor/cuelang.org/go/cue/build/context.go +++ b/vendor/cuelang.org/go/cue/build/context.go @@ -109,7 +109,7 @@ func Loader(f LoadFunc) Option { // ParseFile is called to read and parse each file // when building syntax tree. // It must be safe to call ParseFile simultaneously from multiple goroutines. -// If ParseFile is nil, the loader will uses parser.ParseFile. +// If f is nil, the loader will use [cuelang.org/go/cue/parser.ParseFile]. // // ParseFile should parse the source from src and use filename only for // recording position information. diff --git a/vendor/cuelang.org/go/cue/build/file.go b/vendor/cuelang.org/go/cue/build/file.go index 7b22d2eda6..945fe31e41 100644 --- a/vendor/cuelang.org/go/cue/build/file.go +++ b/vendor/cuelang.org/go/cue/build/file.go @@ -16,14 +16,24 @@ package build import "cuelang.org/go/cue/errors" +// Note: the json tags in File correspond directly to names +// used in the encoding/filetypes package, which unmarshals +// results from CUE into a build.File. + // A File represents a file that is part of the build process. type File struct { Filename string `json:"filename"` - Encoding Encoding `json:"encoding,omitempty"` - Interpretation Interpretation `json:"interpretation,omitempty"` - Form Form `json:"form,omitempty"` - Tags map[string]string `json:"tags,omitempty"` // code=go + Encoding Encoding `json:"encoding,omitempty"` + Interpretation Interpretation `json:"interpretation,omitempty"` + Form Form `json:"form,omitempty"` + // Tags holds key-value pairs relating to the encoding + // conventions to use for the file. + Tags map[string]string `json:"tags,omitempty"` // e.g. code+lang=go + + // BoolTags holds boolean-valued tags relating to the + // encoding conventions to use for the file. + BoolTags map[string]bool `json:"boolTags,omitempty"` ExcludeReason errors.Error `json:"-"` Source interface{} `json:"-"` // TODO: swap out with concrete type. @@ -36,6 +46,7 @@ const ( CUE Encoding = "cue" JSON Encoding = "json" YAML Encoding = "yaml" + TOML Encoding = "toml" JSONL Encoding = "jsonl" Text Encoding = "text" Binary Encoding = "binary" @@ -43,9 +54,6 @@ const ( TextProto Encoding = "textproto" BinaryProto Encoding = "pb" - // TODO: - // TOML - Code Encoding = "code" // Programming languages ) diff --git a/vendor/cuelang.org/go/cue/build/import.go b/vendor/cuelang.org/go/cue/build/import.go index 71ae484961..86d90a3cfa 100644 --- a/vendor/cuelang.org/go/cue/build/import.go +++ b/vendor/cuelang.org/go/cue/build/import.go @@ -15,7 +15,7 @@ package build import ( - "sort" + "slices" "strconv" "cuelang.org/go/cue/errors" @@ -78,7 +78,7 @@ func (inst *Instance) complete() errors.Error { } } - sort.Strings(paths) + slices.Sort(paths) if inst.loadFunc != nil { for i, path := range paths { @@ -147,7 +147,7 @@ func (inst *Instance) complete() errors.Error { for dep := range deps { inst.Deps = append(inst.Deps, dep) } - sort.Strings(inst.Deps) + slices.Sort(inst.Deps) for _, dep := range inst.Deps { p1 := deps[dep] diff --git a/vendor/cuelang.org/go/cue/build/instance.go b/vendor/cuelang.org/go/cue/build/instance.go index 42270ece90..2c116c4fd0 100644 --- a/vendor/cuelang.org/go/cue/build/instance.go +++ b/vendor/cuelang.org/go/cue/build/instance.go @@ -56,7 +56,7 @@ type Instance struct { // ImportPath returns the unique path to identify an imported instance. // - // Instances created with NewInstance do not have an import path. + // Instances created with [Context.NewInstance] do not have an import path. ImportPath string // Imports lists the instances of all direct imports of this instance. @@ -84,25 +84,19 @@ type Instance struct { // instance has no imports. // If Module != "", this corresponds to the module root. // Root/pkg is the directory that holds third-party packages. - Root string // root directory of hierarchy ("" if unknown) + Root string // Dir is the package directory. A package may also include files from // ancestor directories, up to the module file. Dir string - // NOTICE: the below tags may change in the future. - - // ImportComment is the path in the import comment on the package statement. - ImportComment string `api:"alpha"` - - // AllTags are the build tags that can influence file selection in this - // directory. - AllTags []string `api:"alpha"` + // NOTICE: the below struct field tags may change in the future. // Incomplete reports whether any dependencies had an error. Incomplete bool `api:"alpha"` // Dependencies + // ImportPaths gives the transitive dependencies of all imports. ImportPaths []string `api:"alpha"` ImportPos map[string][]token.Pos `api:"alpha"` // line information for Imports @@ -218,7 +212,7 @@ func (inst *Instance) addImport(imp *Instance) { // It does not process the file's imports. The package name of the file must // match the package name of the instance. // -// Deprecated: use AddSyntax or wait for this to be renamed using a new +// Deprecated: use [Instance.AddSyntax] or wait for this to be renamed using a new // signature. func (inst *Instance) AddFile(filename string, src interface{}) error { file, err := inst.parse(filename, src) diff --git a/vendor/cuelang.org/go/cue/context.go b/vendor/cuelang.org/go/cue/context.go index e56a8a917e..3c69e2802a 100644 --- a/vendor/cuelang.org/go/cue/context.go +++ b/vendor/cuelang.org/go/cue/context.go @@ -15,6 +15,8 @@ package cue import ( + "cmp" + "cuelang.org/go/cue/ast" "cuelang.org/go/cue/ast/astutil" "cuelang.org/go/cue/build" @@ -28,17 +30,13 @@ import ( "cuelang.org/go/internal/core/runtime" ) -// A Context is used for creating CUE Values. +// A Context is used for creating CUE [Value]s. // // A Context keeps track of loaded instances, indices of internal // representations of values, and defines the set of supported builtins. Any // operation that involves two Values should originate from the same Context. // -// Use -// -// ctx := cuecontext.New() -// -// to create a new Context. +// Use [cuelang.org/go/cue/cuecontext.New] to create a new context. type Context runtime.Runtime func (c *Context) runtime() *runtime.Runtime { @@ -117,10 +115,10 @@ func (c *Context) parseOptions(options []BuildOption) (cfg runtime.Config) { return cfg } -// BuildInstance creates a Value from the given build.Instance. +// BuildInstance creates a [Value] from the given [*build.Instance]. // -// The returned Value will represent an error, accessible through Err, if any -// error occurred. +// The returned value will represent an error, accessible through [Value.Err], +// if any error occurred. func (c *Context) BuildInstance(i *build.Instance, options ...BuildOption) Value { cfg := c.parseOptions(options) v, err := c.runtime().Build(&cfg, i) @@ -138,7 +136,7 @@ func (c *Context) makeError(err errors.Error) Value { return c.make(node) } -// BuildInstances creates a Value for each of the given instances and reports +// BuildInstances creates a [Value] for each of the given [*build.Instance]s and reports // the combined errors or nil if there were no errors. func (c *Context) BuildInstances(instances []*build.Instance) ([]Value, error) { var errs errors.Error @@ -155,10 +153,10 @@ func (c *Context) BuildInstances(instances []*build.Instance) ([]Value, error) { return a, errs } -// BuildFile creates a Value from f. +// BuildFile creates a [Value] from f. // -// The returned Value will represent an error, accessible through Err, if any -// error occurred. +// The returned value will represent an error, accessible through [Value.Err], +// if any error occurred. func (c *Context) BuildFile(f *ast.File, options ...BuildOption) Value { cfg := c.parseOptions(options) return c.compile(c.runtime().CompileFile(&cfg, f)) @@ -171,10 +169,10 @@ func (c *Context) compile(v *adt.Vertex, p *build.Instance) Value { return c.make(v) } -// BuildExpr creates a Value from x. +// BuildExpr creates a [Value] from x. // -// The returned Value will represent an error, accessible through Err, if any -// error occurred. +// The returned value will represent an error, accessible through [Value.Err], +// if any error occurred. func (c *Context) BuildExpr(x ast.Expr, options ...BuildOption) Value { r := c.runtime() cfg := c.parseOptions(options) @@ -185,10 +183,7 @@ func (c *Context) BuildExpr(x ast.Expr, options ...BuildOption) Value { // and the expression resulting from CompileString differently. astutil.ResolveExpr(x, errFn) - pkgPath := cfg.ImportPath - if pkgPath == "" { - pkgPath = anonymousPkg - } + pkgPath := cmp.Or(cfg.ImportPath, anonymousPkg) conjunct, err := compile.Expr(&cfg.Config, r, pkgPath, x) if err != nil { @@ -217,19 +212,19 @@ func resolveExpr(ctx *adt.OpContext, v Value, x ast.Expr) adt.Value { // anonymousPkg reports a package path that can never resolve to a valid package. const anonymousPkg = "_" -// CompileString parses and build a Value from the given source string. +// CompileString parses and builds a [Value] from the given source string. // -// The returned Value will represent an error, accessible through Err, if any -// error occurred. +// The returned value will represent an error, accessible through [Value.Err], +// if any error occurred. func (c *Context) CompileString(src string, options ...BuildOption) Value { cfg := c.parseOptions(options) return c.compile(c.runtime().Compile(&cfg, src)) } -// CompileBytes parses and build a Value from the given source bytes. +// CompileBytes parses and builds a [Value] from the given source bytes. // -// The returned Value will represent an error, accessible through Err, if any -// error occurred. +// The returned value will represent an error, accessible through [Value.Err], +// if any error occurred. func (c *Context) CompileBytes(b []byte, options ...BuildOption) Value { cfg := c.parseOptions(options) return c.compile(c.runtime().Compile(&cfg, b)) @@ -260,7 +255,7 @@ func (c *Context) make(v *adt.Vertex) Value { } // An EncodeOption defines options for the various encoding-related methods of -// Context. +// [Context]. type EncodeOption func(*encodeOptions) type encodeOptions struct { @@ -280,10 +275,10 @@ func NilIsAny(isAny bool) EncodeOption { return func(o *encodeOptions) { o.nilIsTop = isAny } } -// Encode converts a Go value to a CUE value. +// Encode converts a Go value to a CUE [Value]. // -// The returned Value will represent an error, accessible through Err, if any -// error occurred. +// The returned value will represent an error, accessible through [Value.Err], +// if any error occurred. // // Encode traverses the value v recursively. If an encountered value implements // the json.Marshaler interface and is not a nil pointer, Encode calls its @@ -374,16 +369,21 @@ func (c *Context) Encode(x interface{}, option ...EncodeOption) Value { ctx := c.ctx() // TODO: is true the right default? expr := convert.GoValueToValue(ctx, x, options.nilIsTop) - n := &adt.Vertex{} - n.AddConjunct(adt.MakeRootConjunct(nil, expr)) + var n *adt.Vertex + if v, ok := expr.(*adt.Vertex); ok { + n = v + } else { + n = &adt.Vertex{} + n.AddConjunct(adt.MakeRootConjunct(nil, expr)) + } n.Finalize(ctx) return c.make(n) } -// Encode converts a Go type to a CUE value. +// Encode converts a Go type to a CUE [Value]. // -// The returned Value will represent an error, accessible through Err, if any -// error occurred. +// The returned value will represent an error, accessible through [Value.Err], +// if any error occurred. func (c *Context) EncodeType(x interface{}, option ...EncodeOption) Value { switch v := x.(type) { case *adt.Vertex: @@ -395,8 +395,13 @@ func (c *Context) EncodeType(x interface{}, option ...EncodeOption) Value { if err != nil { return c.makeError(err) } - n := &adt.Vertex{} - n.AddConjunct(adt.MakeRootConjunct(nil, expr)) + var n *adt.Vertex + if v, ok := expr.(*adt.Vertex); ok { + n = v + } else { + n = &adt.Vertex{} + n.AddConjunct(adt.MakeRootConjunct(nil, expr)) + } n.Finalize(ctx) return c.make(n) } @@ -467,7 +472,7 @@ func str(c *adt.OpContext, v adt.Node) string { // eval returns the evaluated value. This may not be the vertex. // -// Deprecated: use ctx.value +// Deprecated: use [adt.OpContext.value]. func (v Value) eval(ctx *adt.OpContext) adt.Value { if v.v == nil { panic("undefined value") diff --git a/vendor/cuelang.org/go/cue/cue.go b/vendor/cuelang.org/go/cue/cue.go index 1b1c878f70..9fcf5b8aea 100644 --- a/vendor/cuelang.org/go/cue/cue.go +++ b/vendor/cuelang.org/go/cue/cue.go @@ -20,14 +20,12 @@ // Values created from the same Context are not safe for concurrent use, // which we intend to change in the future. // -// A Context defines the set of active packages, the translations of field -// names to unique codes, as well as the set of builtins. Use +// [Context] defines the set of active packages, the translations of field +// names to unique codes, as well as the set of builtins. +// Use [cuelang.org/go/cue/cuecontext.New] to create a new context. // -// import "cuelang.org/go/cue/cuecontext" -// -// ctx := cuecontext.New() -// -// to obtain a context. +// While a context can be used to build values, note that loading a module and its +// dependencies should be done with the [cuelang.org/go/cue/load] package. // // Note that the following types are DEPRECATED and their usage should be // avoided if possible: diff --git a/vendor/cuelang.org/go/cue/cuecontext/cuecontext.go b/vendor/cuelang.org/go/cue/cuecontext/cuecontext.go index 60fb2a9e2e..22a9879e37 100644 --- a/vendor/cuelang.org/go/cue/cuecontext/cuecontext.go +++ b/vendor/cuelang.org/go/cue/cuecontext/cuecontext.go @@ -31,20 +31,15 @@ type Option struct { apply func(r *runtime.Runtime) } -// defaultFlags defines the debug flags that are set by default. -var defaultFlags cuedebug.Config - -func init() { - if err := envflag.Parse(&defaultFlags, ""); err != nil { - panic(err) - } -} - -// New creates a new Context. +// New creates a new [*cue.Context]. +// +// The environment variables CUE_EXPERIMENT and CUE_DEBUG are followed to configure +// the evaluator, just like the cue tool documents via [cue help environment]. +// You can override these settings via options like [EvaluatorVersion] and [CUE_DEBUG]. +// +// [cue help environment]: https://cuelang.org/docs/reference/command/cue-help-environment/ func New(options ...Option) *cue.Context { r := runtime.New() - // Ensure default behavior if the flags are not set explicitly. - r.SetDebugOptions(&defaultFlags) for _, o := range options { o.apply(r) } @@ -67,21 +62,21 @@ type EvalVersion = internal.EvaluatorVersion const ( // EvalDefault is the latest stable version of the evaluator. - EvalDefault EvalVersion = EvalV2 + EvalDefault EvalVersion = internal.DefaultVersion // EvalExperiment refers to the latest unstable version of the evaluator. // Note that this version may change without notice. - EvalExperiment EvalVersion = EvalV3 + EvalExperiment EvalVersion = internal.DevVersion // EvalV2 is the currently latest stable version of the evaluator. // It was introduced in CUE version 0.3 and is being maintained until 2024. - EvalV2 EvalVersion = internal.DefaultVersion + EvalV2 EvalVersion = internal.EvalV2 // EvalV3 is the currently experimental version of the evaluator. // It was introduced in 2024 and brought a new disjunction algorithm, // a new closedness algorithm, a new core scheduler, and adds performance // enhancements like structure sharing. - EvalV3 EvalVersion = internal.DevVersion + EvalV3 EvalVersion = internal.EvalV3 ) // EvaluatorVersion indicates which version of the evaluator to use. Currently diff --git a/vendor/cuelang.org/go/cue/decode.go b/vendor/cuelang.org/go/cue/decode.go index b282306a30..713394d7f9 100644 --- a/vendor/cuelang.org/go/cue/decode.go +++ b/vendor/cuelang.org/go/cue/decode.go @@ -19,6 +19,7 @@ import ( "cmp" "encoding" "encoding/json" + "math" "reflect" "slices" "strconv" @@ -29,6 +30,7 @@ import ( "cuelang.org/go/cue/errors" "cuelang.org/go/internal/core/adt" + "cuelang.org/go/internal/cueexperiment" ) // Decode initializes the value pointed to by x with Value v. @@ -76,7 +78,7 @@ func (d *decoder) clear(x reflect.Value) { } } -var valueType = reflect.TypeOf(Value{}) +var valueType = reflect.TypeFor[Value]() func (d *decoder) decode(x reflect.Value, v Value, isPtr bool) { if !x.IsValid() { @@ -118,7 +120,7 @@ func (d *decoder) decode(x reflect.Value, v Value, isPtr bool) { ij, it, x := indirect(x, v.IsNull()) if ij != nil { - b, err := v.marshalJSON() + b, err := v.MarshalJSON() d.addErr(err) d.addErr(ij.UnmarshalJSON(b)) return @@ -268,7 +270,17 @@ func (d *decoder) interfaceValue(v Value) (x interface{}) { case IntKind: if i, err := v.Int64(); err == nil { - return int(i) + cueexperiment.Init() + if cueexperiment.Flags.DecodeInt64 { + return i + } + // When the decodeint64 experiment is not enabled, we want to return the value + // as `int`, but that's not possible for large values on 32-bit architectures. + // To avoid overflows causing entirely wrong values to be returned to the user, + // let the logic continue below so that we return a *big.Int instead. + if i <= math.MaxInt && i >= math.MinInt { + return int(i) + } } x, err = v.Int(nil) @@ -298,7 +310,7 @@ func (d *decoder) interfaceValue(v Value) (x interface{}) { iter, err := v.Fields() d.addErr(err) for iter.Next() { - m[iter.Label()] = d.interfaceValue(iter.Value()) + m[iter.Selector().Unquoted()] = d.interfaceValue(iter.Value()) } x = m @@ -310,7 +322,7 @@ func (d *decoder) interfaceValue(v Value) (x interface{}) { return x } -var textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() +var textUnmarshalerType = reflect.TypeFor[encoding.TextUnmarshaler]() // convertMap keeps an existing map and overwrites any entry found in v, // keeping other preexisting entries. @@ -340,7 +352,7 @@ func (d *decoder) convertMap(x reflect.Value, v Value) { iter, err := v.Fields() d.addErr(err) for iter.Next() { - key := iter.Label() + key := iter.Selector().Unquoted() var kv reflect.Value kt := t.Key() @@ -396,9 +408,8 @@ func (d *decoder) convertStruct(x reflect.Value, v Value) { iter, err := v.Fields() d.addErr(err) for iter.Next() { - var f *goField - key := iter.Label() + key := iter.Selector().Unquoted() if i, ok := fields.nameIndex[key]; ok { // Found an exact name match. f = &fields.list[i] @@ -480,9 +491,6 @@ type goField struct { nameBytes []byte // []byte(name) equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent - nameNonEsc string // `"` + name + `":` - nameEscHTML string // `"` + HTMLEscape(name) + `":` - tag bool index []int typ reflect.Type @@ -518,9 +526,6 @@ func typeFields(t reflect.Type) structFields { // Fields found. var fields []goField - // Buffer to run HTMLEscape on field names. - var nameEscBuf bytes.Buffer - for len(next) > 0 { current, next = next, current[:0] count, nextCount = nextCount, map[reflect.Type]int{} @@ -584,14 +589,6 @@ func typeFields(t reflect.Type) structFields { field.nameBytes = []byte(field.name) field.equalFold = foldFunc(field.nameBytes) - // Build nameEscHTML and nameNonEsc ahead of time. - nameEscBuf.Reset() - nameEscBuf.WriteString(`"`) - json.HTMLEscape(&nameEscBuf, field.nameBytes) - nameEscBuf.WriteString(`":`) - field.nameEscHTML = nameEscBuf.String() - field.nameNonEsc = `"` + field.name + `":` - fields = append(fields, field) if count[f.typ] > 1 { // If there were multiple instances, add a second, diff --git a/vendor/cuelang.org/go/cue/errors.go b/vendor/cuelang.org/go/cue/errors.go index d079b970ac..241d80dbc9 100644 --- a/vendor/cuelang.org/go/cue/errors.go +++ b/vendor/cuelang.org/go/cue/errors.go @@ -18,7 +18,6 @@ import ( "cuelang.org/go/cue/errors" "cuelang.org/go/cue/token" "cuelang.org/go/internal/core/adt" - "cuelang.org/go/internal/core/runtime" ) func (v Value) toErr(b *adt.Bottom) (err errors.Error) { @@ -96,7 +95,7 @@ var errNotExists = &adt.Bottom{ Err: errors.Newf(token.NoPos, "undefined value"), } -func mkErr(idx *runtime.Runtime, src adt.Node, args ...interface{}) *adt.Bottom { +func mkErr(src adt.Node, args ...interface{}) *adt.Bottom { var e *adt.Bottom var code adt.ErrorCode = -1 outer: diff --git a/vendor/cuelang.org/go/cue/errors/errors.go b/vendor/cuelang.org/go/cue/errors/errors.go index 31cb96377c..f1492f1021 100644 --- a/vendor/cuelang.org/go/cue/errors/errors.go +++ b/vendor/cuelang.org/go/cue/errors/errors.go @@ -31,7 +31,7 @@ import ( "cuelang.org/go/cue/token" ) -// New is a convenience wrapper for errors.New in the core library. +// New is a convenience wrapper for [errors.New] in the core library. // It does not return a CUE error. func New(msg string) error { return errors.New(msg) @@ -145,10 +145,24 @@ func Positions(err error) []token.Pos { } } - slices.SortFunc(a[sortOffset:], comparePos) + slices.SortFunc(a[sortOffset:], comparePosWithNoPosFirst) return slices.Compact(a) } +// comparePosWithNoPosFirst wraps [token.Pos.Compare] to place [token.NoPos] first, +// which is currently required for errors to be sorted correctly. +// TODO: give all errors valid positions so that we can use the standard sorting directly. +func comparePosWithNoPosFirst(a, b token.Pos) int { + if a == b { + return 0 + } else if a == token.NoPos { + return -1 + } else if b == token.NoPos { + return +1 + } + return token.Pos.Compare(a, b) +} + // Path returns the path of an Error if err is of that type. func Path(err error) []string { if e := Error(nil); errors.As(err, &e) { @@ -223,7 +237,7 @@ func (e *wrapped) Msg() (format string, args []interface{}) { } func (e *wrapped) Path() []string { - if p := Path(e.main); p != nil { + if p := e.main.Path(); p != nil { return p } return Path(e.wrap) @@ -281,9 +295,7 @@ func Append(a, b Error) Error { return appendToList(x, b) } // Preserve order of errors. - list := appendToList(nil, a) - list = appendToList(list, b) - return list + return appendToList(list{a}, b) } // Errors reports the individual errors associated with an error, which is @@ -311,11 +323,19 @@ func appendToList(a list, err Error) list { case nil: return a case list: - if a == nil { + if len(a) == 0 { return x } - return append(a, x...) + for _, e := range x { + a = appendToList(a, e) + } + return a default: + for _, e := range a { + if e == err { + return a + } + } return append(a, err) } } @@ -356,28 +376,6 @@ func (p *list) Add(err Error) { // Reset resets an List to no errors. func (p *list) Reset() { *p = (*p)[:0] } -func comparePos(a, b token.Pos) int { - if c := cmp.Compare(a.Filename(), b.Filename()); c != 0 { - return c - } - if c := cmp.Compare(a.Line(), b.Line()); c != 0 { - return c - } - return cmp.Compare(a.Column(), b.Column()) -} - -func comparePath(a, b []string) int { - for i, x := range a { - if i >= len(b) { - break - } - if c := cmp.Compare(x, b[i]); c != 0 { - return c - } - } - return cmp.Compare(len(a), len(b)) -} - // Sanitize sorts multiple errors and removes duplicates on a best effort basis. // If err represents a single or no error, it returns the error as is. func Sanitize(err Error) Error { @@ -398,8 +396,7 @@ func (p list) sanitize() list { if p == nil { return p } - a := make(list, len(p)) - copy(a, p) + a := slices.Clone(p) a.RemoveMultiples() return a } @@ -409,13 +406,10 @@ func (p list) sanitize() list { // entry. func (p list) Sort() { slices.SortFunc(p, func(a, b Error) int { - if c := comparePos(a.Position(), b.Position()); c != 0 { + if c := comparePosWithNoPosFirst(a.Position(), b.Position()); c != 0 { return c } - // Note that it is not sufficient to simply compare file offsets because - // the offsets do not reflect modified line information (through //line - // comments). - if c := comparePath(a.Path(), b.Path()); c != 0 { + if c := slices.Compare(a.Path(), b.Path()); c != 0 { return c } return cmp.Compare(a.Error(), b.Error()) @@ -444,10 +438,7 @@ func approximateEqual(a, b Error) bool { if aPos == token.NoPos || bPos == token.NoPos { return a.Error() == b.Error() } - return aPos.Filename() == bPos.Filename() && - aPos.Line() == bPos.Line() && - aPos.Column() == bPos.Column() && - comparePath(a.Path(), b.Path()) == 0 + return comparePosWithNoPosFirst(aPos, bPos) == 0 && slices.Compare(a.Path(), b.Path()) == 0 } // An List implements the error interface. @@ -581,49 +572,42 @@ func printError(w io.Writer, err error, cfg *Config) { fprintf = defaultFprintf } - positions := []string{} - for _, p := range Positions(err) { + if e, ok := err.(Error); ok { + writeErr(w, e) + } else { + fprintf(w, "%v", err) + } + + positions := Positions(err) + if len(positions) == 0 { + fprintf(w, "\n") + return + } + fprintf(w, ":\n") + for _, p := range positions { pos := p.Position() - s := pos.Filename + path := pos.Filename if cfg.Cwd != "" { - if p, err := filepath.Rel(cfg.Cwd, s); err == nil { - s = p - // Some IDEs (e.g. VSCode) only recognize a path if it start + if p, err := filepath.Rel(cfg.Cwd, path); err == nil { + path = p + // Some IDEs (e.g. VSCode) only recognize a path if it starts // with a dot. This also helps to distinguish between local // files and builtin packages. - if !strings.HasPrefix(s, ".") { - s = fmt.Sprintf(".%s%s", string(filepath.Separator), s) + if !strings.HasPrefix(path, ".") { + path = fmt.Sprintf(".%c%s", filepath.Separator, path) } } } if cfg.ToSlash { - s = filepath.ToSlash(s) + path = filepath.ToSlash(path) } + fprintf(w, " %s", path) if pos.IsValid() { - if s != "" { - s += ":" + if path != "" { + fprintf(w, ":") } - s += fmt.Sprintf("%d:%d", pos.Line, pos.Column) - } - if s == "" { - s = "-" + fprintf(w, "%d:%d", pos.Line, pos.Column) } - positions = append(positions, s) - } - - if e, ok := err.(Error); ok { - writeErr(w, e) - } else { - fprintf(w, "%v", err) - } - - if len(positions) == 0 { fprintf(w, "\n") - return - } - - fprintf(w, ":\n") - for _, pos := range positions { - fprintf(w, " %s\n", pos) } } diff --git a/vendor/cuelang.org/go/cue/format/format.go b/vendor/cuelang.org/go/cue/format/format.go index fc80d4f9a0..4fb52e63bb 100644 --- a/vendor/cuelang.org/go/cue/format/format.go +++ b/vendor/cuelang.org/go/cue/format/format.go @@ -25,7 +25,6 @@ package format import ( "bytes" "fmt" - "strings" "text/tabwriter" "cuelang.org/go/cue/ast" @@ -80,8 +79,8 @@ func sortImportsOption() Option { // Node formats node in canonical cue fmt style and writes the result to dst. // -// The node type must be *ast.File, []syntax.Decl, syntax.Expr, syntax.Decl, or -// syntax.Spec. Node does not modify node. Imports are not sorted for nodes +// The node type must be [*ast.File], [][ast.Decl], [ast.Expr], [ast.Decl], or +// [ast.Spec]. Node does not modify node. Imports are not sorted for nodes // representing partial source files (for instance, if the node is not an // *ast.File). // @@ -176,7 +175,7 @@ func (cfg *config) fprint(node interface{}) (out []byte, err error) { return b, nil } -// A formatter walks a syntax.Node, interspersed with comments and spacing +// A formatter walks an [ast.Node], interspersed with comments and spacing // directives, in the order that they would occur in printed form. type formatter struct { *printer @@ -249,7 +248,7 @@ func (f *formatter) print(a ...interface{}) { for _, x := range a { f.Print(x) switch x.(type) { - case string, token.Token: // , *syntax.BasicLit, *syntax.Ident: + case string, token.Token: // , *ast.BasicLit, *ast.Ident: f.current.pos++ } } @@ -314,27 +313,20 @@ func (f *formatter) visitComments(until int8) { func (f *formatter) printComment(cg *ast.CommentGroup) { f.Print(cg) - printBlank := false if cg.Doc && len(f.output) > 0 { f.Print(newline) - printBlank = true } for _, c := range cg.List { - isEnd := strings.HasPrefix(c.Text, "//") - if !printBlank { - if isEnd { - f.Print(vtab) - } else { - f.Print(blank) - } + if f.pos.Column > 1 { + // Vertically align inline comments. + f.Print(vtab) } f.Print(c.Slash) f.Print(c) - if isEnd { - f.Print(newline) - if cg.Doc { - f.Print(nooverride) - } + f.printingComment = true + f.Print(newline) + if cg.Doc { + f.Print(nooverride) } } } diff --git a/vendor/cuelang.org/go/cue/format/node.go b/vendor/cuelang.org/go/cue/format/node.go index 70d571ac07..4d0e943b14 100644 --- a/vendor/cuelang.org/go/cue/format/node.go +++ b/vendor/cuelang.org/go/cue/format/node.go @@ -104,7 +104,7 @@ func hasDocComments(d ast.Decl) bool { func (f *formatter) walkDeclList(list []ast.Decl) { f.before(nil) d := 0 - hasEllipsis := false + var ellipsis ast.Decl for i, x := range list { if i > 0 { f.print(declcomma) @@ -128,7 +128,7 @@ func (f *formatter) walkDeclList(list []ast.Decl) { } } if f.printer.cfg.simplify && internal.IsEllipsis(x) { - hasEllipsis = true + ellipsis = x continue } f.decl(x) @@ -156,8 +156,11 @@ func (f *formatter) walkDeclList(list []ast.Decl) { } f.print(f.current.parentSep) } - if hasEllipsis { - f.decl(&ast.Ellipsis{}) + if ellipsis != nil { + // ensure that comments associated with the original ellipsis are preserved + n := &ast.Ellipsis{} + ast.SetComments(n, ast.Comments(ellipsis)) + f.decl(n) f.print(f.current.parentSep) } f.after(nil) @@ -175,9 +178,12 @@ func (f *formatter) walkSpecList(list []*ast.ImportSpec) { func (f *formatter) walkClauseList(list []ast.Clause, ws whiteSpace) { f.before(nil) - for _, x := range list { + for i, x := range list { f.before(x) - f.print(ws) + // Only print the whitespace between the clauses. + if i > 0 { + f.print(ws) + } f.clause(x) f.after(x) } @@ -308,6 +314,7 @@ func (f *formatter) decl(decl ast.Decl) { } else { f.print(blank, nooverride, n.Token) } + f.visitComments(f.current.pos) if mem := f.inlineField(n); mem != nil { switch { @@ -404,7 +411,7 @@ func (f *formatter) decl(decl ast.Decl) { f.print(formfeed) } f.expr(n.Expr) - f.print(newline, noblank) + f.print(newline) case *ast.Attribute: f.print(n.At, n) @@ -455,10 +462,16 @@ func (f *formatter) nextNeedsFormfeed(n ast.Expr) bool { return strings.IndexByte(x.Value, '\n') >= 0 case *ast.ListLit: return true + case *ast.ParenExpr: + return f.nextNeedsFormfeed(x.X) case *ast.UnaryExpr: return f.nextNeedsFormfeed(x.X) case *ast.BinaryExpr: return f.nextNeedsFormfeed(x.X) || f.nextNeedsFormfeed(x.Y) + case *ast.IndexExpr: + return f.nextNeedsFormfeed(x.X) + case *ast.SelectorExpr: + return f.nextNeedsFormfeed(x.X) case *ast.CallExpr: for _, arg := range x.Args { if f.nextNeedsFormfeed(arg) { @@ -735,6 +748,8 @@ func (f *formatter) clause(clause ast.Clause) { f.markUnindentLine() case *ast.LetClause: + // TODO(mvdan): LetClause is handled in both the clause and decl methods, + // because at the semantic level it is different in each case, but the code is repetitive. f.print(n.Let, token.LET, blank, nooverride) f.print(indent) f.expr(n.Ident) @@ -761,7 +776,7 @@ func walkBinary(e *ast.BinaryExpr) (has6, has7, has8 bool, maxProblem int) { case *ast.BinaryExpr: if l.Op.Precedence() < e.Op.Precedence() { // parens will be inserted. - // pretend this is an *syntax.ParenExpr and do nothing. + // pretend this is an *ast.ParenExpr and do nothing. break } h6, h7, h8, mp := walkBinary(l) @@ -777,7 +792,7 @@ func walkBinary(e *ast.BinaryExpr) (has6, has7, has8 bool, maxProblem int) { case *ast.BinaryExpr: if r.Op.Precedence() <= e.Op.Precedence() { // parens will be inserted. - // pretend this is an *syntax.ParenExpr and do nothing. + // pretend this is an *ast.ParenExpr and do nothing. break } h6, h7, h8, mp := walkBinary(r) @@ -886,7 +901,7 @@ func (f *formatter) binaryExpr(x *ast.BinaryExpr, prec1, cutoff, depth int) { prec := x.Op.Precedence() if prec < prec1 { // parenthesis needed - // Note: The parser inserts a syntax.ParenExpr node; thus this case + // Note: The parser inserts a ast.ParenExpr node; thus this case // can only occur if the AST is created in a different way. // defer p.pushComment(nil).pop() f.print(token.LPAREN, nooverride) @@ -930,7 +945,7 @@ func (f *formatter) possibleSelectorExpr(expr ast.Expr, prec1, depth int) bool { return false } -// selectorExpr handles an *syntax.SelectorExpr node and returns whether x spans +// selectorExpr handles an [*ast.SelectorExpr] node and returns whether x spans // multiple lines. func (f *formatter) selectorExpr(x *ast.SelectorExpr, depth int) bool { f.expr1(x.X, token.HighestPrec, depth) diff --git a/vendor/cuelang.org/go/cue/format/printer.go b/vendor/cuelang.org/go/cue/format/printer.go index a9ffc02717..68e5b7c6bc 100644 --- a/vendor/cuelang.org/go/cue/format/printer.go +++ b/vendor/cuelang.org/go/cue/format/printer.go @@ -39,13 +39,19 @@ type printer struct { pos token.Position // current pos in AST lineout line - lastTok token.Token // last token printed (syntax.ILLEGAL if it's whitespace) + lastTok token.Token // last token printed ([token.ILLEGAL] if it's whitespace) output []byte indent int spaceBefore bool prevLbraceOnLine bool // true if a '{' has been written on the current line + // TODO(mvdan): This is similar to nooverride but used only for comments, + // to ensure that we always print a newline after them. + // We should fix our logic with whiteSpace instead, but for now this ensures + // we don't break the syntax by omitting the newline after a comment. + printingComment bool + errs errors.Error } @@ -92,7 +98,7 @@ func (p *printer) Print(v interface{}) { // the previous and the current token must be // separated by a blank otherwise they combine // into a different incorrect token sequence - // (except for syntax.INT followed by a '.' this + // (except for token.INT followed by a '.' this // should never happen because it is taken care // of via binary expression formatting) if p.allowed&blank != 0 { @@ -231,6 +237,9 @@ func (p *printer) Print(v interface{}) { case token.NewSection: requested |= newsection } + if p.printingComment { + requested |= newline + } p.writeWhitespace(requested) p.allowed = 0 p.requested = 0 @@ -247,6 +256,7 @@ func (p *printer) Print(v interface{}) { p.writeWhitespace(p.allowed) p.allowed = 0 p.requested = 0 + p.printingComment = false p.writeString(data, isLit) p.allowed = nextWS _ = impliedComma // TODO: delay comment printings @@ -415,9 +425,18 @@ func (p *printer) writeByte(ch byte, n int) { p.pos.Column += n } +// TODO(mvdan): mayCombine as a name was carried over from Go, +// but it doesn't really make sense as a name for our logic here, +// since we return true when either side must use a blank space. + func mayCombine(prev, next token.Token) (before, after bool) { s := next.String() if 'a' <= s[0] && s[0] < 'z' { + if prev == token.ILLEGAL { + // If we're printing the first token, + // we don't need a blank space before it. + return false, true + } return true, true } switch prev { diff --git a/vendor/cuelang.org/go/cue/instance.go b/vendor/cuelang.org/go/cue/instance.go index cea6ffc33a..13d54ddb92 100644 --- a/vendor/cuelang.org/go/cue/instance.go +++ b/vendor/cuelang.org/go/cue/instance.go @@ -23,7 +23,7 @@ import ( "cuelang.org/go/internal/core/runtime" ) -// An InstanceOrValue is implemented by [Value] and *[Instance]. +// An InstanceOrValue is implemented by [Value] and [*Instance]. // // This is a placeholder type that is used to allow Instance-based APIs to // transition to Value-based APIs. The goals is to get rid of the Instance @@ -165,17 +165,6 @@ func (inst *Instance) setListOrError(err errors.Error) { inst.Err = errors.Append(inst.Err, err) } -func (inst *Instance) setError(err errors.Error) { - inst.Incomplete = true - inst.Err = errors.Append(inst.Err, err) -} - -func (inst *Instance) eval(ctx *adt.OpContext) adt.Value { - // TODO: remove manifest here? - v := manifest(ctx, inst.root) - return v -} - // ID returns the package identifier that uniquely qualifies module and // package name. func (inst *Instance) ID() string { @@ -185,13 +174,6 @@ func (inst *Instance) ID() string { return inst.inst.ID() } -// Doc returns the package comments for this instance. -// -// Deprecated: use inst.Value().Doc() -func (inst *hiddenInstance) Doc() []*ast.CommentGroup { - return inst.Value().Doc() -} - // Value returns the root value of the configuration. If the configuration // defines in emit value, it will be that value. Otherwise it will be all // top-level values. @@ -256,6 +238,9 @@ func (inst *hiddenInstance) Build(p *build.Instance) *Instance { cfg := &compile.Config{Scope: valueScope(Value{idx: r, v: inst.root})} v, err := compile.Files(cfg, r, p.ID(), p.Files...) + // Just like [runtime.Runtime.Build], ensure that the @embed compiler is run as needed. + err = errors.Append(err, r.InjectImplementations(p, v)) + v.AddConjunct(adt.MakeRootConjunct(nil, inst.root)) i := newInstance(idx, p, v) diff --git a/vendor/cuelang.org/go/cue/literal/indent.go b/vendor/cuelang.org/go/cue/literal/indent.go index 193ca3b440..5a064aaeb9 100644 --- a/vendor/cuelang.org/go/cue/literal/indent.go +++ b/vendor/cuelang.org/go/cue/literal/indent.go @@ -19,7 +19,7 @@ import "strings" // IndentTabs takes a quoted string and reindents it for the given indentation. // If a string is not a multiline string it will return the string as is. func IndentTabs(s string, n int) string { - indent := tabs(n) + indent := strings.Repeat("\t", n) qi, _, _, err := ParseQuotes(s, s) if err != nil || !qi.multiline || qi.whitespace == indent { diff --git a/vendor/cuelang.org/go/cue/literal/quote.go b/vendor/cuelang.org/go/cue/literal/quote.go index bcf8e78a08..2208e2cf7f 100644 --- a/vendor/cuelang.org/go/cue/literal/quote.go +++ b/vendor/cuelang.org/go/cue/literal/quote.go @@ -48,29 +48,15 @@ type Form struct { // WithTabIndent returns a new Form with indentation set to the given number // of tabs. The result will be a multiline string. func (f Form) WithTabIndent(n int) Form { - f.indent = tabs(n) + f.indent = strings.Repeat("\t", n) f.multiline = true return f } -const tabIndent = "\t\t\t\t\t\t\t\t\t\t\t\t" - -func tabs(n int) string { - if n < len(tabIndent) { - return tabIndent[:n] - } - return strings.Repeat("\t", n) -} - // WithOptionalIndent is like WithTabIndent, but only returns a multiline // strings if it doesn't contain any newline characters. func (f Form) WithOptionalTabIndent(tabs int) Form { - // TODO(mvdan): remove this optimization once Go 1.23 lands with https://go.dev/cl/536615 - if tabs < len(tabIndent) { - f.indent = tabIndent[:tabs] - } else { - f.indent = strings.Repeat("\t", tabs) - } + f.indent = strings.Repeat("\t", tabs) f.auto = true return f } @@ -143,7 +129,7 @@ func (f Form) Append(buf []byte, s string) []byte { copy(nBuf, buf) buf = nBuf } - for i := 0; i < f.hashCount; i++ { + for range f.hashCount { buf = append(buf, '#') } if f.multiline { @@ -169,7 +155,7 @@ func (f Form) Append(buf []byte, s string) []byte { } else { buf = append(buf, f.quote) } - for i := 0; i < f.hashCount; i++ { + for range f.hashCount { buf = append(buf, '#') } @@ -234,7 +220,7 @@ func (f *Form) appendEscapedRune(buf []byte, r rune) []byte { buf = append(buf, byte(r)) return buf } - } else if strconv.IsPrint(r) || f.graphicOnly && isInGraphicList(r) { + } else if strconv.IsPrint(r) || (f.graphicOnly && strconv.IsGraphic(r)) { buf = utf8.AppendRune(buf, r) return buf } @@ -280,7 +266,7 @@ func (f *Form) appendEscapedRune(buf []byte, r rune) []byte { func (f *Form) appendEscape(buf []byte) []byte { buf = append(buf, '\\') - for i := 0; i < f.hashCount; i++ { + for range f.hashCount { buf = append(buf, '#') } return buf @@ -319,51 +305,3 @@ func (f *Form) requiredHashCount(s string) int { } return hashCount } - -// isInGraphicList reports whether the rune is in the isGraphic list. This separation -// from IsGraphic allows quoteWith to avoid two calls to IsPrint. -// Should be called only if IsPrint fails. -func isInGraphicList(r rune) bool { - // We know r must fit in 16 bits - see makeisprint.go. - if r > 0xFFFF { - return false - } - rr := uint16(r) - i := bsearch16(isGraphic, rr) - return i < len(isGraphic) && rr == isGraphic[i] -} - -// bsearch16 returns the smallest i such that a[i] >= x. -// If there is no such i, bsearch16 returns len(a). -func bsearch16(a []uint16, x uint16) int { - i, j := 0, len(a) - for i < j { - h := i + (j-i)/2 - if a[h] < x { - i = h + 1 - } else { - j = h - } - } - return i -} - -// isGraphic lists the graphic runes not matched by IsPrint. -var isGraphic = []uint16{ - 0x00a0, - 0x1680, - 0x2000, - 0x2001, - 0x2002, - 0x2003, - 0x2004, - 0x2005, - 0x2006, - 0x2007, - 0x2008, - 0x2009, - 0x200a, - 0x202f, - 0x205f, - 0x3000, -} diff --git a/vendor/cuelang.org/go/cue/literal/string.go b/vendor/cuelang.org/go/cue/literal/string.go index 769470dfde..e43b093bb5 100644 --- a/vendor/cuelang.org/go/cue/literal/string.go +++ b/vendor/cuelang.org/go/cue/literal/string.go @@ -142,7 +142,7 @@ func ParseQuotes(start, end string) (q QuoteInfo, nStart, nEnd int, err error) { // are replaced with the corresponding non-surrogate code points. func (q QuoteInfo) Unquote(s string) (string, error) { if len(s) > 0 && !q.multiline { - if contains(s, '\n') || contains(s, '\r') { + if strings.ContainsAny(s, "\n\r") { return "", errSyntax } @@ -266,16 +266,6 @@ func isSimple(s string, quote rune) bool { return true } -// contains reports whether the string contains the byte c. -func contains(s string, c byte) bool { - for i := 0; i < len(s); i++ { - if s[i] == c { - return true - } - } - return false -} - const ( terminatedByQuote = rune(-1) terminatedByExpr = rune(-2) diff --git a/vendor/cuelang.org/go/cue/load/config.go b/vendor/cuelang.org/go/cue/load/config.go index 8506a4ef83..738b57d083 100644 --- a/vendor/cuelang.org/go/cue/load/config.go +++ b/vendor/cuelang.org/go/cue/load/config.go @@ -26,7 +26,6 @@ import ( "cuelang.org/go/cue/errors" "cuelang.org/go/cue/token" "cuelang.org/go/internal" - "cuelang.org/go/internal/cueexperiment" "cuelang.org/go/mod/modconfig" "cuelang.org/go/mod/modfile" "cuelang.org/go/mod/module" @@ -128,10 +127,12 @@ type Config struct { // Context specifies the context for the load operation. Context *build.Context - // A Module is a collection of packages and instances that are within the - // directory hierarchy rooted at the module root. The module root can be - // marked with a cue.mod file. - // If this is a relative path, it will be interpreted relative to [Config.Dir]. + // ModuleRoot is the directory that contains the cue.mod directory + // as well as all the packages which form part of the module being loaded. + // + // If left as the empty string, a module root is found by walking parent directories + // starting from [Config.Dir] until one is found containing a cue.mod directory. + // If it is a relative path, it will be interpreted relative to [Config.Dir]. ModuleRoot string // Module specifies the module prefix. If not empty, this value must match @@ -235,10 +236,6 @@ type Config struct { // Include all files, regardless of tags. AllCUEFiles bool - // Deprecated: use Tags - BuildTags []string - releaseTags []string - // If Tests is set, the loader includes not just the packages // matching a particular pattern but also any related test packages. Tests bool @@ -247,15 +244,17 @@ type Config struct { // a package. Tools bool + // SkipImports causes the loading to ignore all imports and dependencies. + // The registry will never be consulted. Any external package paths + // mentioned on the command line will result in an error. + // The [cue/build.Instance.Imports] field will be empty. + SkipImports bool + // If DataFiles is set, the loader includes entries for directories that // have no CUE files, but have recognized data files that could be converted // to CUE. DataFiles bool - // StdRoot specifies an alternative directory for standard libraries. - // Deprecated: this has no effect. - StdRoot string - // ParseFile is called to read and parse each file when preparing a // package's syntax tree. It must be safe to call ParseFile simultaneously // from multiple goroutines. If ParseFile is nil, the loader will uses @@ -280,13 +279,13 @@ type Config struct { // Registry is used to fetch CUE module dependencies. // - // When nil, if the modules experiment is enabled - // (CUE_EXPERIMENT=modules), [modconfig.NewRegistry] - // will be used to create a registry instance using the - // usual cmd/cue conventions for environment variables - // (but see the Env field below). + // When nil, [modconfig.NewRegistry] will be used to create a + // registry instance using the variables set in [Config.Env] + // as documented in `[cue help registryconfig]`. // // THIS IS EXPERIMENTAL. API MIGHT CHANGE. + // + // [cue help registryconfig]: https://cuelang.org/docs/reference/command/cue-help-registryconfig/ Registry modconfig.Registry // Env provides environment variables for use in the configuration. @@ -295,7 +294,7 @@ type Config struct { // will be used. Env []string - fileSystem fileSystem + fileSystem *fileSystem } func (c *Config) stdin() io.Reader { @@ -307,13 +306,14 @@ func (c *Config) stdin() io.Reader { type importPath string -type fsPath string - func addImportQualifier(pkg importPath, name string) (importPath, error) { if name == "" { return pkg, nil } ip := module.ParseImportPath(string(pkg)) + if ip.Qualifier == "_" { + return "", fmt.Errorf("invalid import qualifier _ in %q", pkg) + } if ip.ExplicitQualifier && ip.Qualifier != name { return "", fmt.Errorf("non-matching package names (%s != %s)", ip.Qualifier, name) } @@ -333,13 +333,6 @@ func addImportQualifier(pkg importPath, name string) (importPath, error) { // It does not initialize c.Context, because that requires the // loader in order to use for build.Loader. func (c Config) complete() (cfg *Config, err error) { - // Each major CUE release should add a tag here. - // Old tags should not be removed. That is, the cue1.x tag is present - // in all releases >= CUE 1.x. Code that requires CUE 1.x or later should - // say "+build cue1.x", and code that should only be built before CUE 1.x - // (perhaps it is the stub to use in that case) should say "+build !cue1.x". - c.releaseTags = []string{"cue0.1"} - if c.Dir == "" { c.Dir, err = os.Getwd() if err != nil { @@ -351,9 +344,11 @@ func (c Config) complete() (cfg *Config, err error) { // TODO: we could populate this already with absolute file paths, // but relative paths cannot be added. Consider what is reasonable. - if err := c.fileSystem.init(c.Dir, c.Overlay); err != nil { + fsys, err := newFileSystem(&c) + if err != nil { return nil, err } + c.fileSystem = fsys // TODO: determine root on a package basis. Maybe we even need a // pkgname.cue.mod @@ -371,10 +366,11 @@ func (c Config) complete() (cfg *Config, err error) { } else if !filepath.IsAbs(c.ModuleRoot) { c.ModuleRoot = filepath.Join(c.Dir, c.ModuleRoot) } - // Note: if cueexperiment.Flags.Modules _isn't_ set but c.Registry - // is, we consider that a good enough hint that modules support - // should be enabled and hence don't return an error in that case. - if cueexperiment.Flags.Modules && c.Registry == nil { + if c.SkipImports { + // We should never use the registry in SkipImports mode + // but nil it out to be sure. + c.Registry = nil + } else if c.Registry == nil { registry, err := modconfig.NewRegistry(&modconfig.Config{ Env: c.Env, }) @@ -395,19 +391,21 @@ func (c Config) complete() (cfg *Config, err error) { // loadModule loads the module file, resolves and downloads module // dependencies. It sets c.Module if it's empty or checks it for // consistency with the module file otherwise. +// +// Note that this function is a no-op if a module file does not exist, +// as it is still possible to load CUE without a module. func (c *Config) loadModule() error { // TODO: also make this work if run from outside the module? - mod := filepath.Join(c.ModuleRoot, modDir) - info, cerr := c.fileSystem.stat(mod) - if cerr != nil { - return nil - } - if !info.IsDir() { - return fmt.Errorf("cue.mod files are no longer supported; use cue.mod/module.cue") - } - mod = filepath.Join(mod, moduleFile) - f, cerr := c.fileSystem.openFile(mod) + modDir := filepath.Join(c.ModuleRoot, modDir) + modFile := filepath.Join(modDir, moduleFile) + f, cerr := c.fileSystem.openFile(modFile) if cerr != nil { + // If we could not load cue.mod/module.cue, check whether the reason was + // a legacy cue.mod file and give the user a clear error message. + info, cerr2 := c.fileSystem.stat(modDir) + if cerr2 == nil && !info.IsDir() { + return fmt.Errorf("cue.mod files are no longer supported; use cue.mod/module.cue") + } return nil } defer f.Close() @@ -426,7 +424,7 @@ func (c *Config) loadModule() error { // module files have been discovered in the wild. parseModFile = modfile.FixLegacy } - mf, err := parseModFile(data, mod) + mf, err := parseModFile(data, modFile) if err != nil { return err } diff --git a/vendor/cuelang.org/go/cue/load/doc.go b/vendor/cuelang.org/go/cue/load/doc.go index 6be5c34346..781c91d02c 100644 --- a/vendor/cuelang.org/go/cue/load/doc.go +++ b/vendor/cuelang.org/go/cue/load/doc.go @@ -14,3 +14,9 @@ // Package load loads CUE instances. package load + +// Trigger the unconditional loading of all core builtin packages if load is used. +// This was deemed the simplest way to avoid having to import this line explicitly, +// and thus breaking existing code, for the majority of cases, +// while not introducing an import cycle. +import _ "cuelang.org/go/pkg" diff --git a/vendor/cuelang.org/go/cue/load/fs.go b/vendor/cuelang.org/go/cue/load/fs.go index 8ec96dce3d..4bc767d85f 100644 --- a/vendor/cuelang.org/go/cue/load/fs.go +++ b/vendor/cuelang.org/go/cue/load/fs.go @@ -24,11 +24,16 @@ import ( "path/filepath" "slices" "strings" + "sync" "time" + "cuelang.org/go/cue" "cuelang.org/go/cue/ast" + "cuelang.org/go/cue/build" + "cuelang.org/go/cue/cuecontext" "cuelang.org/go/cue/errors" "cuelang.org/go/cue/token" + "cuelang.org/go/internal/encoding" "cuelang.org/go/mod/module" ) @@ -56,6 +61,7 @@ func (f *overlayFile) Sys() interface{} { return nil } type fileSystem struct { overlayDirs map[string]map[string]*overlayFile cwd string + fileCache *fileCache } func (fs *fileSystem) getDir(dir string, create bool) map[string]*overlayFile { @@ -81,24 +87,22 @@ func (fs *fileSystem) getDir(dir string, create bool) map[string]*overlayFile { // paths required by most of the `cue/load` package // implementation. func (fs *fileSystem) ioFS(root string) iofs.FS { - dir := fs.getDir(root, false) - if dir == nil { - return module.OSDirFS(root) - } return &ioFS{ fs: fs, root: root, } } -func (fs *fileSystem) init(cwd string, overlay map[string]Source) error { - fs.cwd = cwd - fs.overlayDirs = map[string]map[string]*overlayFile{} +func newFileSystem(cfg *Config) (*fileSystem, error) { + fs := &fileSystem{ + cwd: cfg.Dir, + overlayDirs: map[string]map[string]*overlayFile{}, + } // Organize overlay - for filename, src := range overlay { + for filename, src := range cfg.Overlay { if !filepath.IsAbs(filename) { - return fmt.Errorf("non-absolute file path %q in overlay", filename) + return nil, fmt.Errorf("non-absolute file path %q in overlay", filename) } // TODO: do we need to further clean the path or check that the // specified files are within the root/ absolute files? @@ -106,7 +110,7 @@ func (fs *fileSystem) init(cwd string, overlay map[string]Source) error { m := fs.getDir(dir, true) b, file, err := src.contents() if err != nil { - return err + return nil, err } m[base] = &overlayFile{ basename: base, @@ -131,7 +135,8 @@ func (fs *fileSystem) init(cwd string, overlay map[string]Source) error { } } } - return nil + fs.fileCache = newFileCache(cfg) + return fs, nil } func (fs *fileSystem) makeAbs(path string) string { @@ -334,6 +339,49 @@ func (fs *ioFS) ReadFile(name string) ([]byte, error) { return os.ReadFile(fpath) } +var _ module.ReadCUEFS = (*ioFS)(nil) + +// ReadCUEFile implements [module.ReadCUEFS] by +// reading and updating the syntax file cache, which +// is shared with the cache used by the [fileSystem.getCUESyntax] +// method. +func (fs *ioFS) ReadCUEFile(path string) (*ast.File, error) { + fpath, err := fs.absPathFromFSPath(path) + if err != nil { + return nil, err + } + cache := fs.fs.fileCache + cache.mu.Lock() + entry, ok := cache.entries[fpath] + cache.mu.Unlock() + if ok { + return entry.file, entry.err + } + var data []byte + if fi := fs.fs.getOverlay(fpath); fi != nil { + if fi.file != nil { + // No need for a cache if we've got the contents in *ast.File + // form already. + return fi.file, nil + } + data = fi.contents + } else { + data, err = os.ReadFile(fpath) + if err != nil { + cache.mu.Lock() + defer cache.mu.Unlock() + cache.entries[fpath] = fileCacheEntry{nil, err} + return nil, err + } + } + return fs.fs.getCUESyntax(&build.File{ + Filename: fpath, + Encoding: build.CUE, + // Form: build.Schema, + Source: data, + }) +} + // ioFSFile implements [io/fs.File] for the overlay filesystem. type ioFSFile struct { fs *fileSystem @@ -384,3 +432,57 @@ func (f *ioFSFile) ReadDir(n int) ([]iofs.DirEntry, error) { f.entries = f.entries[n:] return entries, err } + +func (fs *fileSystem) getCUESyntax(bf *build.File) (*ast.File, error) { + fs.fileCache.mu.Lock() + defer fs.fileCache.mu.Unlock() + if bf.Encoding != build.CUE { + panic("getCUESyntax called with non-CUE file encoding") + } + // When it's a regular CUE file with no funny stuff going on, we + // check and update the syntax cache. + useCache := bf.Form == "" && bf.Interpretation == "" + if useCache { + if syntax, ok := fs.fileCache.entries[bf.Filename]; ok { + return syntax.file, syntax.err + } + } + d := encoding.NewDecoder(fs.fileCache.ctx, bf, &fs.fileCache.config) + defer d.Close() + // Note: CUE files can never have multiple file parts. + f, err := d.File(), d.Err() + if useCache { + fs.fileCache.entries[bf.Filename] = fileCacheEntry{f, err} + } + return f, err +} + +func newFileCache(c *Config) *fileCache { + return &fileCache{ + config: encoding.Config{ + // Note: no need to pass Stdin, as we take care + // always to pass a non-nil source when the file is "-". + ParseFile: c.ParseFile, + }, + ctx: cuecontext.New(), + entries: make(map[string]fileCacheEntry), + } +} + +// fileCache caches data derived from the file system. +type fileCache struct { + config encoding.Config + ctx *cue.Context + mu sync.Mutex + entries map[string]fileCacheEntry +} + +type fileCacheEntry struct { + // TODO cache directory information too. + + // file caches the work involved when decoding a file into an *ast.File. + // This can happen multiple times for the same file, for example when it is present in + // multiple different build instances in the same directory hierarchy. + file *ast.File + err error +} diff --git a/vendor/cuelang.org/go/cue/load/import.go b/vendor/cuelang.org/go/cue/load/import.go index 8140dfaccf..1015227bc2 100644 --- a/vendor/cuelang.org/go/cue/load/import.go +++ b/vendor/cuelang.org/go/cue/load/import.go @@ -19,7 +19,6 @@ import ( "fmt" "io" "io/fs" - "os" pathpkg "path" "path/filepath" "slices" @@ -72,7 +71,7 @@ func (l *loader) importPkg(pos token.Pos, p *build.Instance) []*build.Instance { defer l.stk.Pop() cfg := l.cfg - ctxt := &cfg.fileSystem + ctxt := cfg.fileSystem if p.Err != nil { return []*build.Instance{p} @@ -155,12 +154,17 @@ func (l *loader) importPkg(pos token.Pos, p *build.Instance) []*build.Instance { } return retErr(errors.Wrapf(err, token.NoPos, "import failed reading dir %v", dir)) } - p.UnknownFiles = append(p.UnknownFiles, sd.unknownFiles...) - for _, f := range sd.buildFiles { - bf := *f - fp.add(dir, &bf, importComment) + for _, name := range sd.filenames { + file, err := filetypes.ParseFileAndType(name, "", filetypes.Input) + if err != nil { + p.UnknownFiles = append(p.UnknownFiles, &build.File{ + Filename: name, + ExcludeReason: errors.Newf(token.NoPos, "unknown filetype"), + }) + } else { + fp.add(dir, file, 0) + } } - if p.PkgName == "" || !inModule || l.cfg.isModRoot(dir) || dir == d[0] { break } @@ -188,6 +192,16 @@ func (l *loader) importPkg(pos token.Pos, p *build.Instance) []*build.Instance { p.ReportError(errors.Promote(err, "")) } + if len(p.BuildFiles) == 0 && + len(p.IgnoredFiles) == 0 && + len(p.OrphanedFiles) == 0 && + len(p.InvalidFiles) == 0 && + len(p.UnknownFiles) == 0 { + // The package has no files in it. This can happen + // when the default package added in newFileProcessor + // doesn't have any associated files. + continue + } all = append(all, p) rewriteFiles(p, cfg.ModuleRoot, false) if errs := fp.finalize(p); errs != nil { @@ -210,33 +224,32 @@ func (l *loader) importPkg(pos token.Pos, p *build.Instance) []*build.Instance { return all } -func (l *loader) scanDir(dir string) cachedFileFiles { - sd := cachedFileFiles{} +func (l *loader) scanDir(dir string) cachedDirFiles { files, err := l.cfg.fileSystem.readDir(dir) if err != nil { - sd.err = err - return sd + return cachedDirFiles{ + err: err, + } } + filenames := make([]string, 0, len(files)) for _, f := range files { if f.IsDir() { continue } - if f.Name() == "-" { - if _, err := l.cfg.fileSystem.stat("-"); !os.IsNotExist(err) { - continue - } + name := f.Name() + if name == "-" { + // The name "-" has a special significance to the file types + // logic, but only when specified directly on the command line. + // We don't want an actual file named "-" to have special + // significant, so avoid that by making sure we don't see a naked "-" + // even when a file named "-" is present in a directory. + name = "./-" } - file, err := filetypes.ParseFile(f.Name(), filetypes.Input) - if err != nil { - sd.unknownFiles = append(sd.unknownFiles, &build.File{ - Filename: f.Name(), - ExcludeReason: errors.Newf(token.NoPos, "unknown filetype"), - }) - continue // skip unrecognized file types - } - sd.buildFiles = append(sd.buildFiles, file) + filenames = append(filenames, name) + } + return cachedDirFiles{ + filenames: filenames, } - return sd } func setFileSource(cfg *Config, f *build.File) error { @@ -267,7 +280,14 @@ func setFileSource(cfg *Config, f *build.File) error { return nil } -func (l *loader) loadFunc(pos token.Pos, path string) *build.Instance { +func (l *loader) loadFunc() build.LoadFunc { + if l.cfg.SkipImports { + return nil + } + return l._loadFunc +} + +func (l *loader) _loadFunc(pos token.Pos, path string) *build.Instance { impPath := importPath(path) if isLocalImport(path) { return l.cfg.newErrInstance(errors.Newf(pos, "relative import paths not allowed (%q)", path)) @@ -290,7 +310,7 @@ func (l *loader) newRelInstance(pos token.Pos, path, pkgName string) *build.Inst panic(fmt.Errorf("non-relative import path %q passed to newRelInstance", path)) } - p := l.cfg.Context.NewInstance(path, l.loadFunc) + p := l.cfg.Context.NewInstance(path, l.loadFunc()) p.PkgName = pkgName p.DisplayPath = filepath.ToSlash(path) // p.ImportPath = string(dir) // compute unique ID. @@ -365,8 +385,8 @@ func importPathFromAbsDir(c *Config, absDir string, origPath string) (importPath } func (l *loader) newInstance(pos token.Pos, p importPath) *build.Instance { - dir, err := l.absDirFromImportPath(pos, p) - i := l.cfg.Context.NewInstance(dir, l.loadFunc) + dir, modPath, err := l.absDirFromImportPath(pos, p) + i := l.cfg.Context.NewInstance(dir, l.loadFunc()) i.Err = errors.Append(i.Err, err) i.Dir = dir @@ -374,11 +394,13 @@ func (l *loader) newInstance(pos token.Pos, p importPath) *build.Instance { i.PkgName = parts.Qualifier if i.PkgName == "" { i.Err = errors.Append(i.Err, l.errPkgf([]token.Pos{pos}, "cannot determine package name for %q; set it explicitly with ':'", p)) + } else if i.PkgName == "_" { + i.Err = errors.Append(i.Err, l.errPkgf([]token.Pos{pos}, "_ is not a valid import path qualifier in %q", p)) } i.DisplayPath = string(p) i.ImportPath = string(p) i.Root = l.cfg.ModuleRoot - i.Module = l.cfg.Module + i.Module = modPath return i } @@ -387,85 +409,68 @@ func (l *loader) newInstance(pos token.Pos, p importPath) *build.Instance { // and a package name. The root directory must be set. // // The returned directory may not exist. -func (l *loader) absDirFromImportPath(pos token.Pos, p importPath) (string, errors.Error) { - dir, err := l.absDirFromImportPath1(pos, p) +func (l *loader) absDirFromImportPath(pos token.Pos, p importPath) (dir string, modPath string, _ errors.Error) { + dir, modPath, err := l.absDirFromImportPath1(pos, p) if err != nil { // Any error trying to determine the package location // is a PackageError. - return "", l.errPkgf([]token.Pos{pos}, "%s", err.Error()) + return "", "", l.errPkgf([]token.Pos{pos}, "%s", err.Error()) } - return dir, nil + return dir, modPath, nil } -func (l *loader) absDirFromImportPath1(pos token.Pos, p importPath) (absDir string, err error) { +func (l *loader) absDirFromImportPath1(pos token.Pos, p importPath) (absDir string, modPath string, err error) { if p == "" { - return "", fmt.Errorf("empty import path") + return "", "", fmt.Errorf("empty import path") } if l.cfg.ModuleRoot == "" { - return "", fmt.Errorf("cannot import %q (root undefined)", p) + return "", "", fmt.Errorf("cannot import %q (root undefined)", p) } if isStdlibPackage(string(p)) { - return "", fmt.Errorf("standard library import path %q cannot be imported as a CUE package", p) + return "", "", fmt.Errorf("standard library import path %q cannot be imported as a CUE package", p) + } + if l.pkgs == nil { + return "", "", fmt.Errorf("imports are unavailable because there is no cue.mod/module.cue file") } // Extract the package name. parts := module.ParseImportPath(string(p)) unqualified := parts.Unqualified().String() - if l.cfg.Registry != nil { - if l.pkgs == nil { - return "", fmt.Errorf("imports are unavailable because there is no cue.mod/module.cue file") - } - // TODO predicate registry-aware lookup on module.cue-declared CUE version? - - // Note: use the canonical form of the import path because - // that's the form passed to [modpkgload.LoadPackages] - // and hence it's available by that name via Pkg. - pkg := l.pkgs.Pkg(parts.Canonical().String()) - // TODO(mvdan): using "unqualified" for the errors below doesn't seem right, - // should we not be using either the original path or the canonical path? - // The unqualified import path should only be used for filepath.FromSlash further below. - if pkg == nil { - return "", fmt.Errorf("no dependency found for package %q", unqualified) + // TODO predicate registry-aware lookup on module.cue-declared CUE version? + + // Note: use the canonical form of the import path because + // that's the form passed to [modpkgload.LoadPackages] + // and hence it's available by that name via Pkg. + pkg := l.pkgs.Pkg(parts.Canonical().String()) + // TODO(mvdan): using "unqualified" for the errors below doesn't seem right, + // should we not be using either the original path or the canonical path? + // The unqualified import path should only be used for filepath.FromSlash further below. + if pkg == nil { + return "", "", fmt.Errorf("no dependency found for package %q", unqualified) + } + if err := pkg.Error(); err != nil { + return "", "", fmt.Errorf("cannot find package %q: %v", unqualified, err) + } + if mv := pkg.Mod(); mv.IsLocal() { + // It's a local package that's present inside one or both of the gen, usr or pkg + // directories. Even though modpkgload tells us exactly what those directories + // are, the rest of the cue/load logic expects only a single directory for now, + // so just use that. + absDir = filepath.Join(GenPath(l.cfg.ModuleRoot), parts.Path) + } else { + locs := pkg.Locations() + if len(locs) > 1 { + return "", "", fmt.Errorf("package %q unexpectedly found in multiple locations", unqualified) } - if err := pkg.Error(); err != nil { - return "", fmt.Errorf("cannot find package %q: %v", unqualified, err) + if len(locs) == 0 { + return "", "", fmt.Errorf("no location found for package %q", unqualified) } - if mv := pkg.Mod(); mv.IsLocal() { - // It's a local package that's present inside one or both of the gen, usr or pkg - // directories. Even though modpkgload tells us exactly what those directories - // are, the rest of the cue/load logic expects only a single directory for now, - // so just use that. - absDir = filepath.Join(GenPath(l.cfg.ModuleRoot), parts.Path) - } else { - locs := pkg.Locations() - if len(locs) > 1 { - return "", fmt.Errorf("package %q unexpectedly found in multiple locations", unqualified) - } - if len(locs) == 0 { - return "", fmt.Errorf("no location found for package %q", unqualified) - } - var err error - absDir, err = absPathForSourceLoc(locs[0]) - if err != nil { - return "", fmt.Errorf("cannot determine source directory for package %q: %v", unqualified, err) - } + var err error + absDir, err = absPathForSourceLoc(locs[0]) + if err != nil { + return "", "", fmt.Errorf("cannot determine source directory for package %q: %v", unqualified, err) } - return absDir, nil - } - - // Determine the directory without using the registry. - - sub := filepath.FromSlash(unqualified) - switch hasPrefix := strings.HasPrefix(unqualified, l.cfg.Module); { - case hasPrefix && len(sub) == len(l.cfg.Module): - absDir = l.cfg.ModuleRoot - - case hasPrefix && unqualified[len(l.cfg.Module)] == '/': - absDir = filepath.Join(l.cfg.ModuleRoot, sub[len(l.cfg.Module)+1:]) - - default: - absDir = filepath.Join(GenPath(l.cfg.ModuleRoot), sub) } - return absDir, err + return absDir, pkg.Mod().Path(), nil } func absPathForSourceLoc(loc module.SourceLoc) (string, error) { diff --git a/vendor/cuelang.org/go/cue/load/instances.go b/vendor/cuelang.org/go/cue/load/instances.go index 9bf0a49f20..7488549035 100644 --- a/vendor/cuelang.org/go/cue/load/instances.go +++ b/vendor/cuelang.org/go/cue/load/instances.go @@ -17,22 +17,18 @@ package load import ( "context" "fmt" - "sort" + "io/fs" + "slices" "strconv" + "strings" "cuelang.org/go/cue/ast" "cuelang.org/go/cue/build" - "cuelang.org/go/internal/cueexperiment" "cuelang.org/go/internal/filetypes" + "cuelang.org/go/internal/mod/modimports" "cuelang.org/go/internal/mod/modpkgload" "cuelang.org/go/internal/mod/modrequirements" "cuelang.org/go/mod/module" - - // Trigger the unconditional loading of all core builtin packages if load - // is used. This was deemed the simplest way to avoid having to import - // this line explicitly, and thus breaking existing code, for the majority - // of cases, while not introducing an import cycle. - _ "cuelang.org/go/pkg" ) // Instances returns the instances named by the command line arguments 'args'. @@ -45,11 +41,6 @@ func Instances(args []string, c *Config) []*build.Instance { if c == nil { c = &Config{} } - // We want to consult the CUE_EXPERIMENT flag to see whether - // consult external registries by default. - if err := cueexperiment.Init(); err != nil { - return []*build.Instance{c.newErrInstance(err)} - } newC, err := c.complete() if err != nil { return []*build.Instance{c.newErrInstance(err)} @@ -93,7 +84,6 @@ func Instances(args []string, c *Config) []*build.Instance { pkgArgs = pkgArgs1 } - synCache := newSyntaxCache(c) tg := newTagger(c) // Pass all arguments that look like packages to loadPackages // so that they'll be available when looking up the packages @@ -102,17 +92,24 @@ func Instances(args []string, c *Config) []*build.Instance { if err != nil { return []*build.Instance{c.newErrInstance(err)} } - pkgs, err := loadPackages(ctx, c, synCache, expandedPaths, otherFiles) - if err != nil { - return []*build.Instance{c.newErrInstance(err)} + + var pkgs *modpkgload.Packages + if !c.SkipImports { + pkgs, err = loadPackages(ctx, c, expandedPaths, otherFiles, tg) + if err != nil { + return []*build.Instance{c.newErrInstance(err)} + } } - l := newLoader(c, tg, synCache, pkgs) + l := newLoader(c, tg, pkgs) if c.Context == nil { - c.Context = build.NewContext( - build.Loader(l.loadFunc), + opts := []build.Option{ build.ParseFile(c.ParseFile), - ) + } + if f := l.loadFunc(); l != nil { + opts = append(opts, build.Loader(f)) + } + c.Context = build.NewContext(opts...) } a := []*build.Instance{} @@ -169,12 +166,19 @@ func Instances(args []string, c *Config) []*build.Instance { // loadPackages returns packages loaded from the given package list and also // including imports from the given build files. -func loadPackages(ctx context.Context, cfg *Config, synCache *syntaxCache, pkgs []resolvedPackageArg, otherFiles []*build.File) (*modpkgload.Packages, error) { - if cfg.Registry == nil || cfg.modFile == nil || cfg.modFile.Module == "" { +func loadPackages( + ctx context.Context, + cfg *Config, + pkgs []resolvedPackageArg, + otherFiles []*build.File, + tg *tagger, +) (*modpkgload.Packages, error) { + if cfg.modFile == nil || cfg.modFile.Module == "" { return nil, nil } + mainModPath := cfg.modFile.QualifiedModule() reqs := modrequirements.NewRequirements( - cfg.modFile.QualifiedModule(), + mainModPath, cfg.Registry, cfg.modFile.DepVersions(), cfg.modFile.DefaultMajorVersions(), @@ -194,21 +198,19 @@ func loadPackages(ctx context.Context, cfg *Config, synCache *syntaxCache, pkgs // not a CUE file; assume it has no imports for now. continue } - syntaxes, err := synCache.getSyntax(f) + syntax, err := cfg.fileSystem.getCUESyntax(f) if err != nil { - return nil, fmt.Errorf("cannot get syntax for %q: %v", f.Filename, err) + return nil, fmt.Errorf("cannot get syntax for %q: %w", f.Filename, err) } - for _, syntax := range syntaxes { - for _, imp := range syntax.Imports { - pkgPath, err := strconv.Unquote(imp.Path.Value) - if err != nil { - // Should never happen. - return nil, fmt.Errorf("invalid import path %q in %s", imp.Path.Value, f.Filename) - } - // Canonicalize the path. - pkgPath = module.ParseImportPath(pkgPath).Canonical().String() - pkgPaths[pkgPath] = true + for _, imp := range syntax.Imports { + pkgPath, err := strconv.Unquote(imp.Path.Value) + if err != nil { + // Should never happen. + return nil, fmt.Errorf("invalid import path %q in %s", imp.Path.Value, f.Filename) } + // Canonicalize the path. + pkgPath = module.ParseImportPath(pkgPath).Canonical().String() + pkgPaths[pkgPath] = true } } // TODO use maps.Keys when we can. @@ -216,7 +218,7 @@ func loadPackages(ctx context.Context, cfg *Config, synCache *syntaxCache, pkgs for p := range pkgPaths { pkgPathSlice = append(pkgPathSlice, p) } - sort.Strings(pkgPathSlice) + slices.Sort(pkgPathSlice) return modpkgload.LoadPackages( ctx, cfg.Module, @@ -224,5 +226,34 @@ func loadPackages(ctx context.Context, cfg *Config, synCache *syntaxCache, pkgs reqs, cfg.Registry, pkgPathSlice, + func(pkgPath string, mod module.Version, fsys fs.FS, mf modimports.ModuleFile) bool { + if !cfg.Tools && strings.HasSuffix(mf.FilePath, "_tool.cue") { + return false + } + isTest := strings.HasSuffix(mf.FilePath, "_test.cue") + var tagIsSet func(string) bool + if mod.Path() == mainModPath { + // In the main module. + if isTest && !cfg.Tests { + return false + } + tagIsSet = tg.tagIsSet + } else { + // Outside the main module. + if isTest { + // Don't traverse test files outside the main module + return false + } + // Treat all build tag keys as unset. + tagIsSet = func(string) bool { + return false + } + } + if err := shouldBuildFile(mf.Syntax, tagIsSet); err != nil { + // Later build logic should pick up and report the same error. + return false + } + return true + }, ), nil } diff --git a/vendor/cuelang.org/go/cue/load/loader.go b/vendor/cuelang.org/go/cue/load/loader.go index eed3e743da..b17ccbaa60 100644 --- a/vendor/cuelang.org/go/cue/load/loader.go +++ b/vendor/cuelang.org/go/cue/load/loader.go @@ -22,20 +22,10 @@ package load import ( "path/filepath" - "cuelang.org/go/cue" - "cuelang.org/go/cue/ast" "cuelang.org/go/cue/build" - "cuelang.org/go/cue/cuecontext" "cuelang.org/go/cue/errors" "cuelang.org/go/cue/token" - "cuelang.org/go/internal/encoding" "cuelang.org/go/internal/mod/modpkgload" - - // Trigger the unconditional loading of all core builtin packages if load - // is used. This was deemed the simplest way to avoid having to import - // this line explicitly, and thus breaking existing code, for the majority - // of cases, while not introducing an import cycle. - _ "cuelang.org/go/pkg" ) type loader struct { @@ -44,33 +34,25 @@ type loader struct { stk importStack pkgs *modpkgload.Packages - // syntaxCache caches the work involved when decoding a file into an *ast.File. - // This can happen multiple times for the same file, for example when it is present in - // multiple different build instances in the same directory hierarchy. - syntaxCache *syntaxCache - - // dirCachedBuildFiles caches the work involved when reading a directory - // and determining what build files it contains. - // It is keyed by directory name. - // When we descend into subdirectories to load patterns such as ./... - // we often end up loading parent directories many times over; - // this cache amortizes that work. - dirCachedBuildFiles map[string]cachedFileFiles + // dirCachedBuildFiles caches the work involved when reading a + // directory. It is keyed by directory name. When we descend into + // subdirectories to load patterns such as ./... we often end up + // loading parent directories many times over; this cache + // amortizes that work. + dirCachedBuildFiles map[string]cachedDirFiles } -type cachedFileFiles struct { - err errors.Error - buildFiles []*build.File - unknownFiles []*build.File +type cachedDirFiles struct { + err errors.Error + filenames []string } -func newLoader(c *Config, tg *tagger, syntaxCache *syntaxCache, pkgs *modpkgload.Packages) *loader { +func newLoader(c *Config, tg *tagger, pkgs *modpkgload.Packages) *loader { return &loader{ cfg: c, tagger: tg, pkgs: pkgs, - dirCachedBuildFiles: map[string]cachedFileFiles{}, - syntaxCache: syntaxCache, + dirCachedBuildFiles: make(map[string]cachedDirFiles), } } @@ -94,7 +76,7 @@ func (l *loader) errPkgf(importPos []token.Pos, format string, args ...interface // (typically named on the command line). func (l *loader) cueFilesPackage(files []*build.File) *build.Instance { // ModInit() // TODO: support modules - pkg := l.cfg.Context.NewInstance(l.cfg.Dir, l.loadFunc) + pkg := l.cfg.Context.NewInstance(l.cfg.Dir, l.loadFunc()) for _, bf := range files { f := bf.Filename @@ -150,50 +132,10 @@ func (l *loader) cueFilesPackage(files []*build.File) *build.Instance { // addFiles populates p.Files by reading CUE syntax from p.BuildFiles. func (l *loader) addFiles(p *build.Instance) { for _, bf := range p.BuildFiles { - files, err := l.syntaxCache.getSyntax(bf) + f, err := l.cfg.fileSystem.getCUESyntax(bf) if err != nil { p.ReportError(errors.Promote(err, "load")) } - for _, f := range files { - _ = p.AddSyntax(f) - } - } -} - -type syntaxCache struct { - config encoding.Config - ctx *cue.Context - cache map[string]syntaxCacheEntry -} - -type syntaxCacheEntry struct { - err error - files []*ast.File -} - -func newSyntaxCache(cfg *Config) *syntaxCache { - return &syntaxCache{ - config: encoding.Config{ - Stdin: cfg.stdin(), - ParseFile: cfg.ParseFile, - }, - ctx: cuecontext.New(), - cache: make(map[string]syntaxCacheEntry), - } -} - -// getSyntax returns the CUE syntax corresponding to the file argument f. -func (c *syntaxCache) getSyntax(bf *build.File) ([]*ast.File, error) { - syntax, ok := c.cache[bf.Filename] - if ok { - return syntax.files, syntax.err - } - d := encoding.NewDecoder(c.ctx, bf, &c.config) - for ; !d.Done(); d.Next() { - syntax.files = append(syntax.files, d.File()) + _ = p.AddSyntax(f) } - d.Close() - syntax.err = d.Err() - c.cache[bf.Filename] = syntax - return syntax.files, syntax.err } diff --git a/vendor/cuelang.org/go/cue/load/loader_common.go b/vendor/cuelang.org/go/cue/load/loader_common.go index e5544a36e7..37af722f95 100644 --- a/vendor/cuelang.org/go/cue/load/loader_common.go +++ b/vendor/cuelang.org/go/cue/load/loader_common.go @@ -15,20 +15,15 @@ package load import ( - "bytes" "cmp" pathpkg "path" "path/filepath" "slices" - "sort" "strconv" "strings" - "unicode" - "unicode/utf8" "cuelang.org/go/cue/build" "cuelang.org/go/cue/errors" - "cuelang.org/go/cue/parser" "cuelang.org/go/cue/token" ) @@ -36,16 +31,19 @@ import ( type importMode uint const ( - // If importComment is set, parse import comments on package statements. - // Import returns an error if it finds a comment it cannot understand - // or finds conflicting comments in multiple source files. - // See golang.org/s/go14customimport for more information. - importComment importMode = 1 << iota - - allowAnonymous + allowAnonymous = 1 << iota allowExcludedFiles ) +var errExclude = errors.New("file rejected") + +type cueError = errors.Error +type excludeError struct { + cueError +} + +func (e excludeError) Is(err error) bool { return err == errExclude } + func rewriteFiles(p *build.Instance, root string, isLocal bool) { p.Root = root @@ -95,16 +93,14 @@ func (s *importStack) Pop() { } func (s *importStack) Copy() []string { - return append([]string{}, *s...) + return slices.Clone(*s) } type fileProcessor struct { - firstFile string - firstCommentFile string - imported map[string][]token.Pos - allTags map[string]bool - ignoreOther bool // ignore files from other packages - allPackages bool + firstFile string + imported map[string][]token.Pos + ignoreOther bool // ignore files from other packages + allPackages bool c *fileProcessorConfig tagger *tagger @@ -119,7 +115,6 @@ type fileProcessorConfig = Config func newFileProcessor(c *fileProcessorConfig, p *build.Instance, tg *tagger) *fileProcessor { return &fileProcessor{ imported: make(map[string][]token.Pos), - allTags: make(map[string]bool), c: c, pkgs: map[string]*build.Instance{"_": p}, pkg: p, @@ -151,18 +146,13 @@ func (fp *fileProcessor) finalize(p *build.Instance) errors.Error { return fp.err } - for tag := range fp.allTags { - p.AllTags = append(p.AllTags, tag) - } - sort.Strings(p.AllTags) - p.ImportPaths, _ = cleanImports(fp.imported) return nil } // add adds the given file to the appropriate package in fp. -func (fp *fileProcessor) add(root string, file *build.File, mode importMode) (added bool) { +func (fp *fileProcessor) add(root string, file *build.File, mode importMode) { fullPath := file.Filename if fullPath != "-" { if !filepath.IsAbs(fullPath) { @@ -176,43 +166,59 @@ func (fp *fileProcessor) add(root string, file *build.File, mode importMode) (ad // special * and _ p := fp.pkg // default package + // sameDir holds whether the file should be considered to be + // part of the same directory as the default package. This is + // true when the file is part of the original package directory + // or when allowExcludedFiles is specified, signifying that the + // file is part of an explicit set of files provided on the + // command line. + sameDir := filepath.Dir(fullPath) == p.Dir || (mode&allowExcludedFiles) != 0 + // badFile := func(p *build.Instance, err errors.Error) bool { - badFile := func(err errors.Error) bool { + badFile := func(err errors.Error) { fp.err = errors.Append(fp.err, err) file.ExcludeReason = fp.err p.InvalidFiles = append(p.InvalidFiles, file) - return true } if err := setFileSource(fp.c, file); err != nil { - return badFile(errors.Promote(err, "")) + badFile(errors.Promote(err, "")) + return } - match, data, err := matchFile(fp.c, file, true, fp.allTags, mode) - switch { - case match: - - case err == nil: + if file.Encoding != build.CUE { // Not a CUE file. - p.OrphanedFiles = append(p.OrphanedFiles, file) - return false - - case !errors.Is(err, errExclude): - return badFile(err) - - default: - file.ExcludeReason = err - if file.Interpretation == "" { - p.IgnoredFiles = append(p.IgnoredFiles, file) - } else { + if sameDir { p.OrphanedFiles = append(p.OrphanedFiles, file) } - return false + return } - - pf, perr := parser.ParseFile(fullPath, data, parser.ImportsOnly) + if (mode & allowExcludedFiles) == 0 { + var badPrefix string + for _, prefix := range []string{".", "_"} { + if strings.HasPrefix(base, prefix) { + badPrefix = prefix + } + } + if badPrefix != "" { + if !sameDir { + return + } + file.ExcludeReason = errors.Newf(token.NoPos, "filename starts with a '%s'", badPrefix) + if file.Interpretation == "" { + p.IgnoredFiles = append(p.IgnoredFiles, file) + } else { + p.OrphanedFiles = append(p.OrphanedFiles, file) + } + return + } + } + // Note: when path is "-" (stdin), it will already have + // been read and file.Source set to the resulting data + // by setFileSource. + pf, perr := fp.c.fileSystem.getCUESyntax(file) if perr != nil { badFile(errors.Promote(perr, "add failed")) - return true + return } pkg := pf.PackageName() @@ -222,39 +228,59 @@ func (fp *fileProcessor) add(root string, file *build.File, mode importMode) (ad pos := pf.Pos() switch { - case pkg == p.PkgName, mode&allowAnonymous != 0: + case pkg == p.PkgName && (sameDir || pkg != "_"): + // We've got the exact package that's being looked for. + // It will already be present in fp.pkgs. + case mode&allowAnonymous != 0 && sameDir: + // It's an anonymous file that's not in a parent directory. case fp.allPackages && pkg != "_": q := fp.pkgs[pkg] + if q == nil && !sameDir { + // It's a file in a parent directory that doesn't correspond + // to a package in the original directory. + return + } if q == nil { - q = &build.Instance{ - PkgName: pkg, - - Dir: p.Dir, - DisplayPath: p.DisplayPath, - ImportPath: p.ImportPath + ":" + pkg, - Root: p.Root, - Module: p.Module, - } + q = fp.c.Context.NewInstance(p.Dir, nil) + q.PkgName = pkg + q.DisplayPath = p.DisplayPath + q.ImportPath = p.ImportPath + ":" + pkg + q.Root = p.Root + q.Module = p.Module fp.pkgs[pkg] = q } p = q case pkg != "_": - + // We're loading a single package and we either haven't matched + // the earlier selected package or we haven't selected a package + // yet. In either case, the default package is the one we want to use. default: - file.ExcludeReason = excludeError{errors.Newf(pos, "no package name")} - p.IgnoredFiles = append(p.IgnoredFiles, file) - return false // don't mark as added + if sameDir { + file.ExcludeReason = excludeError{errors.Newf(pos, "no package name")} + p.IgnoredFiles = append(p.IgnoredFiles, file) + } + return } if !fp.c.AllCUEFiles { - if err := shouldBuildFile(pf, fp.tagger); err != nil { + tagIsSet := fp.tagger.tagIsSet + if p.Module != "" && p.Module != fp.c.Module { + // The file is outside the main module so treat all build tag keys as unset. + // Note that if there's no module, we don't consider it to be outside + // the main module, because otherwise @if tags in non-package files + // explicitly specified on the command line will not work. + tagIsSet = func(string) bool { + return false + } + } + if err := shouldBuildFile(pf, tagIsSet); err != nil { if !errors.Is(err, errExclude) { fp.err = errors.Append(fp.err, err) } file.ExcludeReason = err p.IgnoredFiles = append(p.IgnoredFiles, file) - return false + return } } @@ -267,14 +293,15 @@ func (fp *fileProcessor) add(root string, file *build.File, mode importMode) (ad file.ExcludeReason = excludeError{errors.Newf(pos, "package is %s, want %s", pkg, p.PkgName)} p.IgnoredFiles = append(p.IgnoredFiles, file) - return false + return } if !fp.allPackages { - return badFile(&MultiplePackageError{ + badFile(&MultiplePackageError{ Dir: p.Dir, Packages: []string{p.PkgName, pkg}, Files: []string{fp.firstFile, base}, }) + return } } } @@ -282,21 +309,6 @@ func (fp *fileProcessor) add(root string, file *build.File, mode importMode) (ad isTest := strings.HasSuffix(base, "_test"+cueSuffix) isTool := strings.HasSuffix(base, "_tool"+cueSuffix) - if mode&importComment != 0 { - qcom, line := findImportComment(data) - if line != 0 { - com, err := strconv.Unquote(qcom) - if err != nil { - badFile(errors.Newf(pos, "%s:%d: cannot parse import comment", fullPath, line)) - } else if p.ImportComment == "" { - p.ImportComment = com - fp.firstCommentFile = base - } else if p.ImportComment != com { - badFile(errors.Newf(pos, "found import comments %q (%s) and %q (%s) in %s", p.ImportComment, fp.firstCommentFile, com, base, p.Dir)) - } - } - } - for _, spec := range pf.Imports { quoted := spec.Path.Value path, err := strconv.Unquote(quoted) @@ -330,96 +342,6 @@ func (fp *fileProcessor) add(root string, file *build.File, mode importMode) (ad default: p.BuildFiles = append(p.BuildFiles, file) } - return true -} - -func findImportComment(data []byte) (s string, line int) { - // expect keyword package - word, data := parseWord(data) - if string(word) != "package" { - return "", 0 - } - - // expect package name - _, data = parseWord(data) - - // now ready for import comment, a // comment - // beginning and ending on the current line. - for len(data) > 0 && (data[0] == ' ' || data[0] == '\t' || data[0] == '\r') { - data = data[1:] - } - - var comment []byte - switch { - case bytes.HasPrefix(data, slashSlash): - i := bytes.Index(data, newline) - if i < 0 { - i = len(data) - } - comment = data[2:i] - } - comment = bytes.TrimSpace(comment) - - // split comment into `import`, `"pkg"` - word, arg := parseWord(comment) - if string(word) != "import" { - return "", 0 - } - - line = 1 + bytes.Count(data[:cap(data)-cap(arg)], newline) - return strings.TrimSpace(string(arg)), line -} - -var ( - slashSlash = []byte("//") - newline = []byte("\n") -) - -// skipSpaceOrComment returns data with any leading spaces or comments removed. -func skipSpaceOrComment(data []byte) []byte { - for len(data) > 0 { - switch data[0] { - case ' ', '\t', '\r', '\n': - data = data[1:] - continue - case '/': - if bytes.HasPrefix(data, slashSlash) { - i := bytes.Index(data, newline) - if i < 0 { - return nil - } - data = data[i+1:] - continue - } - } - break - } - return data -} - -// parseWord skips any leading spaces or comments in data -// and then parses the beginning of data as an identifier or keyword, -// returning that word and what remains after the word. -func parseWord(data []byte) (word, rest []byte) { - data = skipSpaceOrComment(data) - - // Parse past leading word characters. - rest = data - for { - r, size := utf8.DecodeRune(rest) - if unicode.IsLetter(r) || '0' <= r && r <= '9' || r == '_' { - rest = rest[size:] - continue - } - break - } - - word = data[:len(data)-len(rest)] - if len(word) == 0 { - return nil, nil - } - - return word, rest } func cleanImports(m map[string][]token.Pos) ([]string, map[string][]token.Pos) { @@ -427,7 +349,7 @@ func cleanImports(m map[string][]token.Pos) ([]string, map[string][]token.Pos) { for path := range m { all = append(all, path) } - sort.Strings(all) + slices.Sort(all) return all, m } diff --git a/vendor/cuelang.org/go/cue/load/match.go b/vendor/cuelang.org/go/cue/load/match.go deleted file mode 100644 index 99720be020..0000000000 --- a/vendor/cuelang.org/go/cue/load/match.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2018 The CUE Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package load - -import ( - "path/filepath" - "strings" - - "cuelang.org/go/cue/build" - "cuelang.org/go/cue/errors" - "cuelang.org/go/cue/token" - "cuelang.org/go/internal/cueimports" -) - -// A match represents the result of matching a single package pattern. -type match struct { - Pattern string // the pattern itself - Literal bool // whether it is a literal (no wildcards) - Pkgs []*build.Instance - Err errors.Error -} - -var errExclude = errors.New("file rejected") - -type cueError = errors.Error -type excludeError struct { - cueError -} - -func (e excludeError) Is(err error) bool { return err == errExclude } - -// matchFile determines whether the file with the given name in the given directory -// should be included in the package being constructed. -// It returns the data read from the file. -// If returnImports is true and name denotes a CUE file, matchFile reads -// until the end of the imports (and returns that data) even though it only -// considers text until the first non-comment. -// If allTags is non-nil, matchFile records any encountered build tag -// by setting allTags[tag] = true. -func matchFile(cfg *Config, file *build.File, returnImports bool, allTags map[string]bool, mode importMode) (match bool, data []byte, err errors.Error) { - // Note: file.Source should already have been set by setFileSource just - // after the build.File value was created. - if file.Encoding != build.CUE { - return false, nil, nil // not a CUE file, don't record. - } - if file.Filename == "-" { - return true, file.Source.([]byte), nil // don't check shouldBuild for stdin - } - - name := filepath.Base(file.Filename) - if (mode & allowExcludedFiles) == 0 { - for _, prefix := range []string{".", "_"} { - if strings.HasPrefix(name, prefix) { - return false, nil, &excludeError{ - errors.Newf(token.NoPos, "filename starts with a '%s'", prefix), - } - } - } - } - - f, err := cfg.fileSystem.openFile(file.Filename) - if err != nil { - return false, nil, err - } - - data, err = cueimports.Read(f) - f.Close() - if err != nil { - return false, nil, - errors.Newf(token.NoPos, "read %s: %v", file.Filename, err) - } - - return true, data, nil -} diff --git a/vendor/cuelang.org/go/cue/load/search.go b/vendor/cuelang.org/go/cue/load/search.go index 622382c434..3ac4981d35 100644 --- a/vendor/cuelang.org/go/cue/load/search.go +++ b/vendor/cuelang.org/go/cue/load/search.go @@ -28,6 +28,14 @@ import ( "cuelang.org/go/mod/module" ) +// A match represents the result of matching a single package pattern. +type match struct { + Pattern string // the pattern itself + Literal bool // whether it is a literal (no wildcards) + Pkgs []*build.Instance + Err errors.Error +} + // TODO: should be matched from module file only. // The pattern is either "all" (all packages), "std" (standard packages), // "cmd" (standard commands), or a path including "...". @@ -304,6 +312,9 @@ func appendExpandedPackageArg(c *Config, pkgPaths []resolvedPackageArg, p string p = filepath.ToSlash(p) ip := module.ParseImportPath(p) + if ip.Qualifier == "_" { + return nil, fmt.Errorf("invalid import path qualifier _ in %q", origp) + } isRel := strings.HasPrefix(ip.Path, "./") // Put argument in canonical form. @@ -403,7 +414,7 @@ func appendExpandedUnqualifiedPackagePath(pkgPaths []resolvedPackageArg, origp s _err = err return false } - if err := shouldBuildFile(f.Syntax, tg); err != nil { + if err := shouldBuildFile(f.Syntax, tg.tagIsSet); err != nil { // Later build logic should pick up and report the same error. return true } @@ -519,7 +530,7 @@ func appendExpandedWildcardPackagePath(pkgPaths []resolvedPackageArg, pattern mo if err != nil { return false } - if err := shouldBuildFile(f.Syntax, tg); err != nil { + if err := shouldBuildFile(f.Syntax, tg.tagIsSet); err != nil { // Later build logic should pick up and report the same error. return true } diff --git a/vendor/cuelang.org/go/cue/load/tags.go b/vendor/cuelang.org/go/cue/load/tags.go index 89c4e268db..32e64f15a6 100644 --- a/vendor/cuelang.org/go/cue/load/tags.go +++ b/vendor/cuelang.org/go/cue/load/tags.go @@ -21,32 +21,58 @@ import ( "os/user" "runtime" "strings" + "sync" "time" "cuelang.org/go/cue" "cuelang.org/go/cue/ast" "cuelang.org/go/cue/build" "cuelang.org/go/cue/errors" - "cuelang.org/go/cue/parser" "cuelang.org/go/cue/token" "cuelang.org/go/internal" + "cuelang.org/go/internal/buildattr" "cuelang.org/go/internal/cli" ) type tagger struct { - cfg *Config + cfg *Config + // tagMap holds true for all the tags in cfg.Tags that + // are not associated with a value. + tagMap map[string]bool + // tags keeps a record of all the @tag attibutes found in files. tags []*tag // tags found in files - buildTags map[string]bool replacements map[ast.Node]ast.Node + + // mu guards the usedTags map. + mu sync.Mutex + // usedTags keeps a record of all the tag attributes found in files. + usedTags map[string]bool } func newTagger(c *Config) *tagger { + tagMap := map[string]bool{} + for _, t := range c.Tags { + if !strings.ContainsRune(t, '=') { + tagMap[t] = true + } + } return &tagger{ - cfg: c, - buildTags: make(map[string]bool), + cfg: c, + tagMap: tagMap, + usedTags: make(map[string]bool), } } +// tagIsSet reports whether the tag with the given key +// is enabled. It also updates t.usedTags to +// reflect that the tag has been seen. +func (tg *tagger) tagIsSet(key string) bool { + tg.mu.Lock() + tg.usedTags[key] = true + tg.mu.Unlock() + return tg.tagMap[key] +} + // A TagVar represents an injection variable. type TagVar struct { // Func returns an ast for a tag variable. It is only called once @@ -215,7 +241,7 @@ func findTags(b *build.Instance) (tags []*tag, errs errors.Error) { if f, ok := n.(*ast.Field); ok { for _, a := range f.Attrs { if key, _ := a.Split(); key == "tag" { - errs = errors.Append(errs, errors.Newf(a.Pos(), msg)) + errs = errors.Append(errs, errors.Newf(a.Pos(), "%s", msg)) // TODO: add position of x. } } @@ -266,7 +292,7 @@ func (tg *tagger) injectTags(tags []string) errors.Error { // Parses command line args for _, s := range tags { p := strings.Index(s, "=") - found := tg.buildTags[s] + found := tg.usedTags[s] if p > 0 { // key-value for _, t := range tg.tags { if t.key == s[:p] { @@ -327,102 +353,17 @@ func (tg *tagger) injectTags(tags []string) errors.Error { return nil } -// shouldBuildFile determines whether a File should be included based on its -// attributes. -func shouldBuildFile(f *ast.File, tagger *tagger) errors.Error { - tags := tagger.cfg.Tags - - a, errs := getBuildAttr(f) - if errs != nil { - return errs - } - if a == nil { - return nil - } - - _, body := a.Split() - - expr, err := parser.ParseExpr("", body) +func shouldBuildFile(f *ast.File, tagIsSet func(key string) bool) errors.Error { + ok, attr, err := buildattr.ShouldBuildFile(f, tagIsSet) if err != nil { - return errors.Promote(err, "") - } - - tagMap := map[string]bool{} - for _, t := range tags { - tagMap[t] = !strings.ContainsRune(t, '=') + return err } - - c := checker{tags: tagMap, tagger: tagger} - include := c.shouldInclude(expr) - if c.err != nil { - return c.err - } - if !include { - return excludeError{errors.Newf(a.Pos(), "@if(%s) did not match", body)} - } - return nil -} - -func getBuildAttr(f *ast.File) (*ast.Attribute, errors.Error) { - var a *ast.Attribute - for _, d := range f.Decls { - switch x := d.(type) { - case *ast.Attribute: - key, _ := x.Split() - if key != "if" { - continue - } - if a != nil { - err := errors.Newf(d.Pos(), "multiple @if attributes") - err = errors.Append(err, - errors.Newf(a.Pos(), "previous declaration here")) - return nil, err - } - a = x - - case *ast.Package: - break - } + if ok { + return nil } - return a, nil -} - -type checker struct { - tagger *tagger - tags map[string]bool - err errors.Error -} - -func (c *checker) shouldInclude(expr ast.Expr) bool { - switch x := expr.(type) { - case *ast.Ident: - c.tagger.buildTags[x.Name] = true - return c.tags[x.Name] - - case *ast.BinaryExpr: - switch x.Op { - case token.LAND: - return c.shouldInclude(x.X) && c.shouldInclude(x.Y) - - case token.LOR: - return c.shouldInclude(x.X) || c.shouldInclude(x.Y) - - default: - c.err = errors.Append(c.err, errors.Newf(token.NoPos, - "invalid operator %v", x.Op)) - return false - } - - case *ast.UnaryExpr: - if x.Op != token.NOT { - c.err = errors.Append(c.err, errors.Newf(token.NoPos, - "invalid operator %v", x.Op)) - } - return !c.shouldInclude(x.X) - - default: - c.err = errors.Append(c.err, errors.Newf(token.NoPos, - "invalid type %T in build attribute", expr)) - return false + if key, body := attr.Split(); key == "if" { + return excludeError{errors.Newf(attr.Pos(), "@if(%s) did not match", body)} + } else { + return excludeError{errors.Newf(attr.Pos(), "@ignore() attribute found")} } } diff --git a/vendor/cuelang.org/go/cue/marshal.go b/vendor/cuelang.org/go/cue/marshal.go index 6e1bbf9171..8c2561d851 100644 --- a/vendor/cuelang.org/go/cue/marshal.go +++ b/vendor/cuelang.org/go/cue/marshal.go @@ -92,11 +92,11 @@ func compileInstances(r *Runtime, data []*instanceData) (instances []*Instance, builds = append(builds, b.build(i)) } - return r.build(builds) + return r.BuildInstances(builds) } // Unmarshal returns a slice of instances from bytes generated by -// Runtime.Marshal. +// [Runtime.Marshal]. func (r *Runtime) Unmarshal(b []byte) ([]*Instance, error) { if len(b) == 0 { return nil, errors.Newf(token.NoPos, "unmarshal failed: empty buffer") @@ -151,13 +151,12 @@ func (r *Runtime) Marshal(values ...InstanceOrValue) (b []byte, err error) { }) if inst.PkgName != "" { - pi := internal.GetPackageInfo(file) - if pi.Package == nil { + if pkg := internal.Package(file); pkg == nil { pkg := &ast.Package{Name: ast.NewIdent(inst.PkgName)} file.Decls = append([]ast.Decl{pkg}, file.Decls...) - } else if pi.Name != inst.PkgName { + } else if pkg.Name.Name != inst.PkgName { // pi is guaranteed to be generated by Def, so it is "safe" to modify. - pi.Package.Name = ast.NewIdent(inst.PkgName) + pkg.Name = ast.NewIdent(inst.PkgName) } } diff --git a/vendor/cuelang.org/go/cue/parser/parser.go b/vendor/cuelang.org/go/cue/parser/parser.go index 4b88a1cae3..cc039cf954 100644 --- a/vendor/cuelang.org/go/cue/parser/parser.go +++ b/vendor/cuelang.org/go/cue/parser/parser.go @@ -274,19 +274,7 @@ func (p *parser) next0() { // Consume a comment and return it and the line on which it ends. func (p *parser) consumeComment() (comment *ast.Comment, endline int) { - // /*-style comments may end on a different line than where they start. - // Scan the comment for '\n' chars and adjust endline accordingly. endline = p.file.Line(p.pos) - if p.lit[1] == '*' { - p.assertV0(p.pos, 0, 10, "block quotes") - - // don't use range here - no need to decode Unicode code points - for i := 0; i < len(p.lit); i++ { - if p.lit[i] == '\n' { - endline++ - } - } - } comment = &ast.Comment{Slash: p.pos, Text: p.lit} p.next0() @@ -1019,7 +1007,7 @@ func (p *parser) parseLabel(rhs bool) (label ast.Label, expr ast.Expr, decl ast. } case *ast.Ident: - if strings.HasPrefix(x.Name, "__") { + if strings.HasPrefix(x.Name, "__") && !rhs { p.errf(x.NamePos, "identifiers starting with '__' are reserved") } @@ -1422,6 +1410,14 @@ L: } fallthrough default: + if p.tok.IsKeyword() { + x = &ast.SelectorExpr{ + X: p.checkExpr(x), + Sel: p.parseKeyIdent(), + } + break + } + pos := p.pos p.errorExpected(pos, "selector") p.next() // make progress diff --git a/vendor/cuelang.org/go/cue/path.go b/vendor/cuelang.org/go/cue/path.go index cfa03c3dc5..26d174221b 100644 --- a/vendor/cuelang.org/go/cue/path.go +++ b/vendor/cuelang.org/go/cue/path.go @@ -139,7 +139,7 @@ func (sel Selector) String() string { } // Unquoted returns the unquoted value of a string label. -// It panics unless sel.LabelType is StringLabel and has a concrete name. +// It panics unless [Selector.LabelType] is [StringLabel] and has a concrete name. func (sel Selector) Unquoted() string { if sel.LabelType() != StringLabel || sel.ConstraintType() >= PatternConstraint { @@ -197,8 +197,8 @@ func (sel Selector) PkgPath() string { return s.pkg } -// Index returns the index of the selector. It panics -// unless sel.Type is IndexLabel. +// Index returns the index of the selector. +// It panics unless [Selector.Type] is [IndexLabel]. func (sel Selector) Index() int { // Note that lists will eventually have constraint types too, // and in that case sel.sel would be of type constraintSelector, @@ -211,19 +211,18 @@ func (sel Selector) Index() int { } var ( - - // AnyDefinition can be used to ask for any definition. + // AnyDefinition is a [Selector] which can be used to ask for any definition. // // In paths it is used to select constraints that apply to all elements. // AnyDefinition = anyDefinition anyDefinition = Selector{sel: anySelector(adt.AnyDefinition)} - // AnyIndex can be used to ask for any index. + // AnyIndex is a [Selector] which can be used to ask for any index. // // In paths it is used to select constraints that apply to all elements. AnyIndex = anyIndex anyIndex = Selector{sel: anySelector(adt.AnyIndex)} - // AnyString can be used to ask for any regular string field. + // AnyString is a [Selector] which can be used to ask for any regular string field. // // In paths it is used to select constraints that apply to all elements. AnyString = anyString @@ -258,6 +257,7 @@ type selector interface { } // A Path is series of selectors to query a CUE value. +// The zero value corresponds to an empty path. type Path struct { path []Selector } @@ -408,7 +408,7 @@ func basicLitSelector(b *ast.BasicLit) Selector { errors.Newf(token.NoPos, "integer %s out of range", b.Value), }} } - return Index(int(i)) + return Index(i) case token.STRING: info, _, _, _ := literal.ParseQuotes(b.Value, b.Value) @@ -561,7 +561,8 @@ func (s stringSelector) feature(r adt.Runtime) adt.Feature { } // An Index selects a list element by index. -func Index(x int) Selector { +// It returns an invalid selector if the index is out of range. +func Index[T interface{ int | int64 }](x T) Selector { f, err := adt.MakeLabel(nil, int64(x), adt.IntLabel) if err != nil { return Selector{pathError{err}} @@ -688,7 +689,7 @@ func valueToSel(v adt.Value) Selector { if err != nil { return Selector{&pathError{errors.Promote(err, "invalid number")}} } - return Index(int(i)) + return Index(i) case *adt.String: return Str(x.Str) default: diff --git a/vendor/cuelang.org/go/cue/query.go b/vendor/cuelang.org/go/cue/query.go index 80e4cfadda..43b4180c75 100644 --- a/vendor/cuelang.org/go/cue/query.go +++ b/vendor/cuelang.org/go/cue/query.go @@ -35,6 +35,10 @@ func getScopePrefix(v Value, p Path) Value { } // LookupPath reports the value for path p relative to v. +// +// Use [AnyString] and [AnyIndex] to find the value of undefined element types +// for structs and lists respectively, for example for the patterns in +// `{[string]: int}` and `[...string]`. func (v Value) LookupPath(p Path) Value { if v.v == nil { return Value{} @@ -46,7 +50,8 @@ func (v Value) LookupPath(p Path) Value { outer: for _, sel := range p.path { f := sel.sel.feature(v.idx) - for _, a := range n.Arcs { + deref := n.DerefValue() + for _, a := range deref.Arcs { if a.Label == f { if a.IsConstraint() && !sel.sel.isConstraint() { break @@ -62,7 +67,7 @@ outer: Label: sel.sel.feature(ctx), } n.MatchAndInsert(ctx, x) - if len(x.Conjuncts) > 0 { + if x.HasConjuncts() { x.Finalize(ctx) parent = linkParent(parent, n, x) n = x @@ -74,7 +79,7 @@ outer: if err, ok := sel.sel.(pathError); ok { x = &adt.Bottom{Err: err.Error} } else { - x = mkErr(v.idx, n, adt.EvalError, "field not found: %v", sel.sel) + x = mkErr(n, adt.EvalError, "field not found: %v", sel.sel) if n.Accept(ctx, f) { x.Code = adt.IncompleteError } diff --git a/vendor/cuelang.org/go/cue/scanner/scanner.go b/vendor/cuelang.org/go/cue/scanner/scanner.go index edf483becc..ad94b4c4ee 100644 --- a/vendor/cuelang.org/go/cue/scanner/scanner.go +++ b/vendor/cuelang.org/go/cue/scanner/scanner.go @@ -18,10 +18,8 @@ package scanner import ( - "bytes" "fmt" "path/filepath" - "strconv" "unicode" "unicode/utf8" @@ -48,7 +46,6 @@ type Scanner struct { ch rune // current character offset int // character offset rdOffset int // reading offset (position after current character) - lineOffset int // current line offset linesSinceLast int spacesSinceLast int insertEOL bool // insert a comma before next newline @@ -73,7 +70,6 @@ func (s *Scanner) next() { if s.rdOffset < len(s.src) { s.offset = s.rdOffset if s.ch == '\n' { - s.lineOffset = s.offset s.file.AddLine(s.offset) } r, w := rune(s.src[s.rdOffset]), 1 @@ -94,7 +90,6 @@ func (s *Scanner) next() { } else { s.offset = len(s.src) if s.ch == '\n' { - s.lineOffset = s.offset s.file.AddLine(s.offset) } s.ch = -1 // eof @@ -139,7 +134,6 @@ func (s *Scanner) Init(file *token.File, src []byte, eh ErrorHandler, mode Mode) s.ch = ' ' s.offset = 0 s.rdOffset = 0 - s.lineOffset = 0 s.insertEOL = false s.ErrorCount = 0 @@ -156,29 +150,6 @@ func (s *Scanner) errf(offs int, msg string, args ...interface{}) { s.ErrorCount++ } -var prefix = []byte("//line ") - -func (s *Scanner) interpretLineComment(text []byte) { - if bytes.HasPrefix(text, prefix) { - // get filename and line number, if any - if i := bytes.LastIndex(text, []byte{':'}); i > 0 { - if line, err := strconv.Atoi(string(text[i+1:])); err == nil && line > 0 { - // valid //line filename:line comment - filename := string(bytes.TrimSpace(text[len(prefix):i])) - if filename != "" { - filename = filepath.Clean(filename) - if !filepath.IsAbs(filename) { - // make filename relative to current directory - filename = filepath.Join(s.dir, filename) - } - } - // update scanner position - s.file.AddLineInfo(s.lineOffset+len(text)+1, filename, line) // +len(text)+1 since comment applies to next line - } - } - } -} - func (s *Scanner) scanComment() string { // initial '/' already consumed; s.ch == '/' offs := s.offset - 1 // position of initial '/' @@ -193,10 +164,6 @@ func (s *Scanner) scanComment() string { } s.next() } - if offs == s.lineOffset { - // comment starts at the beginning of the current line - s.interpretLineComment(s.src[offs:s.offset]) - } goto exit } @@ -383,7 +350,7 @@ exit: // // Must be compliant with https://tools.ietf.org/html/rfc4627. func (s *Scanner) scanEscape(quote quoteInfo) (ok, interpolation bool) { - for i := 0; i < quote.numHash; i++ { + for range quote.numHash { if s.ch != '#' { return true, false } @@ -519,7 +486,7 @@ func (s *Scanner) consumeStringClose(ch rune, quote quoteInfo) (next rune, atEnd } func (s *Scanner) scanHashes(maxHash int) int { - for i := 0; i < maxHash; i++ { + for i := range maxHash { if s.ch != '#' { return i } diff --git a/vendor/cuelang.org/go/cue/stats/stats.go b/vendor/cuelang.org/go/cue/stats/stats.go index 87ffc0ab7c..d65b0181ac 100644 --- a/vendor/cuelang.org/go/cue/stats/stats.go +++ b/vendor/cuelang.org/go/cue/stats/stats.go @@ -18,13 +18,25 @@ package stats import ( "strings" + "sync" "text/template" + + "cuelang.org/go/internal" ) // Counts holds counters for key events during a CUE evaluation. // // This is an experimental type and the contents may change without notice. type Counts struct { + // Note that we can't use the public [cuecontext.EvalVersion] type + // as that would lead to an import cycle. We could use "int" but that's a bit odd. + // There's no harm in referencing an internal type in practice, given that + // the public type is a type alias for the internal type already. + + // EvalVersion is the evaluator version which was used for the CUE evaluation, + // corresponding to one of the values under [cuelang.org/go/cue/cuecontext.EvalVersion]. + EvalVersion internal.EvaluatorVersion + // Operation counters // // These counters account for several key operations. @@ -68,6 +80,22 @@ type Counts struct { // add checks on each of the operations. func (c *Counts) Add(other Counts) { + switch v, vo := c.EvalVersion, other.EvalVersion; { + case v == internal.EvalVersionUnset: + // The first time we add evaluator counts, we record the evaluator version being used. + if vo == internal.EvalVersionUnset { + panic("the first call to Counts.Add must provide an evaluator version") + } + c.EvalVersion = vo + case v != vo: + // Any further evaluator counts being added must match the same evaluator version. + // + // TODO(mvdan): this is currently not possible to enforce, as we collect stats globally + // via [adt.AddStats] which includes stats from contexts created with different versions. + // We likely need to refactor the collection of stats so that it is not global first. + + // panic(fmt.Sprintf("cannot mix evaluator versions in Counts.Add: %v vs %v", v, vo)) + } c.Unifications += other.Unifications c.Conjuncts += other.Conjuncts c.Disjuncts += other.Disjuncts @@ -100,7 +128,8 @@ func (s Counts) Leaks() int64 { return s.Allocs + s.Reused - s.Freed } -var stats = template.Must(template.New("stats").Parse(`{{"" -}} +var stats = sync.OnceValue(func() *template.Template { + return template.Must(template.New("stats").Parse(`{{"" -}} Leaks: {{.Leaks}} Freed: {{.Freed}} @@ -111,10 +140,11 @@ Retain: {{.Retained}} Unifications: {{.Unifications}} Conjuncts: {{.Conjuncts}} Disjuncts: {{.Disjuncts}}`)) +}) func (s Counts) String() string { buf := &strings.Builder{} - err := stats.Execute(buf, s) + err := stats().Execute(buf, s) if err != nil { panic(err) } diff --git a/vendor/cuelang.org/go/cue/token/position.go b/vendor/cuelang.org/go/cue/token/position.go index a0542df4ad..8d194d0511 100644 --- a/vendor/cuelang.org/go/cue/token/position.go +++ b/vendor/cuelang.org/go/cue/token/position.go @@ -15,6 +15,7 @@ package token import ( + "cmp" "fmt" "sort" "sync" @@ -74,6 +75,10 @@ func (p Pos) File() *File { return p.file } +// TODO(mvdan): The methods below don't need to build an entire Position +// just to access some of the information. This could matter particularly for +// Compare, as it is called many times when sorting by position. + func (p Pos) Line() int { if p.file == nil { return 0 @@ -106,45 +111,63 @@ func (p Pos) String() string { return p.Position().String() } -// NoPos is the zero value for Pos; there is no file and line information -// associated with it, and NoPos().IsValid() is false. NoPos is always -// smaller than any other Pos value. The corresponding Position value -// for NoPos is the zero value for Position. +// Compare returns an integer comparing two positions. The result will be 0 if p == p2, +// -1 if p < p2, and +1 if p > p2. Note that [NoPos] is always larger than any valid position. +func (p Pos) Compare(p2 Pos) int { + if p == p2 { + return 0 + } else if p == NoPos { + return +1 + } else if p2 == NoPos { + return -1 + } + pos, pos2 := p.Position(), p2.Position() + if c := cmp.Compare(pos.Filename, pos2.Filename); c != 0 { + return c + } + // Note that CUE doesn't currently use any directives which alter + // position information, like Go's //line, so comparing by offset is enough. + return cmp.Compare(pos.Offset, pos2.Offset) + +} + +// NoPos is the zero value for [Pos]; there is no file and line information +// associated with it, and [Pos.IsValid] is false. +// +// NoPos is always larger than any valid [Pos] value, as it tends to relate +// to values produced from evaluating existing values with valid positions. +// The corresponding [Position] value for NoPos is the zero value. var NoPos = Pos{} // RelPos indicates the relative position of token to the previous token. type RelPos int +//go:generate go run golang.org/x/tools/cmd/stringer -type=RelPos -linecomment + const ( // NoRelPos indicates no relative position is specified. - NoRelPos RelPos = iota + NoRelPos RelPos = iota // invalid // Elided indicates that the token for which this position is defined is // not rendered at all. - Elided + Elided // elided // NoSpace indicates there is no whitespace before this token. - NoSpace + NoSpace // nospace // Blank means there is horizontal space before this token. - Blank + Blank // blank // Newline means there is a single newline before this token. - Newline + Newline // newline // NewSection means there are two or more newlines before this token. - NewSection + NewSection // section relMask = 0xf relShift = 4 ) -var relNames = []string{ - "invalid", "elided", "nospace", "blank", "newline", "section", -} - -func (p RelPos) String() string { return relNames[p] } - func (p RelPos) Pos() Pos { return Pos{nil, int(p)} } diff --git a/vendor/cuelang.org/go/cue/token/relpos_string.go b/vendor/cuelang.org/go/cue/token/relpos_string.go new file mode 100644 index 0000000000..0129d7bb62 --- /dev/null +++ b/vendor/cuelang.org/go/cue/token/relpos_string.go @@ -0,0 +1,28 @@ +// Code generated by "stringer -type=RelPos -linecomment"; DO NOT EDIT. + +package token + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[NoRelPos-0] + _ = x[Elided-1] + _ = x[NoSpace-2] + _ = x[Blank-3] + _ = x[Newline-4] + _ = x[NewSection-5] +} + +const _RelPos_name = "invalidelidednospaceblanknewlinesection" + +var _RelPos_index = [...]uint8{0, 7, 13, 20, 25, 32, 39} + +func (i RelPos) String() string { + if i < 0 || i >= RelPos(len(_RelPos_index)-1) { + return "RelPos(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _RelPos_name[_RelPos_index[i]:_RelPos_index[i+1]] +} diff --git a/vendor/cuelang.org/go/cue/types.go b/vendor/cuelang.org/go/cue/types.go index 100714562d..99b7f67082 100644 --- a/vendor/cuelang.org/go/cue/types.go +++ b/vendor/cuelang.org/go/cue/types.go @@ -33,7 +33,6 @@ import ( "cuelang.org/go/internal/core/adt" "cuelang.org/go/internal/core/compile" "cuelang.org/go/internal/core/convert" - "cuelang.org/go/internal/core/eval" "cuelang.org/go/internal/core/export" "cuelang.org/go/internal/core/runtime" "cuelang.org/go/internal/core/subsume" @@ -79,7 +78,7 @@ const ( // Kind.String to indicate NumberKind. // NumberKind represents any kind of number. - NumberKind Kind = IntKind | FloatKind + NumberKind Kind = adt.NumberKind // TopKind represents the top value. TopKind Kind = adt.TopKind @@ -115,7 +114,7 @@ func (o *hiddenStructValue) at(i int) *adt.Vertex { return o.arcs[i] } -// Lookup reports the field for the given key. The returned Value is invalid +// Lookup reports the field for the given key. The returned [Value] is invalid // if it does not exist. func (o *hiddenStructValue) Lookup(key string) Value { f := o.v.idx.StrLabel(key) @@ -127,7 +126,7 @@ func (o *hiddenStructValue) Lookup(key string) Value { } } if i == len { - x := mkErr(o.v.idx, o.obj, 0, "field not found: %v", key) + x := mkErr(o.obj, 0, "field not found: %v", key) x.NotExists = true // TODO: more specifically we should test whether the values that // are addressable from the root of the configuration can support the @@ -143,22 +142,22 @@ func (o *hiddenStructValue) Lookup(key string) Value { // MarshalJSON returns a valid JSON encoding or reports an error if any of the // fields is invalid. -func (o *structValue) marshalJSON() (b []byte, err errors.Error) { +func (o *structValue) appendJSON(b []byte) ([]byte, error) { b = append(b, '{') n := o.Len() - for i := 0; i < n; i++ { + for i := range n { k, v := o.At(i) + // Do not use json.Marshal as it escapes HTML. s, err := internaljson.Marshal(k) if err != nil { - return nil, unwrapJSONError(err) + return nil, err } b = append(b, s...) b = append(b, ':') - bb, err := internaljson.Marshal(v) + b, err = v.appendJSON(o.ctx, b) if err != nil { - return nil, unwrapJSONError(err) + return nil, err } - b = append(b, bb...) if i < n-1 { b = append(b, ',') } @@ -180,7 +179,7 @@ func toMarshalErr(v Value, b *adt.Bottom) error { func marshalErrf(v Value, src adt.Node, code adt.ErrorCode, msg string, args ...interface{}) error { arguments := append([]interface{}{code, msg}, args...) - b := mkErr(v.idx, src, arguments...) + b := mkErr(src, arguments...) return toMarshalErr(v, b) } @@ -259,7 +258,9 @@ func (i *Iterator) Selector() Selector { // Label reports the label of the value if i iterates over struct fields and "" // otherwise. // -// Slated to be deprecated: use [Iterator.Selector] and [Selector.String]. +// Deprecated: use [Iterator.Selector] with methods like +// [Selector.Unquoted] or [Selector.String] depending on whether or not +// you are only dealing with regular fields, whose labels are always [StringLabel]. // Note that this will give more accurate string representations. func (i *hiddenIterator) Label() string { if i.f == 0 { @@ -268,13 +269,6 @@ func (i *hiddenIterator) Label() string { return i.idx.LabelStr(i.f) } -// IsHidden reports if a field is hidden from the data model. -// -// Deprecated: use i.Selector().PkgPath() != "" -func (i *hiddenIterator) IsHidden() bool { - return i.f.IsHidden() -} - // IsOptional reports if a field is optional. func (i *Iterator) IsOptional() bool { return i.arcType == adt.ArcOptional @@ -285,24 +279,17 @@ func (i *Iterator) FieldType() SelectorType { return featureToSelType(i.f, i.arcType) } -// IsDefinition reports if a field is a definition. -// -// Deprecated: use i.Selector().IsDefinition() -func (i *hiddenIterator) IsDefinition() bool { - return i.f.IsDef() -} - // marshalJSON iterates over the list and generates JSON output. HasNext // will return false after this operation. -func marshalList(l *Iterator) (b []byte, err errors.Error) { +func listAppendJSON(b []byte, l *Iterator) ([]byte, error) { b = append(b, '[') if l.Next() { for i := 0; ; i++ { - x, err := internaljson.Marshal(l.Value()) + var err error + b, err = l.Value().appendJSON(l.ctx, b) if err != nil { - return nil, unwrapJSONError(err) + return nil, err } - b = append(b, x...) if !l.Next() { break } @@ -332,7 +319,7 @@ func (v Value) getNum(k adt.Kind) (*adt.Num, errors.Error) { // 200 and exp == -2. Calling MantExp with a nil argument is an efficient way to // get the exponent of the receiver. func (v Value) MantExp(mant *big.Int) (exp int, err error) { - n, err := v.getNum(adt.NumKind) + n, err := v.getNum(adt.NumberKind) if err != nil { return 0, err } @@ -351,7 +338,7 @@ func (v Value) MantExp(mant *big.Int) (exp int, err error) { // Decimal is for internal use only. The Decimal type that is returned is // subject to change. func (v hiddenValue) Decimal() (d *internal.Decimal, err error) { - n, err := v.getNum(adt.NumKind) + n, err := v.getNum(adt.NumberKind) if err != nil { return nil, err } @@ -372,7 +359,7 @@ func (v Value) AppendInt(buf []byte, base int) ([]byte, error) { // AppendFloat appends to buf the string form of the floating-point number x. // It returns an error if v is not a number. func (v Value) AppendFloat(buf []byte, fmt byte, prec int) ([]byte, error) { - n, err := v.getNum(adt.NumKind) + n, err := v.getNum(adt.NumberKind) if err != nil { return nil, err } @@ -510,7 +497,7 @@ func init() { // by a float64 (|x| > math.MaxFloat64), the result is (+Inf, ErrAbove) or // (-Inf, ErrBelow), depending on the sign of x. func (v Value) Float64() (float64, error) { - n, err := v.getNum(adt.NumKind) + n, err := v.getNum(adt.NumberKind) if err != nil { return 0, err } @@ -697,7 +684,7 @@ func remakeValue(base Value, env *adt.Environment, v adt.Expr) Value { return makeChildValue(base.parent(), n) } -func remakeFinal(base Value, env *adt.Environment, v adt.Value) Value { +func remakeFinal(base Value, v adt.Value) Value { n := &adt.Vertex{Parent: base.v.Parent, Label: base.v.Label, BaseValue: v} n.ForceDone() return makeChildValue(base.parent(), n) @@ -733,133 +720,6 @@ func (v Value) Default() (Value, bool) { return v, false } return makeValue(v.idx, d, v.parent_), true - - // d, ok := v.v.Value.(*adt.Disjunction) - // if !ok { - // return v, false - // } - - // var w *adt.Vertex - - // switch d.NumDefaults { - // case 0: - // return v, false - - // case 1: - // w = d.Values[0] - - // default: - // x := *v.v - // x.Value = &adt.Disjunction{ - // Src: d.Src, - // Values: d.Values[:d.NumDefaults], - // NumDefaults: 0, - // } - // w = &x - // } - - // w.Conjuncts = nil - // for _, c := range v.v.Conjuncts { - // // TODO: preserve field information. - // expr, _ := stripNonDefaults(c.Expr()) - // w.AddConjunct(adt.MakeConjunct(c.Env, expr)) - // } - - // return makeValue(v.idx, w), true - - // if !stripped { - // return v, false - // } - - // n := *v.v - // n.Conjuncts = conjuncts - // return Value{v.idx, &n}, true - - // isDefault := false - // for _, c := range v.v.Conjuncts { - // if hasDisjunction(c.Expr()) { - // isDefault = true - // break - // } - // } - - // if !isDefault { - // return v, false - // } - - // TODO: record expanded disjunctions in output. - // - Rename Disjunction to DisjunctionExpr - // - Introduce Disjuncts with Values. - // - In Expr introduce Star - // - Don't pick default by default? - - // Evaluate the value. - // x := eval.FinalizeValue(v.idx.Runtime, v.v) - // if b, _ := x.Value.(*adt.Bottom); b != nil { // && b.IsIncomplete() { - // return v, false - // } - // // Finalize and return here. - // return Value{v.idx, x}, isDefault -} - -// TODO: this should go: record preexpanded disjunctions in Vertex. -func hasDisjunction(expr adt.Expr) bool { - switch x := expr.(type) { - case *adt.DisjunctionExpr: - return true - case *adt.Conjunction: - for _, v := range x.Values { - if hasDisjunction(v) { - return true - } - } - case *adt.BinaryExpr: - switch x.Op { - case adt.OrOp: - return true - case adt.AndOp: - return hasDisjunction(x.X) || hasDisjunction(x.Y) - } - } - return false -} - -// TODO: this should go: record preexpanded disjunctions in Vertex. -func stripNonDefaults(expr adt.Expr) (r adt.Expr, stripped bool) { - switch x := expr.(type) { - case *adt.DisjunctionExpr: - if !x.HasDefaults { - return x, false - } - d := *x - d.Values = []adt.Disjunct{} - for _, v := range x.Values { - if v.Default { - d.Values = append(d.Values, v) - } - } - if len(d.Values) == 1 { - return d.Values[0].Val, true - } - return &d, true - - case *adt.BinaryExpr: - if x.Op != adt.AndOp { - return x, false - } - a, sa := stripNonDefaults(x.X) - b, sb := stripNonDefaults(x.Y) - if sa || sb { - bin := *x - bin.X = a - bin.Y = b - return &bin, true - } - return x, false - - default: - return x, false - } } // Label reports he label used to obtain this value from the enclosing struct. @@ -880,12 +740,9 @@ func (v Value) Kind() Kind { if v.v == nil { return BottomKind } - c := v.v.BaseValue - if !v.v.IsConcrete() { - return BottomKind - } - // TODO: perhaps we should not consider open lists as "incomplete". - if v.IncompleteKind() == adt.ListKind && !v.v.IsClosedList() { + w := v.v.DerefValue() + c := w.BaseValue + if !w.IsConcrete() { return BottomKind } return c.Kind() @@ -901,19 +758,18 @@ func (v Value) IncompleteKind() Kind { // MarshalJSON marshalls this value into valid JSON. func (v Value) MarshalJSON() (b []byte, err error) { - b, err = v.marshalJSON() + b, err = v.appendJSON(v.ctx(), nil) if err != nil { return nil, unwrapJSONError(err) } return b, nil } -func (v Value) marshalJSON() (b []byte, err error) { +func (v Value) appendJSON(ctx *adt.OpContext, b []byte) ([]byte, error) { v, _ = v.Default() if v.v == nil { - return internaljson.Marshal(nil) + return append(b, "null"...), nil } - ctx := newContext(v.idx) x := v.eval(ctx) if _, ok := x.(adt.Resolver); ok { @@ -926,26 +782,35 @@ func (v Value) marshalJSON() (b []byte, err error) { // TODO: implement marshalles in value. switch k := x.Kind(); k { case adt.NullKind: - return internaljson.Marshal(nil) + return append(b, "null"...), nil case adt.BoolKind: - return internaljson.Marshal(x.(*adt.Bool).B) - case adt.IntKind, adt.FloatKind, adt.NumKind: - b, err := x.(*adt.Num).X.MarshalText() - b = bytes.TrimLeft(b, "+") - return b, err + b2, err := json.Marshal(x.(*adt.Bool).B) + return append(b, b2...), err + case adt.IntKind, adt.FloatKind, adt.NumberKind: + // [apd.Decimal] offers no [json.Marshaler] method, + // however the "G" formatting appears to result in valid JSON + // for any valid CUE number that we've come across so far. + // Upstream also rejected adding JSON methods in favor of [encoding.TextMarshaler]. + // + // As an optimization, use the append-like API directly which is equivalent to + // [apd.Decimal.MarshalText], allowing us to avoid extra copies. + return x.(*adt.Num).X.Append(b, 'G'), nil case adt.StringKind: - return internaljson.Marshal(x.(*adt.String).Str) + // Do not use json.Marshal as it escapes HTML. + b2, err := internaljson.Marshal(x.(*adt.String).Str) + return append(b, b2...), err case adt.BytesKind: - return internaljson.Marshal(x.(*adt.Bytes).B) + b2, err := json.Marshal(x.(*adt.Bytes).B) + return append(b, b2...), err case adt.ListKind: - i, _ := v.List() - return marshalList(&i) + i := v.mustList(ctx) + return listAppendJSON(b, &i) case adt.StructKind: obj, err := v.structValData(ctx) if err != nil { return nil, toMarshalErr(v, err) } - return obj.marshalJSON() + return obj.appendJSON(b) case adt.BottomKind: return nil, toMarshalErr(v, x.(*adt.Bottom)) default: @@ -962,8 +827,7 @@ func (v Value) Syntax(opts ...Option) ast.Node { if v.v == nil { return nil } - var o options = getOptions(opts) - // var inst *Instance + o := getOptions(opts) p := export.Profile{ Simplify: !o.raw, @@ -1032,12 +896,21 @@ outer: if len(f.Decls) == 1 { if e, ok := f.Decls[0].(*ast.EmbedDecl); ok { + for _, c := range ast.Comments(e) { + ast.AddComment(f, c) + } + for _, c := range ast.Comments(e.Expr) { + ast.AddComment(f, c) + } + ast.SetComments(e.Expr, f.Comments()) return e.Expr } } - return &ast.StructLit{ + st := &ast.StructLit{ Elts: f.Decls, } + ast.SetComments(st, f.Comments()) + return st } // Doc returns all documentation comments associated with the field from which @@ -1049,26 +922,6 @@ func (v Value) Doc() []*ast.CommentGroup { return export.ExtractDoc(v.v) } -// Split returns a list of values from which v originated such that -// the unification of all these values equals v and for all returned values. -// It will also split unchecked unifications (embeddings), so unifying the -// split values may fail if actually unified. -// Source returns a non-nil value. -// -// Deprecated: use [Value.Expr]. -func (v hiddenValue) Split() []Value { - if v.v == nil { - return nil - } - a := []Value{} - v.v.VisitLeafConjuncts(func(x adt.Conjunct) bool { - env, expr := x.EnvExpr() - a = append(a, remakeValue(v, env, expr)) - return true - }) - return a -} - // Source returns the original node for this value. The return value may not // be an [ast.Expr]. For instance, a struct kind may be represented by a // struct literal, a field comprehension, or a file. It returns nil for @@ -1093,8 +946,7 @@ func (v Value) Source() ast.Node { // If v exactly represents a package, BuildInstance returns // the build instance corresponding to the value; otherwise it returns nil. // -// The value returned by Value.ReferencePath will commonly represent -// a package. +// The value returned by [Value.ReferencePath] will commonly represent a package. func (v Value) BuildInstance() *build.Instance { if v.idx == nil { return nil @@ -1112,7 +964,7 @@ func (v Value) Err() error { // Pos returns position information. // -// Use v.Expr to get positions for all conjuncts and disjuncts. +// Use [Value.Expr] to get positions for all conjuncts and disjuncts. func (v Value) Pos() token.Pos { if v.v == nil { return token.NoPos @@ -1143,25 +995,6 @@ func (v Value) Pos() token.Pos { // TODO: IsFinal: this value can never be changed. -// IsClosed reports whether a list or struct is closed. It reports false when -// the value is not a list or struct. -// -// Deprecated: use Allows(AnyString) and Allows(AnyIndex) or Kind/IncompleteKind. -func (v hiddenValue) IsClosed() bool { - if v.v == nil { - return false - } - switch v.Kind() { - case ListKind: - return v.v.IsClosedList() - case StructKind: - // TODO: remove this more expensive computation once the old evaluator - // is removed. - return !v.Allows(AnyString) - } - return false -} - // Allows reports whether a field with the given selector could be added to v. // // Allows does not take into account validators like list.MaxItems(4). This may @@ -1183,13 +1016,11 @@ func (v Value) IsConcrete() bool { if v.v == nil { return false // any is neither concrete, not a list or struct. } - if b := v.v.Bottom(); b != nil { + w := v.v.DerefValue() + if b := w.Bottom(); b != nil { return !b.IsIncomplete() } - if !adt.IsConcrete(v.v) { - return false - } - if v.IncompleteKind() == adt.ListKind && !v.v.IsClosedList() { + if !adt.IsConcrete(w) { return false } return true @@ -1251,11 +1082,11 @@ func (v Value) checkKind(ctx *adt.OpContext, want adt.Kind) *adt.Bottom { k := x.Kind() if want != adt.BottomKind { if k&want == adt.BottomKind { - return mkErr(v.idx, x, "cannot use value %v (type %s) as %s", + return mkErr(x, "cannot use value %v (type %s) as %s", ctx.Str(x), k, want) } if !adt.IsConcrete(x) { - return mkErr(v.idx, x, adt.IncompleteError, "non-concrete value %v", k) + return mkErr(x, adt.IncompleteError, "non-concrete value %v", k) } } return nil @@ -1264,7 +1095,7 @@ func (v Value) checkKind(ctx *adt.OpContext, want adt.Kind) *adt.Bottom { func makeInt(v Value, x int64) Value { n := &adt.Num{K: adt.IntKind} n.X.SetInt64(int64(x)) - return remakeFinal(v, nil, n) + return remakeFinal(v, n) } // Len returns the number of items of the underlying value. @@ -1278,7 +1109,7 @@ func (v Value) Len() Value { n := &adt.Num{K: adt.IntKind} n.X.SetInt64(int64(len(x.Elems()))) if x.IsClosedList() { - return remakeFinal(v, nil, n) + return remakeFinal(v, n) } // Note: this HAS to be a Conjunction value and cannot be // an adt.BinaryExpr, as the expressions would be considered @@ -1288,7 +1119,7 @@ func (v Value) Len() Value { &adt.BasicType{K: adt.IntKind}, &adt.BoundValue{Op: adt.GreaterEqualOp, Value: n}, }} - return remakeFinal(v, nil, c) + return remakeFinal(v, c) } case *adt.Bytes: @@ -1298,13 +1129,13 @@ func (v Value) Len() Value { } } const msg = "len not supported for type %v" - return remakeValue(v, nil, mkErr(v.idx, v.v, msg, v.Kind())) + return remakeValue(v, nil, mkErr(v.v, msg, v.Kind())) } // Elem returns the value of undefined element types of lists and structs. // -// Deprecated: use [Value.LookupPath] in combination with "AnyString" or "AnyIndex". +// Deprecated: use [Value.LookupPath] in combination with [AnyString] or [AnyIndex]. func (v hiddenValue) Elem() (Value, bool) { sel := AnyString if v.v.IsList() { @@ -1322,13 +1153,19 @@ func (v Value) List() (Iterator, error) { if err := v.checkKind(ctx, adt.ListKind); err != nil { return Iterator{idx: v.idx, ctx: ctx}, v.toErr(err) } + return v.mustList(ctx), nil +} + +// mustList is like [Value.List], but reusing ctx and leaving it to the caller +// to apply defaults and check the kind. +func (v Value) mustList(ctx *adt.OpContext) Iterator { arcs := []*adt.Vertex{} for _, a := range v.v.Elems() { if a.Label.IsInt() { arcs = append(arcs, a) } } - return Iterator{idx: v.idx, ctx: ctx, val: v, arcs: arcs}, nil + return Iterator{idx: v.idx, ctx: ctx, val: v, arcs: arcs} } // Null reports an error if v is not null. @@ -1419,8 +1256,7 @@ func (v Value) structValOpts(ctx *adt.OpContext, o options) (s structValue, err // Allow scalar values if hidden or definition fields are requested. case !o.omitHidden, !o.omitDefinitions: default: - obj, err = v.getStruct() - if err != nil { + if err := v.checkKind(ctx, adt.StructKind); err != nil && !err.ChildError { return structValue{}, err } } @@ -1482,17 +1318,9 @@ func (v hiddenValue) Struct() (*Struct, error) { return &Struct{obj}, nil } -func (v Value) getStruct() (*adt.Vertex, *adt.Bottom) { - ctx := v.ctx() - if err := v.checkKind(ctx, adt.StructKind); err != nil { - if !err.ChildError { - return nil, err - } - } - return v.v, nil -} - // Struct represents a CUE struct value. +// +// Deprecated: only used by deprecated functions. type Struct struct { structValue } @@ -1504,7 +1332,7 @@ type hiddenStruct = Struct // Deprecated: only used by deprecated functions. type FieldInfo struct { Selector string - Name string // Deprecated: use Selector + Name string // Deprecated: use [FieldInfo.Selector] Pos int Value Value @@ -1545,7 +1373,7 @@ func (s *hiddenStruct) FieldByName(name string, isIdent bool) (FieldInfo, error) return FieldInfo{}, errNotFound } -// Fields creates an iterator over the Struct's fields. +// Fields creates an iterator over the struct's fields. func (s *hiddenStruct) Fields(opts ...Option) *Iterator { iter, _ := s.v.Fields(opts...) return iter @@ -1716,15 +1544,15 @@ func (v hiddenValue) Fill(x interface{}, path ...string) Value { // FillPath creates a new value by unifying v with the value of x at the given // path. // -// If x is an cue/ast.Expr, it will be evaluated within the context of the +// If x is an [ast.Expr], it will be evaluated within the context of the // given path: identifiers that are not resolved within the expression are // resolved as if they were defined at the path position. // // If x is a Value, it will be used as is. It panics if x is not created -// from the same Runtime as v. +// from the same [Context] as v. // // Otherwise, the given Go value will be converted to CUE using the same rules -// as Context.Encode. +// as [Context.Encode]. // // Any reference in v referring to the value at the given path will resolve to x // in the newly created value. The resulting value is not validated. @@ -1735,7 +1563,7 @@ func (v Value) FillPath(p Path, x interface{}) Value { } ctx := v.ctx() if err := p.Err(); err != nil { - return newErrValue(v, mkErr(v.idx, nil, 0, "invalid path: %v", err)) + return newErrValue(v, mkErr(nil, 0, "invalid path: %v", err)) } var expr adt.Expr switch x := x.(type) { @@ -1771,7 +1599,7 @@ func (v Value) FillPath(p Path, x interface{}) Value { list := &adt.ListLit{} any := &adt.Top{} // TODO(perf): make this a constant thing. This will be possible with the query extension. - for k := 0; k < i; k++ { + for range i { list.Elems = append(list.Elems, any) } list.Elems = append(list.Elems, expr, &adt.Ellipsis{}) @@ -1858,22 +1686,8 @@ func (v Value) Subsume(w Value, opts ...Option) error { return p.Value(ctx, v.v, w.v) } -// Deprecated: use [Value.Subsume]. -// -// Subsumes reports whether w is an instance of v. -// -// Without options, Subsumes checks whether v is a backwards compatible schema -// of w. -// -// By default, Subsumes tests whether two values are compatible -// Value v and w must be obtained from the same build. -// TODO: remove this requirement. -func (v hiddenValue) Subsumes(w Value) bool { - ctx := v.ctx() - p := subsume.Profile{Defaults: true} - return p.Check(ctx, v.v, w.v) -} - +// TODO: this is likely not correct for V3. There are some cases where this is +// still used for V3. Transition away from those. func allowed(ctx *adt.OpContext, parent, n *adt.Vertex) *adt.Bottom { if !parent.IsClosedList() && !parent.IsClosedStruct() { return nil @@ -1890,11 +1704,17 @@ func allowed(ctx *adt.OpContext, parent, n *adt.Vertex) *adt.Bottom { return nil } -func addConjuncts(dst, src *adt.Vertex) { +func addConjuncts(ctx *adt.OpContext, dst, src *adt.Vertex) { c := adt.MakeRootConjunct(nil, src) - if src.Closed { - var root adt.CloseInfo - c.CloseInfo = root.SpawnRef(src, src.Closed, nil) + c.CloseInfo.GroupUnify = true + + if src.ClosedRecursive { + if ctx.Version == internal.EvalV2 { + var root adt.CloseInfo + c.CloseInfo = root.SpawnRef(src, src.ClosedRecursive, nil) + } else { + c.CloseInfo.FromDef = true + } } dst.AddConjunct(c) } @@ -1911,31 +1731,33 @@ func (v Value) Unify(w Value) Value { return v } + ctx := v.ctx() n := &adt.Vertex{} - addConjuncts(n, v.v) - addConjuncts(n, w.v) + addConjuncts(ctx, n, v.v) + addConjuncts(ctx, n, w.v) - ctx := newContext(v.idx) n.Finalize(ctx) n.Parent = v.v.Parent n.Label = v.v.Label - n.Closed = v.v.Closed || w.v.Closed + n.ClosedRecursive = v.v.ClosedRecursive || w.v.ClosedRecursive if err := n.Err(ctx); err != nil { return makeValue(v.idx, n, v.parent_) } - if err := allowed(ctx, v.v, n); err != nil { - return newErrValue(w, err) - } - if err := allowed(ctx, w.v, n); err != nil { - return newErrValue(v, err) + if ctx.Version == internal.EvalV2 { + if err := allowed(ctx, v.v, n); err != nil { + return newErrValue(w, err) + } + if err := allowed(ctx, w.v, n); err != nil { + return newErrValue(v, err) + } } return makeValue(v.idx, n, v.parent_) } -// UnifyAccept is as v.Unify(w), but will disregard the closedness rules for +// UnifyAccept is like [Value.Unify](w), but will disregard the closedness rules for // v and w, and will, instead, only allow fields that are present in accept. // // UnifyAccept is used to piecemeal unify individual conjuncts obtained from @@ -1952,20 +1774,36 @@ func (v Value) UnifyAccept(w Value, accept Value) Value { } n := &adt.Vertex{} - n.AddConjunct(adt.MakeRootConjunct(nil, v.v)) - n.AddConjunct(adt.MakeRootConjunct(nil, w.v)) + ctx := v.ctx() - ctx := newContext(v.idx) - n.Finalize(ctx) + cv := adt.MakeRootConjunct(nil, v.v) + cw := adt.MakeRootConjunct(nil, w.v) - n.Parent = v.v.Parent - n.Label = v.v.Label + switch ctx.Version { + case internal.EvalV2: + n.AddConjunct(cv) + n.AddConjunct(cw) - if err := n.Err(ctx); err != nil { - return makeValue(v.idx, n, v.parent_) - } - if err := allowed(ctx, accept.v, n); err != nil { - return newErrValue(accept, err) + n.Finalize(ctx) + + n.Parent = v.v.Parent + n.Label = v.v.Label + + if err := n.Err(ctx); err != nil { + return makeValue(v.idx, n, v.parent_) + } + if err := allowed(ctx, accept.v, n); err != nil { + return newErrValue(accept, err) + } + + case internal.EvalV3: + cv.CloseInfo.FromEmbed = true + cw.CloseInfo.FromEmbed = true + n.AddConjunct(cv) + n.AddConjunct(cw) + ca := adt.MakeRootConjunct(nil, accept.v) + n.AddConjunct(ca) + n.Finalize(ctx) } return makeValue(v.idx, n, v.parent_) @@ -2013,7 +1851,7 @@ func (v hiddenValue) Reference() (inst *Instance, path []string) { } // ReferencePath returns the value and path referred to by this value such that -// value.LookupPath(path) resolves to the same value, or no path if this value +// [Value.LookupPath](path) resolves to the same value, or no path if this value // is not a reference. func (v Value) ReferencePath() (root Value, p Path) { // TODO: don't include references to hidden fields. @@ -2133,7 +1971,7 @@ func Schema() Option { // Concrete ensures that all values are concrete. // -// For Validate this means it returns an error if this is not the case. +// For [Validate] this means it returns an error if this is not the case. // In other cases a non-concrete value will be replaced with an error. func Concrete(concrete bool) Option { return func(p *options) { @@ -2260,7 +2098,7 @@ func (o *options) updateOptions(opts []Option) { } // Validate reports any errors, recursively. The returned error may represent -// more than one error, retrievable with errors.Errors, if more than one +// more than one error, retrievable with [errors.Errors], if more than one // exists. // // Note that by default not all errors are reported, unless options like @@ -2299,7 +2137,7 @@ func (v Value) Walk(before func(Value) bool, after func(Value)) { omitHidden: true, omitDefinitions: true, }) - for i := 0; i < obj.Len(); i++ { + for i := range obj.Len() { _, v := obj.At(i) // TODO: should we error on required fields, or visit them anyway? // Walk is not designed to error at this moment, though. @@ -2449,7 +2287,7 @@ process: a.AddConjunct(adt.MakeRootConjunct(env, n.Val)) b.AddConjunct(adt.MakeRootConjunct(env, disjunct.Val)) - ctx := eval.NewContext(v.idx, nil) + ctx := v.ctx() a.Finalize(ctx) b.Finalize(ctx) if allowed(ctx, v.v, &b) != nil { diff --git a/vendor/cuelang.org/go/cue/version.go b/vendor/cuelang.org/go/cue/version.go new file mode 100644 index 0000000000..946dcb2633 --- /dev/null +++ b/vendor/cuelang.org/go/cue/version.go @@ -0,0 +1,24 @@ +// Copyright 2024 The CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cue + +import "cuelang.org/go/internal/cueversion" + +// LanguageVersion returns the CUE language version. +// This determines the latest version of CUE that +// is understood by the evaluator and module code. +func LanguageVersion() string { + return cueversion.LanguageVersion() +} diff --git a/vendor/cuelang.org/go/encoding/json/json.go b/vendor/cuelang.org/go/encoding/json/json.go index 28f79f5553..2ef43739b5 100644 --- a/vendor/cuelang.org/go/encoding/json/json.go +++ b/vendor/cuelang.org/go/encoding/json/json.go @@ -16,6 +16,7 @@ package json import ( + "bytes" "encoding/json" "fmt" "io" @@ -28,6 +29,7 @@ import ( "cuelang.org/go/cue/literal" "cuelang.org/go/cue/parser" "cuelang.org/go/cue/token" + "cuelang.org/go/internal/source" ) // Valid reports whether data is a valid JSON encoding. @@ -60,22 +62,10 @@ func Extract(path string, data []byte) (ast.Expr, error) { if err != nil { return nil, err } - patchExpr(expr) + patchExpr(expr, nil) return expr, nil } -// Decode parses JSON-encoded data to a CUE value, using path for position -// information. -// -// Deprecated: use Extract and build using cue.Context.BuildExpr. -func Decode(r *cue.Runtime, path string, data []byte) (*cue.Instance, error) { - expr, err := extract(path, data) - if err != nil { - return nil, err - } - return r.CompileExpr(expr) -} - func extract(path string, b []byte) (ast.Expr, error) { expr, err := parser.ParseExpr(path, b) if err != nil || !json.Valid(b) { @@ -85,6 +75,14 @@ func extract(path string, b []byte) (ast.Expr, error) { } var x interface{} err := json.Unmarshal(b, &x) + + // If encoding/json has a position, prefer that, as it relates to json.Unmarshal's error message. + if synErr, ok := err.(*json.SyntaxError); ok && len(b) > 0 { + tokFile := token.NewFile(path, 0, len(b)) + tokFile.SetLinesForContent(b) + p = tokFile.Pos(int(synErr.Offset-1), token.NoRelPos) + } + return nil, errors.Wrapf(err, p, "invalid JSON for file %q", path) } return expr, nil @@ -94,30 +92,41 @@ func extract(path string, b []byte) (ast.Expr, error) { // information with each node. The runtime may be nil if the decoder // is only used to extract to CUE ast objects. // -// The runtime may be nil if Decode isn't used. +// The runtime argument is a historical remnant and unused. func NewDecoder(r *cue.Runtime, path string, src io.Reader) *Decoder { + b, err := source.ReadAll(path, src) + tokFile := token.NewFile(path, 0, len(b)) + tokFile.SetLinesForContent(b) return &Decoder{ - r: r, - path: path, - dec: json.NewDecoder(src), + path: path, + dec: json.NewDecoder(bytes.NewReader(b)), + tokFile: tokFile, + readAllErr: err, } } // A Decoder converts JSON values to CUE. type Decoder struct { - r *cue.Runtime path string dec *json.Decoder + + startOffset int + tokFile *token.File + readAllErr error } // Extract converts the current JSON value to a CUE ast. It returns io.EOF // if the input has been exhausted. func (d *Decoder) Extract() (ast.Expr, error) { + if d.readAllErr != nil { + return nil, d.readAllErr + } + expr, err := d.extract() if err != nil { return expr, err } - patchExpr(expr) + patchExpr(expr, d.patchPos) return expr, nil } @@ -128,34 +137,33 @@ func (d *Decoder) extract() (ast.Expr, error) { return nil, err } if err != nil { - pos := token.NewFile(d.path, -1, len(raw)).Pos(0, 0) + pos := token.NoPos + // When decoding into a RawMessage, encoding/json should only error due to syntax errors. + if synErr, ok := err.(*json.SyntaxError); ok { + pos = d.tokFile.Pos(int(synErr.Offset-1), token.NoRelPos) + } return nil, errors.Wrapf(err, pos, "invalid JSON for file %q", d.path) } expr, err := parser.ParseExpr(d.path, []byte(raw)) - if err != nil { return nil, err } + + d.startOffset = int(d.dec.InputOffset()) - len(raw) return expr, nil } -// Decode converts the current JSON value to a CUE instance. It returns io.EOF -// if the input has been exhausted. -// -// Deprecated: use Extract and build with cue.Context.BuildExpr. -func (d *Decoder) Decode() (*cue.Instance, error) { - expr, err := d.Extract() - if err != nil { - return nil, err - } - return d.r.CompileExpr(expr) +func (d *Decoder) patchPos(n ast.Node) { + pos := n.Pos() + realPos := d.tokFile.Pos(pos.Offset()+d.startOffset, pos.RelPos()) + ast.SetPos(n, realPos) } // patchExpr simplifies the AST parsed from JSON. // TODO: some of the modifications are already done in format, but are // a package deal of a more aggressive simplify. Other pieces of modification // should probably be moved to format. -func patchExpr(n ast.Node) { +func patchExpr(n ast.Node, patchPos func(n ast.Node)) { type info struct { reflow bool } @@ -171,6 +179,10 @@ func patchExpr(n ast.Node) { var beforeFn func(n ast.Node) bool beforeFn = func(n ast.Node) bool { + if patchPos != nil { + patchPos(n) + } + isLarge := n.End().Offset()-n.Pos().Offset() > 50 descent := true diff --git a/vendor/cuelang.org/go/encoding/jsonschema/constraints.go b/vendor/cuelang.org/go/encoding/jsonschema/constraints.go index c40cf6a512..ceb1b3a0e3 100644 --- a/vendor/cuelang.org/go/encoding/jsonschema/constraints.go +++ b/vendor/cuelang.org/go/encoding/jsonschema/constraints.go @@ -16,20 +16,10 @@ package jsonschema import ( "fmt" - "math/big" - "path" - "regexp" "cuelang.org/go/cue" - "cuelang.org/go/cue/ast" - "cuelang.org/go/cue/errors" - "cuelang.org/go/cue/token" - "cuelang.org/go/internal" ) -// TODO: skip invalid regexps containing ?! and foes. -// alternatively, fall back to https://github.com/dlclark/regexp2 - type constraint struct { key string @@ -40,676 +30,126 @@ type constraint struct { // "required" and thus must have a lower phase number than the latter. phase int - // Indicates the draft number in which this constraint is defined. - draft int - fn constraintFunc + // versions holds the versions for which this constraint is defined. + versions versionSet + fn constraintFunc } // A constraintFunc converts a given JSON Schema constraint (specified in n) // to a CUE constraint recorded in state. -type constraintFunc func(n cue.Value, s *state) - -func p0(name string, f constraintFunc) *constraint { - return &constraint{key: name, fn: f} -} - -func p1d(name string, draft int, f constraintFunc) *constraint { - return &constraint{key: name, phase: 1, draft: draft, fn: f} -} - -func p1(name string, f constraintFunc) *constraint { - return &constraint{key: name, phase: 1, fn: f} -} - -func p2(name string, f constraintFunc) *constraint { - return &constraint{key: name, phase: 2, fn: f} -} - -func p3(name string, f constraintFunc) *constraint { - return &constraint{key: name, phase: 3, fn: f} -} - -// TODO: -// writeOnly, readOnly +type constraintFunc func(key string, n cue.Value, s *state) var constraintMap = map[string]*constraint{} func init() { for _, c := range constraints { + if _, ok := constraintMap[c.key]; ok { + panic(fmt.Errorf("duplicate constraint entry for %q", c.key)) + } constraintMap[c.key] = c } } -func addDefinitions(n cue.Value, s *state) { - if n.Kind() != cue.StructKind { - s.errf(n, `"definitions" expected an object, found %s`, n.Kind()) - } - - old := s.isSchema - s.isSchema = true - defer func() { s.isSchema = old }() - - s.processMap(n, func(key string, n cue.Value) { - name := key - - var f *ast.Field +// Note: the following table is ordered lexically by keyword name. +// The various implementations are grouped by kind in the constraint-*.go files. - ident := "#" + name - if ast.IsValidIdent(ident) { - f = &ast.Field{Value: s.schema(n, label{ident, true})} - f.Label = ast.NewIdent(ident) - } else { - f = &ast.Field{Value: s.schema(n, label{"#", true}, label{name: name})} - f.Label = ast.NewString(name) - ident = "#" - f = &ast.Field{ - Label: ast.NewIdent("#"), - Value: ast.NewStruct(f), - } - } +const numPhases = 5 - ast.SetRelPos(f, token.NewSection) - s.definitions = append(s.definitions, f) - s.setField(label{name: ident, isDef: true}, f) - }) -} +// Note: OpenAPI is excluded from version sets by default, as it does not fit in +// the linear progression of the rest of the JSON Schema versions. var constraints = []*constraint{ - // Meta data. - - p0("$schema", func(n cue.Value, s *state) { - // Identifies this as a JSON schema and specifies its version. - // TODO: extract version. - s.jsonschema, _ = s.strValue(n) - }), - - p0("$id", func(n cue.Value, s *state) { - // URL: https://domain.com/schemas/foo.json - // anchors: #identifier - // - // TODO: mark identifiers. - - // Resolution must be relative to parent $id - // https://tools.ietf.org/html/draft-handrews-json-schema-02#section-8.2.2 - u := s.resolveURI(n) - if u == nil { - return - } - - if u.Fragment != "" { - if s.cfg.Strict { - s.errf(n, "$id URI may not contain a fragment") - } - return - } - s.id = u - - obj := s.object(n) - - // TODO: handle the case where this is always defined and we don't want - // to include the default value. - obj.Elts = append(obj.Elts, &ast.Attribute{ - Text: fmt.Sprintf("@jsonschema(id=%q)", u)}) - }), - - // Generic constraint - - p1("type", func(n cue.Value, s *state) { - var types cue.Kind - set := func(n cue.Value) { - str, ok := s.strValue(n) - if !ok { - s.errf(n, "type value should be a string") - } - switch str { - case "null": - types |= cue.NullKind - s.setTypeUsed(n, nullType) - // TODO: handle OpenAPI restrictions. - case "boolean": - types |= cue.BoolKind - s.setTypeUsed(n, boolType) - case "string": - types |= cue.StringKind - s.setTypeUsed(n, stringType) - case "number": - types |= cue.NumberKind - s.setTypeUsed(n, numType) - case "integer": - types |= cue.IntKind - s.setTypeUsed(n, numType) - s.add(n, numType, ast.NewIdent("int")) - case "array": - types |= cue.ListKind - s.setTypeUsed(n, arrayType) - case "object": - types |= cue.StructKind - s.setTypeUsed(n, objectType) - - default: - s.errf(n, "unknown type %q", n) - } - } - - switch n.Kind() { - case cue.StringKind: - set(n) - case cue.ListKind: - for i, _ := n.List(); i.Next(); { - set(i.Value()) - } - default: - s.errf(n, `value of "type" must be a string or list of strings`) - } - - s.allowedTypes &= types - }), - - p1("enum", func(n cue.Value, s *state) { - var a []ast.Expr - for _, x := range s.listItems("enum", n, true) { - a = append(a, s.value(x)) - } - s.all.add(n, ast.NewBinExpr(token.OR, a...)) - }), - - // TODO: only allow for OpenAPI. - p1("nullable", func(n cue.Value, s *state) { - null := ast.NewNull() - setPos(null, n) - s.nullable = null - }), - - p1d("const", 6, func(n cue.Value, s *state) { - s.all.add(n, s.value(n)) - }), - - p1("default", func(n cue.Value, s *state) { - sc := *s - s.default_ = sc.value(n) - // TODO: must validate that the default is subsumed by the normal value, - // as CUE will otherwise broaden the accepted values with the default. - s.examples = append(s.examples, s.default_) - }), - - p1("deprecated", func(n cue.Value, s *state) { - if s.boolValue(n) { - s.deprecated = true - } - }), - - p1("examples", func(n cue.Value, s *state) { - if n.Kind() != cue.ListKind { - s.errf(n, `value of "examples" must be an array, found %v`, n.Kind()) - } - // TODO: implement examples properly. - // for _, n := range s.listItems("examples", n, true) { - // if ex := s.value(n); !isAny(ex) { - // s.examples = append(s.examples, ex) - // } - // } - }), - - p1("description", func(n cue.Value, s *state) { - s.description, _ = s.strValue(n) - }), - - p1("title", func(n cue.Value, s *state) { - s.title, _ = s.strValue(n) - }), - - p1d("$comment", 7, func(n cue.Value, s *state) { - }), - - p1("$defs", addDefinitions), - p1("definitions", addDefinitions), - p1("$ref", func(n cue.Value, s *state) { - s.usedTypes = allTypes - - u := s.resolveURI(n) - - if u.Fragment != "" && !path.IsAbs(u.Fragment) { - s.addErr(errors.Newf(n.Pos(), "anchors (%s) not supported", u.Fragment)) - // TODO: support anchors - return - } - - expr := s.makeCUERef(n, u) - - if expr == nil { - expr = &ast.BadExpr{From: n.Pos()} - } - - s.all.add(n, expr) - }), - - // Combinators - - // TODO: work this out in more detail: oneOf and anyOf below have the same - // implementation in CUE. The distinction is that for anyOf a result is - // allowed to be ambiguous at the end, whereas for oneOf a disjunction must - // be fully resolved. There is currently no easy way to set this distinction - // in CUE. - // - // One could correctly write oneOf like this once 'not' is implemented: - // - // oneOf(a, b, c) :- - // anyOf( - // allOf(a, not(b), not(c)), - // allOf(not(a), b, not(c)), - // allOf(not(a), not(b), c), - // )) - // - // This is not necessary if the values are mutually exclusive/ have a - // discriminator. - - p2("allOf", func(n cue.Value, s *state) { - var a []ast.Expr - for _, v := range s.listItems("allOf", n, false) { - x, sub := s.schemaState(v, s.allowedTypes, nil, true) - s.allowedTypes &= sub.allowedTypes - s.usedTypes |= sub.usedTypes - if sub.hasConstraints() { - a = append(a, x) - } - } - if len(a) > 0 { - s.all.add(n, ast.NewBinExpr(token.AND, a...)) - } - }), - - p2("anyOf", func(n cue.Value, s *state) { - var types cue.Kind - var a []ast.Expr - for _, v := range s.listItems("anyOf", n, false) { - x, sub := s.schemaState(v, s.allowedTypes, nil, true) - types |= sub.allowedTypes - a = append(a, x) - } - s.allowedTypes &= types - if len(a) > 0 { - s.all.add(n, ast.NewBinExpr(token.OR, a...)) - } - }), - - p2("oneOf", func(n cue.Value, s *state) { - var types cue.Kind - var a []ast.Expr - hasSome := false - for _, v := range s.listItems("oneOf", n, false) { - x, sub := s.schemaState(v, s.allowedTypes, nil, true) - types |= sub.allowedTypes - - // TODO: make more finegrained by making it two pass. - if sub.hasConstraints() { - hasSome = true - } - - if !isAny(x) { - a = append(a, x) - } - } - s.allowedTypes &= types - if len(a) > 0 && hasSome { - s.usedTypes = allTypes - s.all.add(n, ast.NewBinExpr(token.OR, a...)) - } - - // TODO: oneOf({a:x}, {b:y}, ..., not(anyOf({a:x}, {b:y}, ...))), - // can be translated to {} | {a:x}, {b:y}, ... - }), - - // String constraints - - p1("pattern", func(n cue.Value, s *state) { - str, _ := n.String() - if _, err := regexp.Compile(str); err != nil { - if s.cfg.Strict { - s.errf(n, "unsupported regexp: %v", err) - } - return - } - s.usedTypes |= cue.StringKind - s.add(n, stringType, &ast.UnaryExpr{Op: token.MAT, X: s.string(n)}) - }), - - p1("minLength", func(n cue.Value, s *state) { - s.usedTypes |= cue.StringKind - min := s.number(n) - strings := s.addImport(n, "strings") - s.add(n, stringType, ast.NewCall(ast.NewSel(strings, "MinRunes"), min)) - }), - - p1("maxLength", func(n cue.Value, s *state) { - s.usedTypes |= cue.StringKind - max := s.number(n) - strings := s.addImport(n, "strings") - s.add(n, stringType, ast.NewCall(ast.NewSel(strings, "MaxRunes"), max)) - }), - - p1d("contentMediaType", 7, func(n cue.Value, s *state) { - // TODO: only mark as used if it generates something. - // s.usedTypes |= cue.StringKind - }), - - p1d("contentEncoding", 7, func(n cue.Value, s *state) { - // TODO: only mark as used if it generates something. - // s.usedTypes |= cue.StringKind - // 7bit, 8bit, binary, quoted-printable and base64. - // RFC 2054, part 6.1. - // https://tools.ietf.org/html/rfc2045 - // TODO: at least handle bytes. - }), - - // Number constraints - - p2("minimum", func(n cue.Value, s *state) { - s.usedTypes |= cue.NumberKind - op := token.GEQ - if s.exclusiveMin { - op = token.GTR - } - s.add(n, numType, &ast.UnaryExpr{Op: op, X: s.number(n)}) - }), - - p1("exclusiveMinimum", func(n cue.Value, s *state) { - if n.Kind() == cue.BoolKind { - s.exclusiveMin = true - return - } - s.usedTypes |= cue.NumberKind - s.add(n, numType, &ast.UnaryExpr{Op: token.GTR, X: s.number(n)}) - }), - - p2("maximum", func(n cue.Value, s *state) { - s.usedTypes |= cue.NumberKind - op := token.LEQ - if s.exclusiveMax { - op = token.LSS - } - s.add(n, numType, &ast.UnaryExpr{Op: op, X: s.number(n)}) - }), - - p1("exclusiveMaximum", func(n cue.Value, s *state) { - if n.Kind() == cue.BoolKind { - s.exclusiveMax = true - return - } - s.usedTypes |= cue.NumberKind - s.add(n, numType, &ast.UnaryExpr{Op: token.LSS, X: s.number(n)}) - }), - - p1("multipleOf", func(n cue.Value, s *state) { - s.usedTypes |= cue.NumberKind - multiple := s.number(n) - var x big.Int - _, _ = n.MantExp(&x) - if x.Cmp(big.NewInt(0)) != 1 { - s.errf(n, `"multipleOf" value must be < 0; found %s`, n) - } - math := s.addImport(n, "math") - s.add(n, numType, ast.NewCall(ast.NewSel(math, "MultipleOf"), multiple)) - }), - - // Object constraints - - p1("properties", func(n cue.Value, s *state) { - s.usedTypes |= cue.StructKind - obj := s.object(n) - - if n.Kind() != cue.StructKind { - s.errf(n, `"properties" expected an object, found %v`, n.Kind()) - } - - s.processMap(n, func(key string, n cue.Value) { - // property?: value - name := ast.NewString(key) - expr, state := s.schemaState(n, allTypes, []label{{name: key}}, false) - f := &ast.Field{Label: name, Value: expr} - state.doc(f) - f.Optional = token.Blank.Pos() - if len(obj.Elts) > 0 && len(f.Comments()) > 0 { - // TODO: change formatter such that either a NewSection on the - // field or doc comment will cause a new section. - ast.SetRelPos(f.Comments()[0], token.NewSection) - } - if state.deprecated { - switch expr.(type) { - case *ast.StructLit: - obj.Elts = append(obj.Elts, addTag(name, "deprecated", "")) - default: - f.Attrs = append(f.Attrs, internal.NewAttr("deprecated", "")) - } - } - obj.Elts = append(obj.Elts, f) - s.setField(label{name: key}, f) - }) - }), - - p2("required", func(n cue.Value, s *state) { - if n.Kind() != cue.ListKind { - s.errf(n, `value of "required" must be list of strings, found %v`, n.Kind()) - return - } - - s.usedTypes |= cue.StructKind - - // TODO: detect that properties is defined somewhere. - // s.errf(n, `"required" without a "properties" field`) - obj := s.object(n) - - // Create field map - fields := map[string]*ast.Field{} - for _, d := range obj.Elts { - f, ok := d.(*ast.Field) - if !ok { - continue // Could be embedding? See cirrus.json - } - str, _, err := ast.LabelName(f.Label) - if err == nil { - fields[str] = f - } - } - - for _, n := range s.listItems("required", n, true) { - str, ok := s.strValue(n) - f := fields[str] - if f == nil && ok { - f := &ast.Field{ - Label: ast.NewString(str), - Value: ast.NewIdent("_"), - } - fields[str] = f - obj.Elts = append(obj.Elts, f) - continue - } - if f.Optional == token.NoPos { - s.errf(n, "duplicate required field %q", str) - } - f.Optional = token.NoPos - } - }), - - p1d("propertyNames", 6, func(n cue.Value, s *state) { - // [=~pattern]: _ - if names, _ := s.schemaState(n, cue.StringKind, nil, false); !isAny(names) { - s.usedTypes |= cue.StructKind - x := ast.NewStruct(ast.NewList(names), ast.NewIdent("_")) - s.add(n, objectType, x) - } - }), - - // TODO: reenable when we have proper non-monotonic contraint validation. - // p1("minProperties", func(n cue.Value, s *state) { - // s.usedTypes |= cue.StructKind - - // pkg := s.addImport(n, "struct") - // s.addConjunct(n, ast.NewCall(ast.NewSel(pkg, "MinFields"), s.uint(n))) - // }), - - p1("maxProperties", func(n cue.Value, s *state) { - s.usedTypes |= cue.StructKind - - pkg := s.addImport(n, "struct") - x := ast.NewCall(ast.NewSel(pkg, "MaxFields"), s.uint(n)) - s.add(n, objectType, x) - }), - - p1("dependencies", func(n cue.Value, s *state) { - s.usedTypes |= cue.StructKind - - // Schema and property dependencies. - // TODO: the easiest implementation is with comprehensions. - // The nicer implementation is with disjunctions. This has to be done - // at the very end, replacing properties. - /* - *{ property?: _|_ } | { - property: _ - schema - } - */ - }), - - p2("patternProperties", func(n cue.Value, s *state) { - s.usedTypes |= cue.StructKind - if n.Kind() != cue.StructKind { - s.errf(n, `value of "patternProperties" must be an object, found %v`, n.Kind()) - } - obj := s.object(n) - existing := excludeFields(s.obj.Elts) - s.processMap(n, func(key string, n cue.Value) { - // [!~(properties) & pattern]: schema - s.patterns = append(s.patterns, - &ast.UnaryExpr{Op: token.NMAT, X: ast.NewString(key)}) - f := internal.EmbedStruct(ast.NewStruct(&ast.Field{ - Label: ast.NewList(ast.NewBinExpr(token.AND, - &ast.UnaryExpr{Op: token.MAT, X: ast.NewString(key)}, - existing)), - Value: s.schema(n), - })) - ast.SetRelPos(f, token.NewSection) - obj.Elts = append(obj.Elts, f) - }) - }), - - p3("additionalProperties", func(n cue.Value, s *state) { - switch n.Kind() { - case cue.BoolKind: - s.closeStruct = !s.boolValue(n) - - case cue.StructKind: - s.usedTypes |= cue.StructKind - s.closeStruct = true - obj := s.object(n) - if len(obj.Elts) == 0 { - obj.Elts = append(obj.Elts, &ast.Field{ - Label: ast.NewList(ast.NewIdent("string")), - Value: s.schema(n), - }) - return - } - // [!~(properties|patternProperties)]: schema - existing := append(s.patterns, excludeFields(obj.Elts)) - f := internal.EmbedStruct(ast.NewStruct(&ast.Field{ - Label: ast.NewList(ast.NewBinExpr(token.AND, existing...)), - Value: s.schema(n), - })) - obj.Elts = append(obj.Elts, f) - - default: - s.errf(n, `value of "additionalProperties" must be an object or boolean`) - } - }), - - // Array constraints. - - p1("items", func(n cue.Value, s *state) { - s.usedTypes |= cue.ListKind - switch n.Kind() { - case cue.StructKind: - elem := s.schema(n) - ast.SetRelPos(elem, token.NoRelPos) - s.add(n, arrayType, ast.NewList(&ast.Ellipsis{Type: elem})) - - case cue.ListKind: - var a []ast.Expr - for _, n := range s.listItems("items", n, true) { - v := s.schema(n) // TODO: label with number literal. - ast.SetRelPos(v, token.NoRelPos) - a = append(a, v) - } - s.list = ast.NewList(a...) - s.add(n, arrayType, s.list) - - default: - s.errf(n, `value of "items" must be an object or array`) - } - }), - - p1("additionalItems", func(n cue.Value, s *state) { - switch n.Kind() { - case cue.BoolKind: - // TODO: support - - case cue.StructKind: - if s.list != nil { - s.usedTypes |= cue.ListKind - elem := s.schema(n) - s.list.Elts = append(s.list.Elts, &ast.Ellipsis{Type: elem}) - } - - default: - s.errf(n, `value of "additionalItems" must be an object or boolean`) - } - }), - - p1("contains", func(n cue.Value, s *state) { - s.usedTypes |= cue.ListKind - list := s.addImport(n, "list") - // TODO: Passing non-concrete values is not yet supported in CUE. - if x := s.schema(n); !isAny(x) { - x := ast.NewCall(ast.NewSel(list, "Contains"), clearPos(x)) - s.add(n, arrayType, x) - } - }), - - // TODO: min/maxContains + px("$anchor", constraintTODO, vfrom(VersionDraft2019_09)), + p2("$comment", constraintComment, vfrom(VersionDraft7)), + p2("$defs", constraintAddDefinitions, allVersions), + px("$dynamicAnchor", constraintTODO, vfrom(VersionDraft2020_12)), + px("$dynamicRef", constraintTODO, vfrom(VersionDraft2020_12)), + p1("$id", constraintID, vfrom(VersionDraft6)), + px("$recursiveAnchor", constraintTODO, vbetween(VersionDraft2019_09, VersionDraft2020_12)), + px("$recursiveRef", constraintTODO, vbetween(VersionDraft2019_09, VersionDraft2020_12)), + p2("$ref", constraintRef, allVersions|openAPI), + p0("$schema", constraintSchema, allVersions), + px("$vocabulary", constraintTODO, vfrom(VersionDraft2019_09)), + p4("additionalItems", constraintAdditionalItems, vto(VersionDraft2019_09)), + p4("additionalProperties", constraintAdditionalProperties, allVersions|openAPI), + p3("allOf", constraintAllOf, allVersions|openAPI), + p3("anyOf", constraintAnyOf, allVersions|openAPI), + p2("const", constraintConst, vfrom(VersionDraft6)), + p2("contains", constraintContains, vfrom(VersionDraft6)), + p2("contentEncoding", constraintContentEncoding, vfrom(VersionDraft7)), + p2("contentMediaType", constraintContentMediaType, vfrom(VersionDraft7)), + px("contentSchema", constraintTODO, vfrom(VersionDraft2019_09)), + p2("default", constraintDefault, allVersions|openAPI), + p2("definitions", constraintAddDefinitions, allVersions), + p2("dependencies", constraintDependencies, allVersions), + px("dependentRequired", constraintTODO, vfrom(VersionDraft2019_09)), + px("dependentSchemas", constraintTODO, vfrom(VersionDraft2019_09)), + p2("deprecated", constraintDeprecated, vfrom(VersionDraft2019_09)|openAPI), + p2("description", constraintDescription, allVersions|openAPI), + px("discriminator", constraintTODO, openAPI), + p1("else", constraintElse, vfrom(VersionDraft7)), + p2("enum", constraintEnum, allVersions|openAPI), + px("example", constraintTODO, openAPI), + p2("examples", constraintExamples, vfrom(VersionDraft6)), + p2("exclusiveMaximum", constraintExclusiveMaximum, allVersions|openAPI), + p2("exclusiveMinimum", constraintExclusiveMinimum, allVersions|openAPI), + px("externalDocs", constraintTODO, openAPI), + p1("format", constraintFormat, allVersions|openAPI), + p1("id", constraintID, vto(VersionDraft4)), + p1("if", constraintIf, vfrom(VersionDraft7)), + p2("items", constraintItems, allVersions|openAPI), + p1("maxContains", constraintMaxContains, vfrom(VersionDraft2019_09)), + p2("maxItems", constraintMaxItems, allVersions|openAPI), + p2("maxLength", constraintMaxLength, allVersions|openAPI), + p2("maxProperties", constraintMaxProperties, allVersions|openAPI), + p3("maximum", constraintMaximum, allVersions|openAPI), + p1("minContains", constraintMinContains, vfrom(VersionDraft2019_09)), + p2("minItems", constraintMinItems, allVersions|openAPI), + p2("minLength", constraintMinLength, allVersions|openAPI), + p1("minProperties", constraintMinProperties, allVersions|openAPI), + p3("minimum", constraintMinimum, allVersions|openAPI), + p2("multipleOf", constraintMultipleOf, allVersions|openAPI), + p3("not", constraintNot, allVersions|openAPI), + p2("nullable", constraintNullable, openAPI), + p3("oneOf", constraintOneOf, allVersions|openAPI), + p2("pattern", constraintPattern, allVersions|openAPI), + p3("patternProperties", constraintPatternProperties, allVersions), + p2("prefixItems", constraintPrefixItems, vfrom(VersionDraft2020_12)), + p2("properties", constraintProperties, allVersions|openAPI), + p2("propertyNames", constraintPropertyNames, vfrom(VersionDraft6)), + px("readOnly", constraintTODO, vfrom(VersionDraft7)|openAPI), + p3("required", constraintRequired, allVersions|openAPI), + p1("then", constraintThen, vfrom(VersionDraft7)), + p2("title", constraintTitle, allVersions|openAPI), + p2("type", constraintType, allVersions|openAPI), + px("unevaluatedItems", constraintTODO, vfrom(VersionDraft2019_09)), + px("unevaluatedProperties", constraintTODO, vfrom(VersionDraft2019_09)), + p2("uniqueItems", constraintUniqueItems, allVersions|openAPI), + px("writeOnly", constraintTODO, vfrom(VersionDraft7)|openAPI), + px("xml", constraintTODO, openAPI), +} - p1("minItems", func(n cue.Value, s *state) { - s.usedTypes |= cue.ListKind - a := []ast.Expr{} - p, err := n.Uint64() - if err != nil { - s.errf(n, "invalid uint") - } - for ; p > 0; p-- { - a = append(a, ast.NewIdent("_")) - } - s.add(n, arrayType, ast.NewList(append(a, &ast.Ellipsis{})...)) +// px represents a TODO constraint that we haven't decided on a phase for yet. +func px(name string, f constraintFunc, versions versionSet) *constraint { + return p1(name, f, versions) +} - // TODO: use this once constraint resolution is properly implemented. - // list := s.addImport(n, "list") - // s.addConjunct(n, ast.NewCall(ast.NewSel(list, "MinItems"), clearPos(s.uint(n)))) - }), +func p0(name string, f constraintFunc, versions versionSet) *constraint { + return &constraint{key: name, phase: 0, versions: versions, fn: f} +} - p1("maxItems", func(n cue.Value, s *state) { - s.usedTypes |= cue.ListKind - list := s.addImport(n, "list") - x := ast.NewCall(ast.NewSel(list, "MaxItems"), clearPos(s.uint(n))) - s.add(n, arrayType, x) +func p1(name string, f constraintFunc, versions versionSet) *constraint { + return &constraint{key: name, phase: 1, versions: versions, fn: f} +} - }), +func p2(name string, f constraintFunc, versions versionSet) *constraint { + return &constraint{key: name, phase: 2, versions: versions, fn: f} +} - p1("uniqueItems", func(n cue.Value, s *state) { - s.usedTypes |= cue.ListKind - if s.boolValue(n) { - list := s.addImport(n, "list") - s.add(n, arrayType, ast.NewCall(ast.NewSel(list, "UniqueItems"))) - } - }), +func p3(name string, f constraintFunc, versions versionSet) *constraint { + return &constraint{key: name, phase: 3, versions: versions, fn: f} } -func clearPos(e ast.Expr) ast.Expr { - ast.SetRelPos(e, token.NoRelPos) - return e +func p4(name string, f constraintFunc, versions versionSet) *constraint { + return &constraint{key: name, phase: 4, versions: versions, fn: f} } diff --git a/vendor/cuelang.org/go/encoding/jsonschema/constraints_array.go b/vendor/cuelang.org/go/encoding/jsonschema/constraints_array.go new file mode 100644 index 0000000000..785adbc2a7 --- /dev/null +++ b/vendor/cuelang.org/go/encoding/jsonschema/constraints_array.go @@ -0,0 +1,168 @@ +// Copyright 2019 CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package jsonschema + +import ( + "strconv" + + "cuelang.org/go/cue" + "cuelang.org/go/cue/ast" + "cuelang.org/go/cue/token" +) + +// Array constraints + +func constraintAdditionalItems(key string, n cue.Value, s *state) { + var elem ast.Expr + switch n.Kind() { + case cue.BoolKind: + // Boolean values are supported even in earlier + // versions that did not support boolean schemas otherwise. + elem = boolSchema(s.boolValue(n)) + case cue.StructKind: + elem = s.schema(n) + default: + s.errf(n, `value of "additionalItems" must be an object or boolean`) + } + if s.list == nil || !s.listItemsIsArray { + // If there's no "items" keyword or its value is not an array "additionalItems" doesn't apply. + return + } + if len(s.list.Elts) == 0 { + // Should never happen because "items" always adds an ellipsis + panic("no elements in list") + } + last := s.list.Elts[len(s.list.Elts)-1].(*ast.Ellipsis) + if isBottom(elem) { + // No additional elements allowed. Remove the ellipsis. + s.list.Elts = s.list.Elts[:len(s.list.Elts)-1] + return + } + if isTop(elem) { + // Nothing to do: there's already an ellipsis in place that + // allows anything. + return + } + last.Type = elem +} + +func constraintMinContains(key string, n cue.Value, s *state) { + p, err := uint64Value(n) + if err != nil { + s.errf(n, `value of "minContains" must be a non-negative integer value`) + return + } + s.minContains = &p +} + +func constraintMaxContains(key string, n cue.Value, s *state) { + p, err := uint64Value(n) + if err != nil { + s.errf(n, `value of "maxContains" must be a non-negative integer value`) + return + } + s.maxContains = &p +} + +func constraintContains(key string, n cue.Value, s *state) { + list := s.addImport(n, "list") + x := s.schema(n) + + var min uint64 = 1 + if s.minContains != nil { + min = *s.minContains + } + var c ast.Expr = &ast.UnaryExpr{ + Op: token.GEQ, + X: ast.NewLit(token.INT, strconv.FormatUint(min, 10)), + } + + if s.maxContains != nil { + c = ast.NewBinExpr(token.AND, c, &ast.UnaryExpr{ + Op: token.LEQ, + X: ast.NewLit(token.INT, strconv.FormatUint(*s.maxContains, 10)), + }) + } + + x = ast.NewCall(ast.NewSel(list, "MatchN"), c, clearPos(x)) + s.add(n, arrayType, x) +} + +func constraintItems(key string, n cue.Value, s *state) { + switch n.Kind() { + case cue.StructKind, cue.BoolKind: + elem := s.schema(n) + ast.SetRelPos(elem, token.NoRelPos) + s.add(n, arrayType, ast.NewList(&ast.Ellipsis{Type: elem})) + + case cue.ListKind: + if !vto(VersionDraft2019_09).contains(s.schemaVersion) { + // The list form is only supported up to 2019-09 + s.errf(n, `from version %v onwards, the value of "items" must be an object or a boolean`, VersionDraft2020_12) + return + } + s.listItemsIsArray = true + constraintPrefixItems(key, n, s) + } +} + +func constraintPrefixItems(key string, n cue.Value, s *state) { + if n.Kind() != cue.ListKind { + s.errf(n, `value of "prefixItems" must be an array`) + } + var a []ast.Expr + for _, n := range s.listItems(key, n, true) { + v := s.schema(n) // TODO: label with number literal. + ast.SetRelPos(v, token.NoRelPos) + a = append(a, v) + } + s.list = ast.NewList(a...) + s.list.Elts = append(s.list.Elts, &ast.Ellipsis{}) + s.add(n, arrayType, s.list) +} + +func constraintMaxItems(key string, n cue.Value, s *state) { + list := s.addImport(n, "list") + x := ast.NewCall(ast.NewSel(list, "MaxItems"), clearPos(s.uint(n))) + s.add(n, arrayType, x) +} + +func constraintMinItems(key string, n cue.Value, s *state) { + a := []ast.Expr{} + p, err := uint64Value(n) + if err != nil { + s.errf(n, "invalid uint") + } + for ; p > 0; p-- { + a = append(a, top()) + } + s.add(n, arrayType, ast.NewList(append(a, &ast.Ellipsis{})...)) + + // TODO: use this once constraint resolution is properly implemented. + // list := s.addImport(n, "list") + // s.addConjunct(n, ast.NewCall(ast.NewSel(list, "MinItems"), clearPos(s.uint(n)))) +} + +func constraintUniqueItems(key string, n cue.Value, s *state) { + if s.boolValue(n) { + list := s.addImport(n, "list") + s.add(n, arrayType, ast.NewCall(ast.NewSel(list, "UniqueItems"))) + } +} + +func clearPos(e ast.Expr) ast.Expr { + ast.SetRelPos(e, token.NoRelPos) + return e +} diff --git a/vendor/cuelang.org/go/encoding/jsonschema/constraints_combinator.go b/vendor/cuelang.org/go/encoding/jsonschema/constraints_combinator.go new file mode 100644 index 0000000000..07ece912ab --- /dev/null +++ b/vendor/cuelang.org/go/encoding/jsonschema/constraints_combinator.go @@ -0,0 +1,222 @@ +// Copyright 2019 CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package jsonschema + +import ( + "strconv" + + "cuelang.org/go/cue" + "cuelang.org/go/cue/ast" + "cuelang.org/go/cue/token" +) + +// Constraint combinators. + +func constraintAllOf(key string, n cue.Value, s *state) { + var knownTypes cue.Kind + items := s.listItems("allOf", n, false) + if len(items) == 0 { + s.errf(n, "allOf requires at least one subschema") + return + } + a := make([]ast.Expr, 0, len(items)) + for _, v := range items { + x, sub := s.schemaState(v, s.allowedTypes) + s.allowedTypes &= sub.allowedTypes + if sub.hasConstraints { + // This might seem a little odd, since the actual + // types are the intersection of the known types + // of the allOf members. However, knownTypes + // is really there to avoid adding redundant disjunctions. + // So if we have (int & string) & (disjunction) + // we definitely don't have to add int or string to + // disjunction. + knownTypes |= sub.knownTypes + a = append(a, x) + } + } + // TODO maybe give an error/warning if s.allowedTypes == 0 + // as that's a known-impossible assertion? + if len(a) > 0 { + s.knownTypes &= knownTypes + if len(a) == 1 { + // Only one possibility. Use that. + s.all.add(n, a[0]) + return + } + s.all.add(n, ast.NewCall( + ast.NewIdent("matchN"), + // TODO it would be nice to be able to use a special sentinel "all" value + // here rather than redundantly encoding the length of the list. + &ast.BasicLit{ + Kind: token.INT, + Value: strconv.Itoa(len(items)), + }, + ast.NewList(a...), + )) + } +} + +func constraintAnyOf(key string, n cue.Value, s *state) { + var types cue.Kind + var knownTypes cue.Kind + items := s.listItems("anyOf", n, false) + if len(items) == 0 { + s.errf(n, "anyOf requires at least one subschema") + return + } + a := make([]ast.Expr, 0, len(items)) + for _, v := range items { + x, sub := s.schemaState(v, s.allowedTypes) + if sub.allowedTypes == 0 { + // Nothing is allowed; omit. + continue + } + types |= sub.allowedTypes + knownTypes |= sub.knownTypes + a = append(a, x) + } + if len(a) == 0 { + // Nothing at all is allowed. + s.allowedTypes = 0 + return + } + if len(a) == 1 { + s.all.add(n, a[0]) + return + } + s.allowedTypes &= types + s.knownTypes &= knownTypes + s.all.add(n, ast.NewCall( + ast.NewIdent("matchN"), + &ast.UnaryExpr{ + Op: token.GEQ, + X: &ast.BasicLit{ + Kind: token.INT, + Value: "1", + }, + }, + ast.NewList(a...), + )) +} + +func constraintOneOf(key string, n cue.Value, s *state) { + var types cue.Kind + var knownTypes cue.Kind + needsConstraint := false + items := s.listItems("oneOf", n, false) + if len(items) == 0 { + s.errf(n, "oneOf requires at least one subschema") + return + } + a := make([]ast.Expr, 0, len(items)) + for _, v := range items { + x, sub := s.schemaState(v, s.allowedTypes) + if sub.allowedTypes == 0 { + // Nothing is allowed; omit + continue + } + + // TODO: make more finegrained by making it two pass. + if sub.hasConstraints { + needsConstraint = true + } else if (types & sub.allowedTypes) != 0 { + // If there's overlap between the unconstrained elements, + // we'll definitely need to add a constraint. + needsConstraint = true + } + types |= sub.allowedTypes + knownTypes |= sub.knownTypes + a = append(a, x) + } + // TODO if there are no elements in the oneOf, validation + // should fail. + s.allowedTypes &= types + if len(a) > 0 && needsConstraint { + s.knownTypes &= knownTypes + if len(a) == 1 { + // Only one possibility. Use that. + s.all.add(n, a[0]) + return + } + s.all.add(n, ast.NewCall( + ast.NewIdent("matchN"), + &ast.BasicLit{ + Kind: token.INT, + Value: "1", + }, + ast.NewList(a...), + )) + } + + // TODO: oneOf({a:x}, {b:y}, ..., not(anyOf({a:x}, {b:y}, ...))), + // can be translated to {} | {a:x}, {b:y}, ... +} + +func constraintNot(key string, n cue.Value, s *state) { + subSchema := s.schema(n) + s.all.add(n, ast.NewCall( + ast.NewIdent("matchN"), + &ast.BasicLit{ + Kind: token.INT, + Value: "0", + }, + ast.NewList(subSchema), + )) +} + +func constraintIf(key string, n cue.Value, s *state) { + s.ifConstraint = n +} + +func constraintThen(key string, n cue.Value, s *state) { + s.thenConstraint = n +} + +func constraintElse(key string, n cue.Value, s *state) { + s.elseConstraint = n +} + +// constraintIfThenElse is not implemented as a standard constraint +// function because it needs to operate knowing about the presence +// of all of "if", "then" and "else". +func constraintIfThenElse(s *state) { + hasIf, hasThen, hasElse := s.ifConstraint.Exists(), s.thenConstraint.Exists(), s.elseConstraint.Exists() + if !hasIf || (!hasThen && !hasElse) { + return + } + var ifExpr, thenExpr, elseExpr ast.Expr + ifExpr, ifSub := s.schemaState(s.ifConstraint, s.allowedTypes) + if hasThen { + // The allowed types of the "then" constraint are constrained both + // by the current constraints and the "if" constraint. + thenExpr, _ = s.schemaState(s.thenConstraint, s.allowedTypes&ifSub.allowedTypes) + } + if hasElse { + elseExpr, _ = s.schemaState(s.elseConstraint, s.allowedTypes) + } + if thenExpr == nil { + thenExpr = top() + } + if elseExpr == nil { + elseExpr = top() + } + s.all.add(s.pos, ast.NewCall( + ast.NewIdent("matchIf"), + ifExpr, + thenExpr, + elseExpr, + )) +} diff --git a/vendor/cuelang.org/go/encoding/jsonschema/constraints_format.go b/vendor/cuelang.org/go/encoding/jsonschema/constraints_format.go new file mode 100644 index 0000000000..c6c578c9ab --- /dev/null +++ b/vendor/cuelang.org/go/encoding/jsonschema/constraints_format.go @@ -0,0 +1,129 @@ +// Copyright 2019 CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package jsonschema + +import ( + "sync" + + "cuelang.org/go/cue" + "cuelang.org/go/cue/ast" +) + +type formatFuncInfo struct { + versions versionSet + f func(n cue.Value, s *state) +} + +var formatFuncs = sync.OnceValue(func() map[string]formatFuncInfo { + return map[string]formatFuncInfo{ + "binary": {openAPI, formatTODO}, + "byte": {openAPI, formatTODO}, + "data": {openAPI, formatTODO}, + "date": {vfrom(VersionDraft7) | openAPI, formatDate}, + "date-time": {allVersions | openAPI, formatDateTime}, + "double": {openAPI, formatTODO}, + "duration": {vfrom(VersionDraft2019_09), formatTODO}, + "email": {allVersions | openAPI, formatTODO}, + "float": {openAPI, formatTODO}, + "hostname": {allVersions | openAPI, formatTODO}, + "idn-email": {vfrom(VersionDraft7), formatTODO}, + "idn-hostname": {vfrom(VersionDraft7), formatTODO}, + "int32": {openAPI, formatInt32}, + "int64": {openAPI, formatInt64}, + "ipv4": {allVersions | openAPI, formatTODO}, + "ipv6": {allVersions | openAPI, formatTODO}, + "iri": {vfrom(VersionDraft7), formatURI}, + "iri-reference": {vfrom(VersionDraft7), formatURIReference}, + "json-pointer": {vfrom(VersionDraft6), formatTODO}, + "password": {openAPI, formatTODO}, + "regex": {vfrom(VersionDraft7), formatRegex}, + "relative-json-pointer": {vfrom(VersionDraft7), formatTODO}, + "time": {vfrom(VersionDraft7), formatTODO}, + // TODO we should probably disallow non-ASCII URIs (IRIs) but + // this is good enough for now. + "uri": {allVersions | openAPI, formatURI}, + "uri-reference": {vfrom(VersionDraft6), formatURIReference}, + "uri-template": {vfrom(VersionDraft6), formatTODO}, + "uuid": {vfrom(VersionDraft2019_09), formatTODO}, + } +}) + +func constraintFormat(key string, n cue.Value, s *state) { + formatStr, ok := s.strValue(n) + if !ok { + return + } + // Note: OpenAPI 3.0 says "the format property is an open + // string-valued property, and can have any value" so even when + // StrictKeywords is true, we do not generate an error if we're + // using OpenAPI. TODO it would still be nice to have a mode + // that allows the use to find likely spelling mistakes in + // format values in OpenAPI. + finfo, ok := formatFuncs()[formatStr] + if !ok { + // TODO StrictKeywords isn't exactly right here, but in general + // we want unknown formats to be ignored even when StrictFeatures + // is enabled, and StrictKeywords is closest to what we want. + // Perhaps we should have a "lint" mode? + if s.cfg.StrictKeywords && s.schemaVersion != VersionOpenAPI { + s.errf(n, "unknown format %q", formatStr) + } + return + } + if !finfo.versions.contains(s.schemaVersion) { + if s.cfg.StrictKeywords && s.schemaVersion != VersionOpenAPI { + s.errf(n, "format %q is not recognized in schema version %v", formatStr, s.schemaVersion) + } + return + } + finfo.f(n, s) +} + +func formatURI(n cue.Value, s *state) { + s.add(n, stringType, ast.NewSel(s.addImport(n, "net"), "AbsURL")) +} + +func formatURIReference(n cue.Value, s *state) { + s.add(n, stringType, ast.NewSel(s.addImport(n, "net"), "URL")) +} + +func formatDateTime(n cue.Value, s *state) { + // TODO this is a bit stricter than the spec, because the spec + // allows lower-case "T" and "Z", and leap seconds, but + // it's not bad for now. + s.add(n, stringType, ast.NewSel(s.addImport(n, "time"), "Time")) +} + +func formatDate(n cue.Value, s *state) { + // TODO it might be nice to have a dedicated `time.Date` validator rather + // than using `time.Format`. + s.add(n, stringType, ast.NewCall(ast.NewSel(s.addImport(n, "time"), "Format"), ast.NewString("2006-01-02"))) +} + +func formatRegex(n cue.Value, s *state) { + // TODO this is a bit stricter than the spec, because the spec + // allows Perl idioms such as back-references. + s.add(n, stringType, ast.NewSel(s.addImport(n, "regexp"), "Valid")) +} + +func formatInt32(n cue.Value, s *state) { + s.add(n, numType, ast.NewIdent("int32")) +} + +func formatInt64(n cue.Value, s *state) { + s.add(n, numType, ast.NewIdent("int64")) +} + +func formatTODO(n cue.Value, s *state) {} diff --git a/vendor/cuelang.org/go/encoding/jsonschema/constraints_generic.go b/vendor/cuelang.org/go/encoding/jsonschema/constraints_generic.go new file mode 100644 index 0000000000..e220c81f24 --- /dev/null +++ b/vendor/cuelang.org/go/encoding/jsonschema/constraints_generic.go @@ -0,0 +1,221 @@ +// Copyright 2019 CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package jsonschema + +import ( + "errors" + "fmt" + "net/url" + "strings" + + "cuelang.org/go/cue" + "cuelang.org/go/cue/ast" + "cuelang.org/go/cue/token" +) + +// Generic constraints + +func constraintAddDefinitions(key string, n cue.Value, s *state) { + if n.Kind() != cue.StructKind { + s.errf(n, `%q expected an object, found %s`, key, n.Kind()) + } + + s.processMap(n, func(key string, n cue.Value) { + // Ensure that we are going to make a definition + // for this node. + s.ensureDefinition(n) + s.schema(n) + }) +} + +func constraintComment(key string, n cue.Value, s *state) { +} + +func constraintConst(key string, n cue.Value, s *state) { + s.all.add(n, s.constValue(n)) + s.allowedTypes &= n.Kind() + s.knownTypes &= n.Kind() +} + +func constraintDefault(key string, n cue.Value, s *state) { + // TODO make the default value available in a separate + // template-like CUE value outside of the usual schema output. +} + +func constraintDeprecated(key string, n cue.Value, s *state) { + if s.boolValue(n) { + s.deprecated = true + } +} + +func constraintDescription(key string, n cue.Value, s *state) { + s.description, _ = s.strValue(n) +} + +func constraintEnum(key string, n cue.Value, s *state) { + var a []ast.Expr + var types cue.Kind + for _, x := range s.listItems("enum", n, true) { + if (s.allowedTypes & x.Kind()) == 0 { + // Enum value is redundant because it's + // not in the allowed type set. + continue + } + a = append(a, s.constValue(x)) + types |= x.Kind() + } + s.knownTypes &= types + s.allowedTypes &= types + if len(a) > 0 { + s.all.add(n, ast.NewBinExpr(token.OR, a...)) + } +} + +func constraintExamples(key string, n cue.Value, s *state) { + if n.Kind() != cue.ListKind { + s.errf(n, `value of "examples" must be an array, found %v`, n.Kind()) + } +} + +func constraintNullable(key string, n cue.Value, s *state) { + null := ast.NewNull() + setPos(null, n) + s.nullable = null +} + +func constraintRef(key string, n cue.Value, s *state) { + u := s.resolveURI(n) + if u == nil { + return + } + schemaRoot := s.schemaRoot() + if u.Fragment == "" && schemaRoot.isRoot && sameSchemaRoot(u, schemaRoot.id) { + // It's a reference to the root of the schema being + // generated. This never maps to something different. + s.all.add(n, s.refExpr(n, "", cue.Path{})) + return + } + importPath, path, err := cueLocationForRef(s, n, u, schemaRoot) + if err != nil { + s.errf(n, "%v", err) + return + } + if e := s.refExpr(n, importPath, path); e != nil { + s.all.add(n, e) + } +} + +func cueLocationForRef(s *state, n cue.Value, u *url.URL, schemaRoot *state) (importPath string, path cue.Path, err error) { + if ds, ok := s.defs[u.String()]; ok { + // We already know about the schema, so use the information that's stored for it. + return ds.importPath, ds.path, nil + } + loc := SchemaLoc{ + ID: u, + } + var base cue.Value + isAnchor := u.Fragment != "" && !strings.HasPrefix(u.Fragment, "/") + if !isAnchor { + // It's a JSON pointer reference. + if sameSchemaRoot(u, s.rootID) { + base = s.root + } else if sameSchemaRoot(u, schemaRoot.id) { + // it's within the current schema. + base = schemaRoot.pos + } + if base.Exists() { + target, err := lookupJSONPointer(schemaRoot.pos, u.Fragment) + if err != nil { + if errors.Is(err, errRefNotFound) { + return "", cue.Path{}, fmt.Errorf("reference to non-existent schema") + } + return "", cue.Path{}, fmt.Errorf("invalid JSON Pointer: %v", err) + } + if ds := s.defForValue.get(target); ds != nil { + // There's a definition in place for the value, which gives + // us our answer. + return ds.importPath, ds.path, nil + } + s.ensureDefinition(target) + loc.IsLocal = true + loc.Path = relPath(target, s.root) + } + } + importPath, path, err = s.cfg.MapRef(loc) + if err != nil { + return "", cue.Path{}, fmt.Errorf("cannot determine CUE location for JSON Schema location %v: %v", loc, err) + } + // TODO we'd quite like to avoid invoking MapRef many times + // for the same reference, but in general we don't necessily know + // the canonical URI of the schema until we've done at least one pass. + // There are potentially ways to do it, but leave it for now in favor + // of simplicity. + return importPath, path, nil +} + +func constraintTitle(key string, n cue.Value, s *state) { + s.title, _ = s.strValue(n) +} + +func constraintType(key string, n cue.Value, s *state) { + var types cue.Kind + set := func(n cue.Value) { + str, ok := s.strValue(n) + if !ok { + s.errf(n, "type value should be a string") + } + switch str { + case "null": + types |= cue.NullKind + s.setTypeUsed(n, nullType) + // TODO: handle OpenAPI restrictions. + case "boolean": + types |= cue.BoolKind + s.setTypeUsed(n, boolType) + case "string": + types |= cue.StringKind + s.setTypeUsed(n, stringType) + case "number": + types |= cue.NumberKind + s.setTypeUsed(n, numType) + case "integer": + types |= cue.IntKind + s.setTypeUsed(n, numType) + s.add(n, numType, ast.NewIdent("int")) + case "array": + types |= cue.ListKind + s.setTypeUsed(n, arrayType) + case "object": + types |= cue.StructKind + s.setTypeUsed(n, objectType) + + default: + s.errf(n, "unknown type %q", n) + } + } + + switch n.Kind() { + case cue.StringKind: + set(n) + case cue.ListKind: + for i, _ := n.List(); i.Next(); { + set(i.Value()) + } + default: + s.errf(n, `value of "type" must be a string or list of strings`) + } + + s.allowedTypes &= types +} diff --git a/vendor/cuelang.org/go/encoding/jsonschema/constraints_meta.go b/vendor/cuelang.org/go/encoding/jsonschema/constraints_meta.go new file mode 100644 index 0000000000..fdc7d4ff39 --- /dev/null +++ b/vendor/cuelang.org/go/encoding/jsonschema/constraints_meta.go @@ -0,0 +1,76 @@ +// Copyright 2019 CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package jsonschema + +import ( + "cuelang.org/go/cue" +) + +// Meta constraints + +func constraintID(key string, n cue.Value, s *state) { + // URL: https://domain.com/schemas/foo.json + // anchors: #identifier + // + // TODO: mark anchors + + // Resolution is relative to parent $id + // https://tools.ietf.org/html/draft-handrews-json-schema-02#section-8.2.2 + u := s.resolveURI(n) + if u == nil { + return + } + + if u.Fragment != "" { + // TODO do not use StrictFeatures for this. The specification is clear: + // before 2019-09, IDs could contain plain-name fragments; + // (see https://json-schema.org/draft-07/draft-handrews-json-schema-01#rfc.section.5) + // afterwards, $anchor was reserved for that purpose. + if s.cfg.StrictFeatures { + s.errf(n, "$id URI may not contain a fragment") + } + return + } + s.id = u +} + +// constraintSchema implements $schema, which +// identifies this as a JSON schema and specifies its version. +func constraintSchema(key string, n cue.Value, s *state) { + if !s.isRoot && !vfrom(VersionDraft2019_09).contains(s.schemaVersion) { + // Before 2019-09, the $schema keyword was not allowed + // to appear anywhere but the root. + s.errf(n, "$schema can only appear at the root in JSON Schema version %v", s.schemaVersion) + return + } + str, ok := s.strValue(n) + if !ok { + // If there's no $schema value, use the default. + return + } + sv, err := ParseVersion(str) + if err != nil { + s.errf(n, "invalid $schema URL %q: %v", str, err) + return + } + s.schemaVersionPresent = true + s.schemaVersion = sv +} + +func constraintTODO(key string, n cue.Value, s *state) { + if s.cfg.StrictFeatures { + s.errf(n, `keyword %q not yet implemented`, key) + } +} diff --git a/vendor/cuelang.org/go/encoding/jsonschema/constraints_number.go b/vendor/cuelang.org/go/encoding/jsonschema/constraints_number.go new file mode 100644 index 0000000000..6c84dddfa9 --- /dev/null +++ b/vendor/cuelang.org/go/encoding/jsonschema/constraints_number.go @@ -0,0 +1,67 @@ +// Copyright 2019 CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package jsonschema + +import ( + "math/big" + + "cuelang.org/go/cue" + "cuelang.org/go/cue/ast" + "cuelang.org/go/cue/token" +) + +// Numeric constraints + +func constraintExclusiveMaximum(key string, n cue.Value, s *state) { + if n.Kind() == cue.BoolKind { + s.exclusiveMax = true + return + } + s.add(n, numType, &ast.UnaryExpr{Op: token.LSS, X: s.number(n)}) +} +func constraintExclusiveMinimum(key string, n cue.Value, s *state) { + if n.Kind() == cue.BoolKind { + s.exclusiveMin = true + return + } + s.add(n, numType, &ast.UnaryExpr{Op: token.GTR, X: s.number(n)}) +} + +func constraintMinimum(key string, n cue.Value, s *state) { + op := token.GEQ + if s.exclusiveMin { + op = token.GTR + } + s.add(n, numType, &ast.UnaryExpr{Op: op, X: s.number(n)}) +} + +func constraintMaximum(key string, n cue.Value, s *state) { + op := token.LEQ + if s.exclusiveMax { + op = token.LSS + } + s.add(n, numType, &ast.UnaryExpr{Op: op, X: s.number(n)}) +} + +func constraintMultipleOf(key string, n cue.Value, s *state) { + multiple := s.number(n) + var x big.Int + _, _ = n.MantExp(&x) + if x.Cmp(big.NewInt(0)) != 1 { + s.errf(n, `"multipleOf" value must be > 0; found %s`, n) + } + math := s.addImport(n, "math") + s.add(n, numType, ast.NewCall(ast.NewSel(math, "MultipleOf"), multiple)) +} diff --git a/vendor/cuelang.org/go/encoding/jsonschema/constraints_object.go b/vendor/cuelang.org/go/encoding/jsonschema/constraints_object.go new file mode 100644 index 0000000000..c5a692129d --- /dev/null +++ b/vendor/cuelang.org/go/encoding/jsonschema/constraints_object.go @@ -0,0 +1,192 @@ +// Copyright 2019 CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package jsonschema + +import ( + "cuelang.org/go/cue" + "cuelang.org/go/cue/ast" + "cuelang.org/go/cue/token" + "cuelang.org/go/internal" +) + +// Object constraints + +func constraintAdditionalProperties(key string, n cue.Value, s *state) { + switch n.Kind() { + case cue.BoolKind: + s.closeStruct = !s.boolValue(n) + _ = s.object(n) + + case cue.StructKind: + s.closeStruct = true + obj := s.object(n) + if len(obj.Elts) == 0 { + obj.Elts = append(obj.Elts, &ast.Field{ + Label: ast.NewList(ast.NewIdent("string")), + Value: s.schema(n), + }) + return + } + // [!~(properties|patternProperties)]: schema + existing := append(s.patterns, excludeFields(obj.Elts)...) + f := internal.EmbedStruct(ast.NewStruct(&ast.Field{ + Label: ast.NewList(ast.NewBinExpr(token.AND, existing...)), + Value: s.schema(n), + })) + obj.Elts = append(obj.Elts, f) + + default: + s.errf(n, `value of "additionalProperties" must be an object or boolean`) + } +} + +func constraintDependencies(key string, n cue.Value, s *state) { + // Schema and property dependencies. + // TODO: the easiest implementation is with comprehensions. + // The nicer implementation is with disjunctions. This has to be done + // at the very end, replacing properties. + /* + *{ property?: _|_ } | { + property: _ + schema + } + */ +} + +func constraintMaxProperties(key string, n cue.Value, s *state) { + pkg := s.addImport(n, "struct") + x := ast.NewCall(ast.NewSel(pkg, "MaxFields"), s.uint(n)) + s.add(n, objectType, x) +} + +func constraintMinProperties(key string, n cue.Value, s *state) { + pkg := s.addImport(n, "struct") + x := ast.NewCall(ast.NewSel(pkg, "MinFields"), s.uint(n)) + s.add(n, objectType, x) +} + +func constraintPatternProperties(key string, n cue.Value, s *state) { + if n.Kind() != cue.StructKind { + s.errf(n, `value of "patternProperties" must be an object, found %v`, n.Kind()) + } + obj := s.object(n) + existing := excludeFields(s.obj.Elts) + s.processMap(n, func(key string, n cue.Value) { + if !s.checkRegexp(n, key) { + return + } + + // Record the pattern for potential use by + // additionalProperties because patternProperties are + // considered before additionalProperties. + s.patterns = append(s.patterns, + &ast.UnaryExpr{Op: token.NMAT, X: ast.NewString(key)}) + + // We'll make a pattern constraint of the form: + // [pattern & !~(properties)]: schema + f := internal.EmbedStruct(ast.NewStruct(&ast.Field{ + Label: ast.NewList(ast.NewBinExpr( + token.AND, + append([]ast.Expr{&ast.UnaryExpr{Op: token.MAT, X: ast.NewString(key)}}, existing...)..., + )), + Value: s.schema(n), + })) + ast.SetRelPos(f, token.NewSection) + obj.Elts = append(obj.Elts, f) + }) +} + +func constraintProperties(key string, n cue.Value, s *state) { + obj := s.object(n) + + if n.Kind() != cue.StructKind { + s.errf(n, `"properties" expected an object, found %v`, n.Kind()) + } + + s.processMap(n, func(key string, n cue.Value) { + // property?: value + name := ast.NewString(key) + expr, state := s.schemaState(n, allTypes) + f := &ast.Field{Label: name, Value: expr} + if doc := state.comment(); doc != nil { + ast.SetComments(f, []*ast.CommentGroup{doc}) + } + f.Optional = token.Blank.Pos() + if len(obj.Elts) > 0 && len(f.Comments()) > 0 { + // TODO: change formatter such that either a NewSection on the + // field or doc comment will cause a new section. + ast.SetRelPos(f.Comments()[0], token.NewSection) + } + if state.deprecated { + switch expr.(type) { + case *ast.StructLit: + obj.Elts = append(obj.Elts, addTag(name, "deprecated", "")) + default: + f.Attrs = append(f.Attrs, internal.NewAttr("deprecated", "")) + } + } + obj.Elts = append(obj.Elts, f) + }) +} + +func constraintPropertyNames(key string, n cue.Value, s *state) { + // [=~pattern]: _ + if names, _ := s.schemaState(n, cue.StringKind); !isTop(names) { + x := ast.NewStruct(ast.NewList(names), top()) + s.add(n, objectType, x) + } +} + +func constraintRequired(key string, n cue.Value, s *state) { + if n.Kind() != cue.ListKind { + s.errf(n, `value of "required" must be list of strings, found %v`, n.Kind()) + return + } + + obj := s.object(n) + + // Create field map + fields := map[string]*ast.Field{} + for _, d := range obj.Elts { + f, ok := d.(*ast.Field) + if !ok { + continue // Could be embedding? See cirrus.json + } + str, _, err := ast.LabelName(f.Label) + if err == nil { + fields[str] = f + } + } + + for _, n := range s.listItems("required", n, true) { + str, ok := s.strValue(n) + f := fields[str] + if f == nil && ok { + f := &ast.Field{ + Label: ast.NewString(str), + Value: top(), + Constraint: token.NOT, + } + fields[str] = f + obj.Elts = append(obj.Elts, f) + continue + } + if f.Optional == token.NoPos { + s.errf(n, "duplicate required field %q", str) + } + f.Constraint = token.NOT + f.Optional = token.NoPos + } +} diff --git a/vendor/cuelang.org/go/encoding/jsonschema/constraints_string.go b/vendor/cuelang.org/go/encoding/jsonschema/constraints_string.go new file mode 100644 index 0000000000..2aef032a0a --- /dev/null +++ b/vendor/cuelang.org/go/encoding/jsonschema/constraints_string.go @@ -0,0 +1,55 @@ +// Copyright 2019 CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package jsonschema + +import ( + "cuelang.org/go/cue" + "cuelang.org/go/cue/ast" + "cuelang.org/go/cue/token" +) + +// String constraints + +func constraintContentEncoding(key string, n cue.Value, s *state) { + // TODO: only mark as used if it generates something. + // 7bit, 8bit, binary, quoted-printable and base64. + // RFC 2054, part 6.1. + // https://tools.ietf.org/html/rfc2045 + // TODO: at least handle bytes. +} + +func constraintContentMediaType(key string, n cue.Value, s *state) { + // TODO: only mark as used if it generates something. +} + +func constraintMaxLength(key string, n cue.Value, s *state) { + max := s.uint(n) + strings := s.addImport(n, "strings") + s.add(n, stringType, ast.NewCall(ast.NewSel(strings, "MaxRunes"), max)) +} + +func constraintMinLength(key string, n cue.Value, s *state) { + min := s.uint(n) + strings := s.addImport(n, "strings") + s.add(n, stringType, ast.NewCall(ast.NewSel(strings, "MinRunes"), min)) +} + +func constraintPattern(key string, n cue.Value, s *state) { + str, ok := s.regexpValue(n) + if !ok { + return + } + s.add(n, stringType, &ast.UnaryExpr{Op: token.MAT, X: str}) +} diff --git a/vendor/cuelang.org/go/encoding/jsonschema/decode.go b/vendor/cuelang.org/go/encoding/jsonschema/decode.go index 0e844247f6..1a8a0eb3e9 100644 --- a/vendor/cuelang.org/go/encoding/jsonschema/decode.go +++ b/vendor/cuelang.org/go/encoding/jsonschema/decode.go @@ -20,8 +20,12 @@ package jsonschema import ( "fmt" + "math" "net/url" + "regexp" + "regexp/syntax" "sort" + "strconv" "strings" "cuelang.org/go/cue" @@ -30,19 +34,74 @@ import ( "cuelang.org/go/cue/errors" "cuelang.org/go/cue/token" "cuelang.org/go/internal" + "cuelang.org/go/mod/module" +) + +const ( + // DefaultRootID is used as the absolute base URI for a schema + // when no value is provided in [Config.ID]. + DefaultRootID = "https://" + DefaultRootIDHost + DefaultRootIDHost = "cue.jsonschema.invalid" ) // rootDefs defines the top-level name of the map of definitions that do not // have a valid identifier name. // -// TODO: find something more principled, like allowing #."a-b" or `#a-b`. +// TODO: find something more principled, like allowing #("a-b"). const rootDefs = "#" // A decoder converts JSON schema to CUE. type decoder struct { - cfg *Config - errs errors.Error - numID int // for creating unique numbers: increment on each use + cfg *Config + errs errors.Error + mapURLErrors map[string]bool + + root cue.Value + rootID *url.URL + + // defForValue holds an entry for internal values + // that are known to map to a defined schema. + // A nil entry is stored for nodes that have been + // referred to but we haven't yet seen when walking + // the schemas. + defForValue *valueMap[*definedSchema] + + // danglingRefs records the number of nil entries in defForValue, + // representing the number of references into the internal + // structure that have not yet been resolved. + danglingRefs int + + // defs holds the set of named schemas, indexed by URI (both + // canonical, and root-relative if known), including external + // schemas that aren't known. + defs map[string]*definedSchema + + // builder is used to build the final syntax tree as it becomes known. + builder structBuilder + + // needAnotherPass is set to true when we know that + // we need another pass through the schema extraction + // process. This can happen because `MapRef` might choose + // a different location depending on whether a reference is local + // or external. We don't know that until we've traversed the + // entire schema and the `$ref` might be seen before the + // schema it's referring to. Still more passes might be required + // if a $ref is found to be referring to a node that would not normally + // be considered part of the schema data. + needAnotherPass bool +} + +// definedSchema records information for a schema or subschema. +type definedSchema struct { + // importPath is empty for internal schemas. + importPath string + + // path holds the location of the schema relative to importPath. + path cue.Path + + // schema holds the actual syntax for the schema. This + // is nil if the entry was created by a reference only. + schema ast.Expr } // addImport registers @@ -60,117 +119,131 @@ func (d *decoder) addImport(n cue.Value, pkg string) *ast.Ident { } func (d *decoder) decode(v cue.Value) *ast.File { - f := &ast.File{} - - if pkgName := d.cfg.PkgName; pkgName != "" { - pkg := &ast.Package{Name: ast.NewIdent(pkgName)} - f.Decls = append(f.Decls, pkg) - } - - var a []ast.Decl - - if d.cfg.Root == "" { - a = append(a, d.schema(nil, v)...) - } else { - ref := d.parseRef(token.NoPos, d.cfg.Root) - if ref == nil { - return f - } - i, err := v.Lookup(ref...).Fields() + var defsRoot cue.Value + if d.cfg.Root != "" { + defsPath, err := parseRootRef(d.cfg.Root) if err != nil { - d.errs = errors.Append(d.errs, errors.Promote(err, "")) + d.errf(cue.Value{}, "invalid Config.Root value %q: %v", d.cfg.Root, err) return nil } - for i.Next() { - ref := append(ref, i.Label()) - lab := d.mapRef(i.Value().Pos(), "", ref) - if len(lab) == 0 { - return nil - } - decls := d.schema(lab, i.Value()) - a = append(a, decls...) + defsRoot = v.LookupPath(defsPath) + if !defsRoot.Exists() && d.cfg.AllowNonExistentRoot { + defsRoot = v.Context().CompileString("{}") + } else if defsRoot.Kind() != cue.StructKind { + d.errf(defsRoot, "value at path %v must be struct containing definitions but is actually %v", d.cfg.Root, defsRoot) + return nil } } - f.Decls = append(f.Decls, a...) - - _ = astutil.Sanitize(f) - - return f -} - -func (d *decoder) schema(ref []ast.Label, v cue.Value) (a []ast.Decl) { - root := state{decoder: d} - - var name ast.Label - inner := len(ref) - 1 - - if inner >= 0 { - name = ref[inner] - root.isSchema = true - } - - expr, state := root.schemaState(v, allTypes, nil, false) - - tags := []string{} - if state.jsonschema != "" { - tags = append(tags, fmt.Sprintf("schema=%q", state.jsonschema)) - } - - if name == nil { - if len(tags) > 0 { - body := strings.Join(tags, ",") - a = append(a, &ast.Attribute{ - Text: fmt.Sprintf("@jsonschema(%s)", body)}) + var rootInfo schemaInfo + // extraSchemas records any nodes that are referred to + // but not part of the regular schema traversal. + var extraSchemas []cue.Value + // basePass records the last time that any new schemas were + // added for inspection. This can be set whenever new schemas + // not part of the regular traversal are found. + basePass := 0 + + for pass := 0; ; pass++ { + if pass > 10 { + // Should never happen: the most we should ever see in practice + // should be 2, but some pathological cases could end up with more. + d.errf(v, "internal error: too many passes without resolution") + return nil + } + root := &state{ + decoder: d, + schemaInfo: schemaInfo{ + schemaVersion: d.cfg.DefaultVersion, + id: d.rootID, + }, + isRoot: true, + pos: v, } - if state.deprecated { - a = append(a, &ast.Attribute{Text: "@deprecated()"}) + if defsRoot.Exists() { + // When d.cfg.Root is non-empty, it points to a struct + // containing a field for each definition. + constraintAddDefinitions("schemas", defsRoot, root) + } else { + expr, state := root.schemaState(v, allTypes) + if state.allowedTypes == 0 { + root.errf(v, "constraints are not possible to satisfy") + return nil + } + if !d.builder.put(cue.Path{}, expr, state.comment()) { + root.errf(v, "duplicate definition at root") // TODO better error message + return nil + } + rootInfo = state } - } else { - if len(tags) > 0 { - a = append(a, addTag(name, "jsonschema", strings.Join(tags, ","))) + if d.danglingRefs > 0 && pass == basePass+1 { + // There are still dangling references but we've been through the + // schema twice, so we know that there's a reference + // to a non-schema node. Technically this is not necessarily valid, + // but we do see this in the wild. This should be rare, + // so efficiency (re-parsing paths) shouldn't be a great issue. + for path, def := range d.defForValue.byPath { + if def != nil { + continue + } + n := d.root.LookupPath(cue.ParsePath(path)) + if !n.Exists() { + panic("failed to find entry for dangling reference") + } + extraSchemas = append(extraSchemas, n) + basePass = pass + } + } + for _, n := range extraSchemas { + // As the ID namespace isn't well-defined we treat all such + // schemas as if they were directly under the root. + // See https://json-schema.org/draft/2020-12/json-schema-core#section-9.4.2 + root.schema(n) + } + if !d.needAnotherPass && d.danglingRefs == 0 { + break } - if state.deprecated { - a = append(a, addTag(name, "deprecated", "")) + d.builder = structBuilder{} + for _, def := range d.defs { + def.schema = nil } + d.needAnotherPass = false } - - if name != nil { - f := &ast.Field{ - Label: name, - Value: expr, + if d.cfg.DefineSchema != nil { + // Let the caller know about any internal schemas that + // have been mapped to an external location. + for _, def := range d.defs { + if def.schema != nil && def.importPath != "" { + d.cfg.DefineSchema(def.importPath, def.path, def.schema) + } } - - a = append(a, f) - } else if st, ok := expr.(*ast.StructLit); ok { - a = append(a, st.Elts...) - } else { - a = append(a, &ast.EmbedDecl{Expr: expr}) } - - state.doc(a[0]) - - for i := inner - 1; i >= 0; i-- { - a = []ast.Decl{&ast.Field{ - Label: ref[i], - Value: &ast.StructLit{Elts: a}, - }} - expr = ast.NewStruct(ref[i], expr) + f, err := d.builder.syntax() + if err != nil { + d.errf(v, "cannot build final syntax: %v", err) + return nil } - - if root.hasSelfReference { - return []ast.Decl{ - &ast.EmbedDecl{Expr: ast.NewIdent(topSchema)}, - &ast.Field{ - Label: ast.NewIdent(topSchema), - Value: &ast.StructLit{Elts: a}, - }, - } + var preamble []ast.Decl + if d.cfg.PkgName != "" { + preamble = append(preamble, &ast.Package{Name: ast.NewIdent(d.cfg.PkgName)}) } - - return a + if rootInfo.schemaVersionPresent { + // TODO use cue/literal.String + // TODO is this actually useful information: why is knowing the schema + // version of the input useful? + preamble = append(preamble, &ast.Attribute{ + Text: fmt.Sprintf("@jsonschema(schema=%q)", rootInfo.schemaVersion), + }) + } + if rootInfo.deprecated { + preamble = append(preamble, &ast.Attribute{Text: "@deprecated()"}) + } + if len(preamble) > 0 { + f.Decls = append(preamble, f.Decls...) + } + return f } func (d *decoder) errf(n cue.Value, format string, args ...interface{}) ast.Expr { @@ -190,16 +263,16 @@ func (d *decoder) number(n cue.Value) ast.Expr { return n.Syntax(cue.Final()).(ast.Expr) } -func (d *decoder) uint(n cue.Value) ast.Expr { - _, err := n.Uint64() +func (d *decoder) uint(nv cue.Value) ast.Expr { + n, err := uint64Value(nv) if err != nil { - d.errf(n, "invalid uint") + d.errf(nv, "invalid uint") + } + return &ast.BasicLit{ + ValuePos: nv.Pos(), + Kind: token.FLOAT, + Value: strconv.FormatUint(n, 10), } - return n.Syntax(cue.Final()).(ast.Expr) -} - -func (d *decoder) bool(n cue.Value) ast.Expr { - return n.Syntax(cue.Final()).(ast.Expr) } func (d *decoder) boolValue(n cue.Value) bool { @@ -223,6 +296,60 @@ func (d *decoder) strValue(n cue.Value) (s string, ok bool) { return s, true } +func (d *decoder) regexpValue(n cue.Value) (ast.Expr, bool) { + s, ok := d.strValue(n) + if !ok { + return nil, false + } + if !d.checkRegexp(n, s) { + return nil, false + } + return d.string(n), true +} + +func (d *decoder) checkRegexp(n cue.Value, s string) bool { + _, err := syntax.Parse(s, syntax.Perl) + if err == nil { + return true + } + var regErr *syntax.Error + if errors.As(err, ®Err) { + switch regErr.Code { + case syntax.ErrInvalidPerlOp: + // It's Perl syntax that we'll never support because the CUE evaluation + // engine uses Go's regexp implementation and because the missing + // features are usually not there for good reason (e.g. exponential + // runtime). In other words, this is a missing feature but not an invalid + // regular expression as such. + if d.cfg.StrictFeatures { + // TODO: could fall back to https://github.com/dlclark/regexp2 instead + d.errf(n, "unsupported Perl regexp syntax in %q: %v", s, err) + } + return false + case syntax.ErrInvalidCharRange: + // There are many more character class ranges than Go supports currently + // (see https://go.dev/issue/14509) so treat an unknown character class + // range as a feature error rather than a bad regexp. + // TODO translate names to Go-supported class names when possible. + if d.cfg.StrictFeatures { + d.errf(n, "unsupported regexp character class in %q: %v", s, err) + } + return false + } + } + d.errf(n, "invalid regexp %q: %v", s, err) + return false +} + +// ensureDefinition ensures that node n will +// be a defined schema. +func (d *decoder) ensureDefinition(n cue.Value) { + if _, ok := d.defForValue.lookup(n); !ok { + d.defForValue.set(n, nil) + d.danglingRefs++ + } +} + // const draftCutoff = 5 type coreType int @@ -241,7 +368,7 @@ const ( var coreToCUE = []cue.Kind{ nullType: cue.NullKind, boolType: cue.BoolKind, - numType: cue.FloatKind, + numType: cue.NumberKind, // Note: both int and float. stringType: cue.StringKind, arrayType: cue.ListKind, objectType: cue.StructKind, @@ -254,8 +381,12 @@ func kindToAST(k cue.Kind) ast.Expr { return ast.NewNull() case cue.BoolKind: return ast.NewIdent("bool") - case cue.FloatKind: + case cue.NumberKind: return ast.NewIdent("number") + case cue.IntKind: + return ast.NewIdent("int") + case cue.FloatKind: + return ast.NewIdent("float") case cue.StringKind: return ast.NewIdent("string") case cue.ListKind: @@ -263,7 +394,7 @@ func kindToAST(k cue.Kind) ast.Expr { case cue.StructKind: return ast.NewStruct(&ast.Ellipsis{}) } - return nil + panic(fmt.Errorf("unexpected kind %v", k)) } var coreTypeName = []string{ @@ -289,7 +420,7 @@ func (c *constraintInfo) setTypeUsed(n cue.Value, t coreType) { } func (c *constraintInfo) add(n cue.Value, x ast.Expr) { - if !isAny(x) { + if !isTop(x) { setPos(x, n) ast.SetRelPos(x, token.NoRelPos) c.constraints = append(c.constraints, x) @@ -301,21 +432,17 @@ func (s *state) add(n cue.Value, t coreType, x ast.Expr) { } func (s *state) setTypeUsed(n cue.Value, t coreType) { + if int(t) >= len(s.types) { + panic(fmt.Errorf("type out of range %v/%v", int(t), len(s.types))) + } s.types[t].setTypeUsed(n, t) } type state struct { *decoder + schemaInfo - isSchema bool // for omitting ellipsis in an ast.File - - up *state - parent *state - - path []string - - // idRef is used to refer to this schema in case it defines an $id. - idRef []label + up *state pos cue.Value @@ -324,52 +451,107 @@ type state struct { all constraintInfo // values and oneOf etc. nullable *ast.BasicLit // nullable - usedTypes cue.Kind - allowedTypes cue.Kind - - default_ ast.Expr - examples []ast.Expr - title string - description string - deprecated bool exclusiveMin bool // For OpenAPI and legacy support. exclusiveMax bool // For OpenAPI and legacy support. - jsonschema string - id *url.URL // base URI for $ref + + // Keep track of whether a $ref keyword is present, + // because pre-2019-09 schemas ignore sibling keywords + // to $ref. + hasRefKeyword bool + + // isRoot holds whether this state is at the root + // of the schema. + isRoot bool + + minContains *uint64 + maxContains *uint64 + + ifConstraint cue.Value + thenConstraint cue.Value + elseConstraint cue.Value definitions []ast.Decl // Used for inserting definitions, properties, etc. - hasSelfReference bool - obj *ast.StructLit - // Complete at finalize. - fieldRefs map[label]refs + obj *ast.StructLit + objN cue.Value // used for adding obj to constraints closeStruct bool patterns []ast.Expr list *ast.ListLit + + // listItemsIsArray keeps track of whether the + // value of the "items" keyword is an array. + // Without this, we can't distinguish between + // + // "items": true + // + // and + // + // "items": [] + listItemsIsArray bool } -type label struct { - name string - isDef bool +// schemaInfo holds information about a schema +// after it has been created. +type schemaInfo struct { + // allowedTypes holds the set of types that + // this node is allowed to be. + allowedTypes cue.Kind + + // knownTypes holds the set of types that this node + // is known to be one of by virtue of the constraints inside + // all. This is used to avoid adding redundant elements + // to the disjunction created by [state.finalize]. + knownTypes cue.Kind + + title string + description string + + // id holds the absolute URI of the schema if has a $id field . + // It's the base URI for $ref or nested $id fields. + id *url.URL + deprecated bool + + schemaVersion Version + schemaVersionPresent bool + + hasConstraints bool } -type refs struct { - field *ast.Field - ident string - refs []*ast.Ident +func (s *state) idTag() *ast.Attribute { + return &ast.Attribute{Text: fmt.Sprintf("@jsonschema(id=%q)", s.id)} } func (s *state) object(n cue.Value) *ast.StructLit { if s.obj == nil { s.obj = &ast.StructLit{} - s.add(n, objectType, s.obj) + s.objN = n + + if s.id != nil { + s.obj.Elts = append(s.obj.Elts, s.idTag()) + } } return s.obj } +func (s *state) finalizeObject() { + if s.obj == nil { + return + } + + var e ast.Expr + if s.closeStruct { + e = ast.NewCall(ast.NewIdent("close"), s.obj) + } else { + s.obj.Elts = append(s.obj.Elts, &ast.Ellipsis{}) + e = s.obj + } + + s.add(s.objN, objectType, e) +} + func (s *state) hasConstraints() bool { if len(s.all.constraints) > 0 { return true @@ -382,23 +564,31 @@ func (s *state) hasConstraints() bool { return len(s.patterns) > 0 || s.title != "" || s.description != "" || - s.obj != nil + s.obj != nil || + s.id != nil } -const allTypes = cue.NullKind | cue.BoolKind | cue.NumberKind | cue.IntKind | - cue.StringKind | cue.ListKind | cue.StructKind +const allTypes = cue.BoolKind | + cue.ListKind | + cue.NullKind | + cue.NumberKind | + cue.IntKind | + cue.StringKind | + cue.StructKind -// finalize constructs a CUE type from the collected constraints. +// finalize constructs CUE syntax from the collected constraints. func (s *state) finalize() (e ast.Expr) { + if s.allowedTypes == 0 { + // Nothing is possible. This isn't a necessarily a problem, as + // we might be inside an allOf or oneOf with other valid constraints. + return bottom() + } + + s.finalizeObject() + conjuncts := []ast.Expr{} disjuncts := []ast.Expr{} - types := s.allowedTypes &^ s.usedTypes - if types == allTypes { - disjuncts = append(disjuncts, ast.NewIdent("_")) - types = 0 - } - // Sort literal structs and list last for nicer formatting. sort.SliceStable(s.types[arrayType].constraints, func(i, j int) bool { _, ok := s.types[arrayType].constraints[i].(*ast.ListLit) @@ -409,59 +599,76 @@ func (s *state) finalize() (e ast.Expr) { return !ok }) - for i, t := range s.types { - k := coreToCUE[i] - isAllowed := s.allowedTypes&k != 0 - if len(t.constraints) > 0 { - if t.typ == nil && !isAllowed { - for _, c := range t.constraints { - s.addErr(errors.Newf(c.Pos(), - "constraint not allowed because type %s is excluded", - coreTypeName[i], - )) + type excludeInfo struct { + pos token.Pos + typIndex int + } + var excluded []excludeInfo + + needsTypeDisjunction := s.allowedTypes != s.knownTypes + if !needsTypeDisjunction { + for i, t := range s.types { + k := coreToCUE[i] + if len(t.constraints) > 0 && s.allowedTypes&k != 0 { + // We need to include at least one type-specific + // constraint in the disjunction. + needsTypeDisjunction = true + break + } + } + } + + if needsTypeDisjunction { + npossible := 0 + nexcluded := 0 + for i, t := range s.types { + k := coreToCUE[i] + allowed := s.allowedTypes&k != 0 + switch { + case len(t.constraints) > 0: + npossible++ + if !allowed { + nexcluded++ + for _, c := range t.constraints { + excluded = append(excluded, excludeInfo{c.Pos(), i}) + } + continue + } + x := ast.NewBinExpr(token.AND, t.constraints...) + disjuncts = append(disjuncts, x) + case allowed: + npossible++ + if s.knownTypes&k != 0 { + disjuncts = append(disjuncts, kindToAST(k)) } - continue } - x := ast.NewBinExpr(token.AND, t.constraints...) - disjuncts = append(disjuncts, x) - } else if s.usedTypes&k != 0 { - continue - } else if t.typ != nil { - if !isAllowed { - s.addErr(errors.Newf(t.typ.Pos(), + } + if nexcluded == npossible { + // All possibilities have been excluded: this is an impossible + // schema. + for _, e := range excluded { + s.addErr(errors.Newf(e.pos, "constraint not allowed because type %s is excluded", - coreTypeName[i], + coreTypeName[e.typIndex], )) - continue - } - disjuncts = append(disjuncts, t.typ) - } else if types&k != 0 { - x := kindToAST(k) - if x != nil { - disjuncts = append(disjuncts, x) } } } - conjuncts = append(conjuncts, s.all.constraints...) - obj := s.obj - if obj == nil { - obj, _ = s.types[objectType].typ.(*ast.StructLit) - } - if obj != nil { - // TODO: may need to explicitly close. - if !s.closeStruct { - obj.Elts = append(obj.Elts, &ast.Ellipsis{}) - } - } - if len(disjuncts) > 0 { conjuncts = append(conjuncts, ast.NewBinExpr(token.OR, disjuncts...)) } if len(conjuncts) == 0 { - e = &ast.BottomLit{} + // There are no conjuncts, which can only happen when there + // are no disjuncts, which can only happen when the entire + // set of disjuncts is redundant with respect to the types + // already implied by s.all. As we've already checked that + // s.allowedTypes is non-zero (so we know that + // it's not bottom) and we need _some_ expression + // to be part of the subequent syntax, we use top. + e = top() } else { e = ast.NewBinExpr(token.AND, conjuncts...) } @@ -471,19 +678,6 @@ func (s *state) finalize() (e ast.Expr) { a = []ast.Expr{s.nullable, e} } -outer: - switch { - case s.default_ != nil: - // check conditions where default can be skipped. - switch x := s.default_.(type) { - case *ast.ListLit: - if s.usedTypes == cue.ListKind && len(x.Elts) == 0 { - break outer - } - } - a = append(a, &ast.UnaryExpr{Op: token.MUL, X: s.default_}) - } - e = ast.NewBinExpr(token.OR, a...) if len(s.definitions) > 0 { @@ -497,17 +691,23 @@ outer: } } - s.linkReferences() + // If an "$id" exists and has not been included in any object constraints + if s.id != nil && s.obj == nil { + if st, ok := e.(*ast.StructLit); ok { + st.Elts = append([]ast.Decl{s.idTag()}, st.Elts...) + } else { + e = &ast.StructLit{Elts: []ast.Decl{s.idTag(), &ast.EmbedDecl{Expr: e}}} + } + } + // Now that we've expressed the schema as actual syntax, + // all the allowed types are actually explicit and will not + // need to be mentioned again. + s.knownTypes = s.allowedTypes return e } -func isAny(s ast.Expr) bool { - i, ok := s.(*ast.Ident) - return ok && i.Name == "_" -} - -func (s *state) comment() *ast.CommentGroup { +func (s schemaInfo) comment() *ast.CommentGroup { // Create documentation. doc := strings.TrimSpace(s.title) if s.description != "" { @@ -524,64 +724,244 @@ func (s *state) comment() *ast.CommentGroup { return internal.NewComment(true, doc) } -func (s *state) doc(n ast.Node) { - doc := s.comment() - if doc != nil { - ast.SetComments(n, []*ast.CommentGroup{doc}) - } -} - -func (s *state) schema(n cue.Value, idRef ...label) ast.Expr { - expr, _ := s.schemaState(n, allTypes, idRef, false) - // TODO: report unused doc. +func (s *state) schema(n cue.Value) ast.Expr { + expr, _ := s.schemaState(n, allTypes) return expr } -// schemaState is a low-level API for schema. isLogical specifies whether the -// caller is a logical operator like anyOf, allOf, oneOf, or not. -func (s *state) schemaState(n cue.Value, types cue.Kind, idRef []label, isLogical bool) (ast.Expr, *state) { - state := &state{ - up: s, - isSchema: s.isSchema, - decoder: s.decoder, - allowedTypes: types, - path: s.path, - idRef: idRef, - pos: n, +// schemaState returns a new state value derived from s. +// n holds the JSONSchema node to translate to a schema. +// types holds the set of possible types that the value can hold. +func (s0 *state) schemaState(n cue.Value, types cue.Kind) (expr ast.Expr, ingo schemaInfo) { + s := &state{ + up: s0, + schemaInfo: schemaInfo{ + schemaVersion: s0.schemaVersion, + allowedTypes: types, + knownTypes: allTypes, + }, + decoder: s0.decoder, + pos: n, + isRoot: s0.isRoot && n == s0.pos, } - if isLogical { - state.parent = s + defer func() { + // Perhaps replace the schema expression with a reference. + expr = s.maybeDefine(expr) + }() + if n.Kind() == cue.BoolKind { + if vfrom(VersionDraft6).contains(s.schemaVersion) { + // From draft6 onwards, boolean values signify a schema that always passes or fails. + // TODO if false, set s.allowedTypes and s.knownTypes to zero? + return boolSchema(s.boolValue(n)), s.schemaInfo + } + return s.errf(n, "boolean schemas not supported in %v", s.schemaVersion), s.schemaInfo } - if n.Kind() != cue.StructKind { - return s.errf(n, "schema expects mapping node, found %s", n.Kind()), state + return s.errf(n, "schema expects mapping node, found %s", n.Kind()), s.schemaInfo } // do multiple passes over the constraints to ensure they are done in order. - for pass := 0; pass < 4; pass++ { - state.processMap(n, func(key string, value cue.Value) { + for pass := 0; pass < numPhases; pass++ { + s.processMap(n, func(key string, value cue.Value) { + if pass == 0 && key == "$ref" { + // Before 2019-19, keywords alongside $ref are ignored so keep + // track of whether we've seen any non-$ref keywords so we can + // ignore those keywords. This could apply even when the schema + // is >=2019-19 because $schema could be used to change the version. + s.hasRefKeyword = true + } + if strings.HasPrefix(key, "x-") { + // A keyword starting with a leading x- is clearly + // not intended to be a valid keyword, and is explicitly + // allowed by OpenAPI. It seems reasonable that + // this is not an error even with StrictKeywords enabled. + return + } // Convert each constraint into a either a value or a functor. c := constraintMap[key] if c == nil { - if pass == 0 && s.cfg.Strict { + if pass == 0 && s.cfg.StrictKeywords { // TODO: value is not the correct position, albeit close. Fix this. - s.warnf(value.Pos(), "unsupported constraint %q", key) + s.warnf(value.Pos(), "unknown keyword %q", key) } return } - if c.phase == pass { - c.fn(value, state) + if c.phase != pass { + return + } + if !c.versions.contains(s.schemaVersion) { + if s.cfg.StrictKeywords { + s.warnf(value.Pos(), "keyword %q is not supported in JSON schema version %v", key, s.schemaVersion) + } + return } + if pass > 0 && !vfrom(VersionDraft2019_09).contains(s.schemaVersion) && s.hasRefKeyword && key != "$ref" { + // We're using a schema version that ignores keywords alongside $ref. + // + // Note that we specifically exclude pass 0 (the pass in which $schema is checked) + // from this check, because hasRefKeyword is only set in pass 0 and we + // can get into a self-contradictory situation ($schema says we should + // ignore keywords alongside $ref, but $ref says we should ignore the $schema + // keyword itself). We could make that situation an explicit error, but other + // implementations don't, and it would require an entire extra pass just to do so. + if s.cfg.StrictKeywords { + s.warnf(value.Pos(), "ignoring keyword %q alongside $ref", key) + } + return + } + c.fn(key, value, s) }) } + if s.id != nil { + // If there's an ID, it can be referred to. + s.ensureDefinition(s.pos) + } + constraintIfThenElse(s) + + schemaExpr := s.finalize() + s.schemaInfo.hasConstraints = s.hasConstraints() + return schemaExpr, s.schemaInfo +} + +// maybeDefine checks whether we might need a definition +// for n given its actual schema syntax expression. If +// it does, it creates the definition as appropriate and returns +// an expression that refers to that definition; if not, +// it just returns expr itself. +// TODO also report whether the schema has been defined at a place +// where it can be unified with something else? +func (s *state) maybeDefine(expr ast.Expr) ast.Expr { + def := s.definedSchemaForNode(s.pos) + if def == nil || len(def.path.Selectors()) == 0 { + return expr + } + def.schema = expr + if def.importPath == "" { + // It's a local definition that's not at the root. + if !s.builder.put(def.path, expr, s.comment()) { + s.errf(s.pos, "redefinition of schema CUE path %v", def.path) + return expr + } + } + return s.refExpr(s.pos, def.importPath, def.path) +} + +// definedSchemaForNode returns the definedSchema value +// for the given node in the JSON schema, or nil +// if the node does not need a definition. +func (s *state) definedSchemaForNode(n cue.Value) *definedSchema { + def, ok := s.defForValue.lookup(n) + if !ok { + return nil + } + if def != nil { + // We've either made a definition in a previous pass + // or it's a redefinition. + // TODO if it's a redefinition, error. + return def + } + // This node has been referred to but not actually defined. We'll + // need another pass to sort out the reference even though the + // reference is no longer dangling. + s.needAnotherPass = true - return state.finalize(), state + def = s.addDefinition(n) + if def == nil { + return nil + } + s.defForValue.set(n, def) + s.danglingRefs-- + return def +} + +func (s *state) addDefinition(n cue.Value) *definedSchema { + var loc SchemaLoc + schemaRoot := s.schemaRoot() + loc.ID = ref(*schemaRoot.id) + loc.ID.Fragment = cuePathToJSONPointer(relPath(n, schemaRoot.pos)) + idStr := loc.ID.String() + def, ok := s.defs[idStr] + if ok { + // We've already got a definition for this ID. + // TODO if it's been defined in the same pass, then it's a redefinition + // s.errf(n, "redefinition of schema %s at %v", idStr, n.Path()) + return def + } + loc.IsLocal = true + loc.Path = relPath(n, s.root) + importPath, path, err := s.cfg.MapRef(loc) + if err != nil { + s.errf(n, "cannot get reference for %v: %v", loc, err) + return nil + } + def = &definedSchema{ + importPath: importPath, + path: path, + } + s.defs[idStr] = def + return def +} + +// refExpr returns a CUE expression to refer to the given path within the given +// imported CUE package. If importPath is empty, it returns a reference +// relative to the root of the schema being generated. +func (s *state) refExpr(n cue.Value, importPath string, path cue.Path) ast.Expr { + if importPath == "" { + // Internal reference + expr, err := s.builder.getRef(path) + if err != nil { + s.errf(n, "cannot generate reference: %v", err) + return nil + } + return expr + } + // External reference + ip := module.ParseImportPath(importPath) + if ip.Qualifier == "" { + // TODO choose an arbitrary name here. + s.errf(n, "cannot determine package name from import path %q", importPath) + return nil + } + ident := ast.NewIdent(ip.Qualifier) + ident.Node = &ast.ImportSpec{Path: ast.NewString(importPath)} + expr, err := pathRefSyntax(path, ident) + if err != nil { + s.errf(n, "cannot determine CUE path: %v", err) + return nil + } + return expr +} + +func (s *state) constValue(n cue.Value) ast.Expr { + k := n.Kind() + switch k { + case cue.ListKind: + a := []ast.Expr{} + for i, _ := n.List(); i.Next(); { + a = append(a, s.constValue(i.Value())) + } + return setPos(ast.NewList(a...), n) + + case cue.StructKind: + a := []ast.Decl{} + s.processMap(n, func(key string, n cue.Value) { + a = append(a, &ast.Field{ + Label: ast.NewString(key), + Value: s.constValue(n), + Constraint: token.NOT, + }) + }) + return setPos(ast.NewCall(ast.NewIdent("close"), &ast.StructLit{Elts: a}), n) + default: + if !n.IsConcrete() { + s.errf(n, "invalid non-concrete value") + } + return n.Syntax(cue.Final()).(ast.Expr) + } } func (s *state) value(n cue.Value) ast.Expr { k := n.Kind() - s.usedTypes |= k - s.allowedTypes &= k switch k { case cue.ListKind: a := []ast.Expr{} @@ -598,8 +978,6 @@ func (s *state) value(n cue.Value) ast.Expr { Value: s.value(n), }) }) - // TODO: only open when s.isSchema? - a = append(a, &ast.Ellipsis{}) return setPos(&ast.StructLit{Elts: a}, n) default: @@ -616,14 +994,9 @@ func (s *state) value(n cue.Value) ast.Expr { // This may also prevent exponential blow-up (as may happen when // converting YAML to JSON). func (s *state) processMap(n cue.Value, f func(key string, n cue.Value)) { - saved := s.path - defer func() { s.path = saved }() - // TODO: intercept references to allow for optimized performance. for i, _ := n.Fields(); i.Next(); { - key := i.Label() - s.path = append(saved, key) - f(key, i.Value()) + f(i.Selector().Unquoted(), i.Value()) } } @@ -640,21 +1013,27 @@ func (s *state) listItems(name string, n cue.Value, allowEmpty bool) (a []cue.Va return a } -// excludeFields returns a CUE expression that can be used to exclude the +// excludeFields returns either an empty slice (if decls is empty) +// or a slice containing a CUE expression that can be used to exclude the // fields of the given declaration in a label expression. For instance, for // // { foo: 1, bar: int } // -// it creates +// it creates a slice holding the expression // -// "^(foo|bar)$" +// !~ "^(foo|bar)$" // // which can be used in a label expression to define types for all fields but // those existing: // // [!~"^(foo|bar)$"]: string -func excludeFields(decls []ast.Decl) ast.Expr { - var a []string +func excludeFields(decls []ast.Decl) []ast.Expr { + if len(decls) == 0 { + return nil + } + var buf strings.Builder + first := true + buf.WriteString("^(") for _, d := range decls { f, ok := d.(*ast.Field) if !ok { @@ -662,17 +1041,48 @@ func excludeFields(decls []ast.Decl) ast.Expr { } str, _, _ := ast.LabelName(f.Label) if str != "" { - a = append(a, str) + if !first { + buf.WriteByte('|') + } + buf.WriteString(regexp.QuoteMeta(str)) + first = false } } - re := fmt.Sprintf("^(%s)$", strings.Join(a, "|")) - return &ast.UnaryExpr{Op: token.NMAT, X: ast.NewString(re)} + buf.WriteString(")$") + return []ast.Expr{ + &ast.UnaryExpr{Op: token.NMAT, X: ast.NewString(buf.String())}, + } +} + +func bottom() ast.Expr { + return &ast.BottomLit{} +} + +func top() ast.Expr { + return ast.NewIdent("_") +} + +func boolSchema(ok bool) ast.Expr { + if ok { + return top() + } + return bottom() +} + +func isTop(s ast.Expr) bool { + i, ok := s.(*ast.Ident) + return ok && i.Name == "_" +} + +func isBottom(e ast.Expr) bool { + _, ok := e.(*ast.BottomLit) + return ok } func addTag(field ast.Label, tag, value string) *ast.Field { return &ast.Field{ Label: field, - Value: ast.NewIdent("_"), + Value: top(), Attrs: []*ast.Attribute{ {Text: fmt.Sprintf("@%s(%s)", tag, value)}, }, @@ -683,3 +1093,25 @@ func setPos(e ast.Expr, v cue.Value) ast.Expr { ast.SetPos(e, v.Pos()) return e } + +// uint64Value is like v.Uint64 except that it +// also allows floating point constants, as long +// as they have no fractional part. +func uint64Value(v cue.Value) (uint64, error) { + n, err := v.Uint64() + if err == nil { + return n, nil + } + f, err := v.Float64() + if err != nil { + return 0, err + } + intPart, fracPart := math.Modf(f) + if fracPart != 0 { + return 0, errors.Newf(v.Pos(), "%v is not a whole number", v) + } + if intPart < 0 || intPart > math.MaxUint64 { + return 0, errors.Newf(v.Pos(), "%v is out of bounds", v) + } + return uint64(intPart), nil +} diff --git a/vendor/cuelang.org/go/encoding/jsonschema/external_teststats.txt b/vendor/cuelang.org/go/encoding/jsonschema/external_teststats.txt new file mode 100644 index 0000000000..665015de1f --- /dev/null +++ b/vendor/cuelang.org/go/encoding/jsonschema/external_teststats.txt @@ -0,0 +1,22 @@ +# Generated by CUE_UPDATE=1 go test. DO NOT EDIT +v2: + schema extract (pass / total): 1054 / 1363 = 77.3% + tests (pass / total): 3793 / 4803 = 79.0% + tests on extracted schemas (pass / total): 3793 / 3955 = 95.9% + +v3: + schema extract (pass / total): 1054 / 1363 = 77.3% + tests (pass / total): 3793 / 4803 = 79.0% + tests on extracted schemas (pass / total): 3793 / 3955 = 95.9% + +Optional tests + +v2: + schema extract (pass / total): 235 / 274 = 85.8% + tests (pass / total): 1635 / 2372 = 68.9% + tests on extracted schemas (pass / total): 1635 / 2262 = 72.3% + +v3: + schema extract (pass / total): 235 / 274 = 85.8% + tests (pass / total): 1635 / 2372 = 68.9% + tests on extracted schemas (pass / total): 1635 / 2262 = 72.3% diff --git a/vendor/cuelang.org/go/encoding/jsonschema/jsonschema.go b/vendor/cuelang.org/go/encoding/jsonschema/jsonschema.go index c7e7be4382..a62c5b1110 100644 --- a/vendor/cuelang.org/go/encoding/jsonschema/jsonschema.go +++ b/vendor/cuelang.org/go/encoding/jsonschema/jsonschema.go @@ -32,8 +32,12 @@ package jsonschema import ( + "fmt" + "net/url" + "cuelang.org/go/cue" "cuelang.org/go/cue/ast" + "cuelang.org/go/cue/ast/astutil" "cuelang.org/go/cue/token" ) @@ -41,16 +45,64 @@ import ( // // The generated CUE schema is guaranteed to deem valid any value that is // a valid instance of the source JSON schema. -func Extract(data cue.InstanceOrValue, cfg *Config) (f *ast.File, err error) { - d := &decoder{cfg: cfg} +func Extract(data cue.InstanceOrValue, cfg *Config) (*ast.File, error) { + cfg = ref(*cfg) + if cfg.MapURL == nil { + cfg.MapURL = DefaultMapURL + } + if cfg.Map == nil { + cfg.Map = defaultMap + } + if cfg.MapRef == nil { + cfg.MapRef = func(loc SchemaLoc) (string, cue.Path, error) { + return defaultMapRef(loc, cfg.Map, cfg.MapURL) + } + } + if cfg.DefaultVersion == VersionUnknown { + cfg.DefaultVersion = DefaultVersion + } + if cfg.Strict { + cfg.StrictKeywords = true + cfg.StrictFeatures = true + } + if cfg.ID == "" { + // Always choose a fully-qualified ID for the schema, even + // if it doesn't declare one. + // + // From https://json-schema.org/draft-07/draft-handrews-json-schema-01#rfc.section.8.1 + // > Informatively, the initial base URI of a schema is the URI at which it was found, or a suitable substitute URI if none is known. + cfg.ID = DefaultRootID + } + rootIDURI, err := url.Parse(cfg.ID) + if err != nil { + return nil, fmt.Errorf("invalid Config.ID value %q: %v", cfg.ID, err) + } + if !rootIDURI.IsAbs() { + return nil, fmt.Errorf("Config.ID %q is not absolute URI", cfg.ID) + } + d := &decoder{ + cfg: cfg, + mapURLErrors: make(map[string]bool), + root: data.Value(), + rootID: rootIDURI, + defs: make(map[string]*definedSchema), + defForValue: newValueMap[*definedSchema](), + } - f = d.decode(data.Value()) + f := d.decode(d.root) if d.errs != nil { return nil, d.errs } + if err := astutil.Sanitize(f); err != nil { + return nil, fmt.Errorf("cannot sanitize jsonschema resulting syntax: %v", err) + } return f, nil } +// DefaultVersion defines the default schema version used when +// there is no $schema field and no explicit [Config.DefaultVersion]. +const DefaultVersion = VersionDraft2020_12 + // A Config configures a JSON Schema encoding or decoding. type Config struct { PkgName string @@ -58,14 +110,25 @@ type Config struct { // ID sets the URL of the original source, corresponding to the $id field. ID string - // JSON reference of location containing schema. The empty string indicates - // that there is a single schema at the root. + // JSON reference of location containing schemas. The empty string indicates + // that there is a single schema at the root. If this is non-empty, + // the referred-to location should be an object, and each member + // is taken to be a schema. // // Examples: - // "#/" top-level fields are schemas. + // "#/" or "#" top-level fields are schemas. // "#/components/schemas" the canonical OpenAPI location. + // + // Note: #/ should technically _not_ refer to the root of the + // schema: this behavior is preserved for backwards compatibility + // only. Just `#` is preferred. Root string + // AllowNonExistentRoot prevents an error when there is no value at + // the above Root path. Such an error can be useful to signal that + // the data may not be a JSON Schema, but is not always a good idea. + AllowNonExistentRoot bool + // Map maps the locations of schemas and definitions to a new location. // References are updated accordingly. A returned label must be // an identifier or string literal. @@ -74,16 +137,143 @@ type Config struct { // {} {} // {"definitions", foo} {#foo} or {#, foo} // {"$defs", foo} {#foo} or {#, foo} + // + // Deprecated: use [Config.MapRef]. Map func(pos token.Pos, path []string) ([]ast.Label, error) + // MapURL maps a URL reference as found in $ref to + // an import path for a CUE package and a path within that package. + // If this is nil, [DefaultMapURL] will be used. + // + // Deprecated: use [Config.MapRef]. + MapURL func(u *url.URL) (importPath string, path cue.Path, err error) + + // NOTE: this method is currently experimental. Its usage and type + // signature may change. + // + // MapRef is used to determine how a JSON schema location maps to + // CUE. It is used for both explicit references and for named + // schemas inside $defs and definitions. + // + // For example, given this schema: + // + // { + // "$schema": "https://json-schema.org/draft/2020-12/schema", + // "$id": "https://my.schema.org/hello", + // "$defs": { + // "foo": { + // "$id": "https://other.org", + // "type": "object", + // "properties": { + // "a": { + // "type": "string" + // }, + // "b": { + // "$ref": "#/properties/a" + // } + // } + // } + // }, + // "allOf": [{ + // "$ref": "#/$defs/foo" + // }, { + // "$ref": "https://my.schema.org/hello#/$defs/foo" + // }, { + // "$ref": "https://other.org" + // }, { + // "$ref": "https://external.ref" + // }] + // } + // + // ... MapRef will be called with the following locations for the + // $ref keywords in order of appearance (no guarantees are made + // about the actual order or number of calls to MapRef): + // + // ID RootRel + // https://other.org/properties/a https://my.schema.org/hello#/$defs/foo/properties/a + // https://my.schema.org/hello#/$defs/foo https://my.schema.org/hello#/$defs/foo + // https://other.org https://my.schema.org/hello#/$defs/foo + // https://external.ref + // + // It will also be called for the named schema in #/$defs/foo with these arguments: + // + // https://other.org https://my.schema.org/hello#/$defs/foo + // + // MapRef should return the desired CUE location for the schema with + // the provided IDs, consisting of the import path of the package + // containing the schema, and a path within that package. If the + // returned import path is empty, the path will be interpreted + // relative to the root of the generated JSON schema. + // + // Note that MapRef is general enough to subsume use of [Config.Map] and + // [Config.MapURL], which are both now deprecated. If all three fields are + // nil, [DefaultMapRef] will be used. + MapRef func(loc SchemaLoc) (importPath string, relPath cue.Path, err error) + + // NOTE: this method is currently experimental. Its usage and type + // signature may change. + // + // DefineSchema is called, if not nil, for any schema that is defined + // within the json schema being converted but is mapped somewhere + // external via [Config.MapRef]. The invoker of [Extract] is + // responsible for defining the schema e in the correct place as described + // by the import path and its relative CUE path. + // + // The importPath and path are exactly as returned by [Config.MapRef]. + // If this or [Config.MapRef] is nil this function will never be called. + // Note that importPath will never be empty, because if MapRef + // returns an empty importPath, it's specifying an internal schema + // which will be defined accordingly. + DefineSchema func(importPath string, path cue.Path, e ast.Expr) + // TODO: configurability to make it compatible with OpenAPI, such as // - locations of definitions: #/components/schemas, for instance. // - selection and definition of formats // - documentation hooks. - // Strict reports an error for unsupported features, rather than ignoring - // them. + // Strict reports an error for unsupported features and keywords, + // rather than ignoring them. When true, this is equivalent to + // setting both StrictFeatures and StrictKeywords to true. Strict bool + // StrictFeatures reports an error for features that are known + // to be unsupported. + StrictFeatures bool + + // StrictKeywords reports an error when unknown keywords + // are encountered. + StrictKeywords bool + + // DefaultVersion holds the default schema version to use + // when no $schema field is present. If it is zero, [DefaultVersion] + // will be used. + DefaultVersion Version + _ struct{} // prohibit casting from different type. } + +// SchemaLoc defines the location of schema, both in absolute +// terms as its canonical ID and, optionally, relative to the +// root of the value passed to [Extract]. +type SchemaLoc struct { + // ID holds the canonical URI of the schema, as declared + // by the schema or one of its parents. + ID *url.URL + + // IsLocal holds whether the schema has been defined locally. + // If true, then [SchemaLoc.Path] holds the path from the root + // value, as passed to [Extract], to the schema definition. + IsLocal bool + Path cue.Path +} + +func (loc SchemaLoc) String() string { + if loc.IsLocal { + return fmt.Sprintf("id=%v localPath=%v", loc.ID, loc.Path) + } + return fmt.Sprintf("id=%v", loc.ID) +} + +func ref[T any](x T) *T { + return &x +} diff --git a/vendor/cuelang.org/go/encoding/jsonschema/pointer.go b/vendor/cuelang.org/go/encoding/jsonschema/pointer.go new file mode 100644 index 0000000000..1dbe4f0ce1 --- /dev/null +++ b/vendor/cuelang.org/go/encoding/jsonschema/pointer.go @@ -0,0 +1,45 @@ +package jsonschema + +import "strings" + +// TODO this file contains functionality that mimics the JSON Pointer functionality +// in https://pkg.go.dev/github.com/go-json-experiment/json/jsontext#Pointer; +// perhaps use it when it moves into the stdlib as json/v2. + +var ( + jsonPtrEsc = strings.NewReplacer("~", "~0", "/", "~1") + jsonPtrUnesc = strings.NewReplacer("~0", "~", "~1", "/") +) + +// TODO(go1.23) func jsonPointerFromTokens(tokens iter.Seq[string]) string +func jsonPointerFromTokens(tokens func(func(string) bool)) string { + var buf strings.Builder + // TODO for tok := range tokens { + tokens(func(tok string) bool { + buf.WriteByte('/') + buf.WriteString(jsonPtrEsc.Replace(tok)) + return true + }) + return buf.String() +} + +// TODO(go1.23) func jsonPointerTokens(p string) iter.Seq[string] +func jsonPointerTokens(p string) func(func(string) bool) { + return func(yield func(string) bool) { + needUnesc := strings.IndexByte(p, '~') >= 0 + for len(p) > 0 { + p = strings.TrimPrefix(p, "/") + i := min(uint(strings.IndexByte(p, '/')), uint(len(p))) + var ok bool + if needUnesc { + ok = yield(jsonPtrUnesc.Replace(p[:i])) + } else { + ok = yield(p[:i]) + } + if !ok { + return + } + p = p[i:] + } + } +} diff --git a/vendor/cuelang.org/go/encoding/jsonschema/ref.go b/vendor/cuelang.org/go/encoding/jsonschema/ref.go index 81e0913ff6..fd7bf644a6 100644 --- a/vendor/cuelang.org/go/encoding/jsonschema/ref.go +++ b/vendor/cuelang.org/go/encoding/jsonschema/ref.go @@ -15,6 +15,8 @@ package jsonschema import ( + "encoding/base64" + "fmt" "net/url" "path" "strconv" @@ -27,41 +29,72 @@ import ( "cuelang.org/go/internal" ) -func (d *decoder) parseRef(p token.Pos, str string) []string { +func parseRootRef(str string) (cue.Path, error) { u, err := url.Parse(str) if err != nil { - d.addErr(errors.Newf(p, "invalid JSON reference: %s", err)) - return nil - } - - if u.Host != "" || u.Path != "" { - d.addErr(errors.Newf(p, "external references (%s) not supported", str)) - // TODO: handle - // host: - // If the host corresponds to a package known to cue, - // load it from there. It would prefer schema converted to - // CUE, although we could consider loading raw JSON schema - // if present. - // If not present, advise the user to run cue get. - // path: - // Look up on file system or relatively to authority location. - return nil - } - - if !path.IsAbs(u.Fragment) { - d.addErr(errors.Newf(p, "anchors (%s) not supported", u.Fragment)) - // TODO: support anchors - return nil - } + return cue.Path{}, fmt.Errorf("invalid JSON reference: %s", err) + } + if u.Host != "" || u.Path != "" || u.Opaque != "" { + return cue.Path{}, fmt.Errorf("external references (%s) not supported in Root", str) + } + // As a special case for backward compatibility, treat + // trim a final slash because the docs specifically + // mention that #/ refers to the root document + // and the openapi code uses #/components/schemas/. + // (technically a trailing slash `/` means there's an empty + // final element). + u.Fragment = strings.TrimSuffix(u.Fragment, "/") + fragmentParts := collectSlice(jsonPointerTokens(u.Fragment)) + var selectors []cue.Selector + for _, r := range fragmentParts { + // Technically this is incorrect because a numeric + // element could also index into a list, but the + // resulting CUE path will not allow that. + selectors = append(selectors, cue.Str(r)) + } + return cue.MakePath(selectors...), nil +} - // NOTE: Go bug?: url.URL has no raw representation of the fragment. This - // means that %2F gets translated to `/` before it can be split. This, in - // turn, means that field names cannot have a `/` as name. +var errRefNotFound = errors.New("JSON Pointer reference not found") + +func lookupJSONPointer(v cue.Value, p string) (_ cue.Value, _err error) { + // TODO(go1.23) for part := range jsonPointerTokens(p) + jsonPointerTokens(p)(func(part string) bool { + // Note: a JSON Pointer doesn't distinguish between indexing + // and struct lookup. We have to use the value itself to decide + // which operation is appropriate. + v, _ = v.Default() + switch v.Kind() { + case cue.StructKind: + v = v.LookupPath(cue.MakePath(cue.Str(part))) + case cue.ListKind: + idx := int64(0) + if len(part) > 1 && part[0] == '0' { + // Leading zeros are not allowed + _err = errRefNotFound + return false + } + idx, err := strconv.ParseInt(part, 10, 64) + if err != nil { + _err = errRefNotFound + return false + } + v = v.LookupPath(cue.MakePath(cue.Index(idx))) + } + if !v.Exists() { + _err = errRefNotFound + return false + } + return true + }) + return v, _err +} - return splitFragment(u) +func sameSchemaRoot(u1, u2 *url.URL) bool { + return u1.Host == u2.Host && u1.Path == u2.Path && u1.Opaque == u2.Opaque } -// resolveURI parses a URI from n and resolves it in the current context. +// resolveURI parses a URI from s and resolves it in the current context. // To resolve it in the current context, it looks for the closest URI from // an $id in the parent scopes and the uses the URI resolution to get the // new URI. @@ -75,360 +108,103 @@ func (s *state) resolveURI(n cue.Value) *url.URL { u, err := url.Parse(str) if err != nil { - s.addErr(errors.Newf(n.Pos(), "invalid JSON reference: %s", err)) + s.addErr(errors.Newf(n.Pos(), "invalid JSON reference: %v", err)) return nil } - for { - if s.id != nil { - u = s.id.ResolveReference(u) - break - } - if s.up == nil { - break - } - s = s.up - } - - return u -} - -const topSchema = "_schema" - -// makeCUERef converts a URI into a CUE reference for the current location. -// The returned identifier (or first expression in a selection chain), is -// hardwired to point to the resolved value. This will allow astutil.Sanitize -// to automatically unshadow any shadowed variables. -func (s *state) makeCUERef(n cue.Value, u *url.URL) ast.Expr { - a := splitFragment(u) - - switch fn := s.cfg.Map; { - case fn != nil: - // TODO: This block is only used in case s.cfg.Map is set, which is - // currently only used for OpenAPI. Handling should be brought more in - // line with JSON schema. - a, err := fn(n.Pos(), a) - if err != nil { - s.addErr(errors.Newf(n.Pos(), "invalid reference %q: %v", u, err)) + if u.IsAbs() { + // Absolute URI: no need to walk up the tree. + if u.Host == DefaultRootIDHost { + // No-one should be using the default root ID explicitly. + s.errf(n, "invalid use of default root ID host (%v) in URI", DefaultRootIDHost) return nil } - if len(a) == 0 { - // TODO: should we allow inserting at root level? - s.addErr(errors.Newf(n.Pos(), - "invalid empty reference returned by map for %q", u)) - return nil - } - sel, ok := a[0].(ast.Expr) - if !ok { - sel = &ast.BadExpr{} - } - for _, l := range a[1:] { - switch x := l.(type) { - case *ast.Ident: - sel = &ast.SelectorExpr{X: sel, Sel: x} - - case *ast.BasicLit: - sel = &ast.IndexExpr{X: sel, Index: x} - } - } - return sel + return u } - var ident *ast.Ident - - for ; ; s = s.up { - if s.up == nil { - switch { - case u.Host == "" && u.Path == "", - s.id != nil && s.id.Host == u.Host && s.id.Path == u.Path: - if len(a) == 0 { - // refers to the top of the file. We will allow this by - // creating a helper schema as such: - // _schema: {...} - // _schema - // This is created at the finalization stage if - // hasSelfReference is set. - s.hasSelfReference = true - - ident = ast.NewIdent(topSchema) - ident.Node = s.obj - return ident - } - - ident, a = s.getNextIdent(n, a) - - case u.Host != "": - // Reference not found within scope. Create an import reference. - - // TODO: allow the configuration to specify a map from - // URI domain+paths to CUE packages. - - // TODO: currently only $ids that are in scope can be - // referenced. We could consider doing an extra pass to record - // all '$id's in a file to be able to link to them even if they - // are not in scope. - p := u.Path - - base := path.Base(p) - if !ast.IsValidIdent(base) { - base = strings.TrimSuffix(base, ".json") - if !ast.IsValidIdent(base) { - // Find something more clever to do there. For now just - // pick "schema" as the package name. - base = "schema" - } - p += ":" + base - } - - ident = ast.NewIdent(base) - ident.Node = &ast.ImportSpec{Path: ast.NewString(u.Host + p)} - - default: - // Just a path, not sure what that means. - s.errf(n, "unknown domain for reference %q", u) - return nil - } - break - } - - if s.id == nil { - continue - } - - if s.id.Host == u.Host && s.id.Path == u.Path { - if len(a) == 0 { - if len(s.idRef) == 0 { - // This is a reference to either root or a schema for which - // we do not yet support references. See Issue #386. - if s.up.up != nil { - s.errf(n, "cannot refer to internal schema %q", u) - return nil - } - - // This is referring to the root scope. There is a dummy - // state above the root state that we need to update. - s = s.up - - // refers to the top of the file. We will allow this by - // creating a helper schema as such: - // _schema: {...} - // _schema - // This is created at the finalization stage if - // hasSelfReference is set. - s.hasSelfReference = true - ident = ast.NewIdent(topSchema) - ident.Node = s.obj - return ident - } - - x := s.idRef[0] - if !x.isDef && !ast.IsValidIdent(x.name) { - s.errf(n, "referring to field %q not supported", x.name) - return nil - } - e := ast.NewIdent(x.name) - if len(s.idRef) == 1 { - return e - } - return newSel(e, s.idRef[1]) - } - ident, a = s.getNextIdent(n, a) - ident.Node = s.obj - break - } - } - - return s.newSel(ident, n, a) + // TODO(go1.23) use ResolveReference directly. + return resolveReference(s.schemaRoot().id, u) } -// getNextSelector translates a JSON Reference path into a CUE path by consuming -// the first path elements and returning the corresponding CUE label. -func (s *state) getNextSelector(v cue.Value, a []string) (l label, tail []string) { - switch elem := a[0]; elem { - case "$defs", "definitions": - if len(a) == 1 { - s.errf(v, "cannot refer to %s section: must refer to one of its elements", a[0]) - return label{}, nil - } - - if name := "#" + a[1]; ast.IsValidIdent(name) { - return label{name, true}, a[2:] - } - - return label{"#", true}, a[1:] - - case "properties": - if len(a) == 1 { - s.errf(v, "cannot refer to %s section: must refer to one of its elements", a[0]) - return label{}, nil +// schemaRoot returns the state for the nearest enclosing +// schema that has its own schema ID. +func (s *state) schemaRoot() *state { + for ; s != nil; s = s.up { + if s.id != nil { + return s } - - return label{a[1], false}, a[2:] - - default: - return label{elem, false}, a[1:] - - case "additionalProperties", - "patternProperties", - "items", - "additionalItems": - // TODO: as a temporary workaround, include the schema verbatim. - // TODO: provide definitions for these in CUE. - s.errf(v, "referring to field %q not yet supported", elem) - - // Other known fields cannot be supported. - return label{}, nil } + // Should never happen, as we ensure there's always an absolute + // URI at the root. + panic("unreachable") } -// newSel converts a JSON Reference path and initial CUE identifier to -// a CUE selection path. -func (s *state) newSel(e ast.Expr, v cue.Value, a []string) ast.Expr { - for len(a) > 0 { - var label label - label, a = s.getNextSelector(v, a) - e = newSel(e, label) - } - return e -} - -// newSel converts label to a CUE index and creates an expression to index -// into e. -func newSel(e ast.Expr, label label) ast.Expr { - if label.isDef { - return ast.NewSel(e, label.name) - - } - if ast.IsValidIdent(label.name) && !internal.IsDefOrHidden(label.name) { - return ast.NewSel(e, label.name) - } - return &ast.IndexExpr{X: e, Index: ast.NewString(label.name)} -} - -func (s *state) setField(lab label, f *ast.Field) { - x := s.getRef(lab) - x.field = f - s.setRef(lab, x) - x = s.getRef(lab) +// DefaultMapRef implements the default logic for mapping a schema location +// to CUE. +// It uses a heuristic to map the URL host and path to an import path, +// and maps the fragment part according to the following: +// +// # +// #/definitions/foo #foo or #."foo" +// #/$defs/foo #foo or #."foo" +func DefaultMapRef(loc SchemaLoc) (importPath string, path cue.Path, err error) { + return defaultMapRef(loc, defaultMap, DefaultMapURL) } -func (s *state) getRef(lab label) refs { - if s.fieldRefs == nil { - s.fieldRefs = make(map[label]refs) - } - x, ok := s.fieldRefs[lab] - if !ok { - if lab.isDef || - (ast.IsValidIdent(lab.name) && !internal.IsDefOrHidden(lab.name)) { - x.ident = lab.name - } else { - x.ident = "_X" + strconv.Itoa(s.decoder.numID) - s.decoder.numID++ +// defaultMapRef implements the default MapRef semantics +// in terms of the default Map and MapURL functions provided +// in the configuration. +func defaultMapRef( + loc SchemaLoc, + mapFn func(pos token.Pos, path []string) ([]ast.Label, error), + mapURLFn func(u *url.URL) (importPath string, path cue.Path, err error), +) (importPath string, path cue.Path, err error) { + var fragment string + if loc.IsLocal { + fragment = cuePathToJSONPointer(loc.Path) + } else { + // It's external: use mapURLFn. + u := ref(*loc.ID) + fragment = loc.ID.Fragment + u.Fragment = "" + var err error + importPath, path, err = mapURLFn(u) + if err != nil { + return "", cue.Path{}, err } - s.fieldRefs[lab] = x } - return x -} - -func (s *state) setRef(lab label, r refs) { - s.fieldRefs[lab] = r -} - -// getNextIdent gets the first CUE reference from a JSON Reference path and -// converts it to a CUE identifier. -func (s *state) getNextIdent(v cue.Value, a []string) (resolved *ast.Ident, tail []string) { - lab, a := s.getNextSelector(v, a) - - x := s.getRef(lab) - ident := ast.NewIdent(x.ident) - x.refs = append(x.refs, ident) - s.setRef(lab, x) - - return ident, a -} - -// linkReferences resolves identifiers to relevant nodes. This allows -// astutil.Sanitize to unshadow nodes if necessary. -func (s *state) linkReferences() { - for _, r := range s.fieldRefs { - if r.field == nil { - // TODO: improve error message. - s.errf(cue.Value{}, "reference to non-existing value %q", r.ident) - continue - } - - // link resembles the link value. See astutil.Resolve. - var link ast.Node - - ident, ok := r.field.Label.(*ast.Ident) - if ok && ident.Name == r.ident { - link = r.field.Value - } else if len(r.refs) > 0 { - r.field.Label = &ast.Alias{ - Ident: ast.NewIdent(r.ident), - Expr: r.field.Label.(ast.Expr), - } - link = r.field - } - - for _, i := range r.refs { - i.Node = link - } + if len(fragment) > 0 && fragment[0] != '/' { + return "", cue.Path{}, fmt.Errorf("anchors (%s) not supported", fragment) } -} - -// splitFragment splits the fragment part of a URI into path components. The -// result may be an empty slice. -// -// TODO: this requires RawFragment introduced in go1.15 to function properly. -// As for now, CUE still uses go1.12. -func splitFragment(u *url.URL) []string { - if u.Fragment == "" { - return nil + parts := collectSlice(jsonPointerTokens(fragment)) + labels, err := mapFn(token.Pos{}, parts) + if err != nil { + return "", cue.Path{}, err } - s := strings.TrimRight(u.Fragment[1:], "/") - if s == "" { - return nil + relPath, err := labelsToCUEPath(labels) + if err != nil { + return "", cue.Path{}, err } - return strings.Split(s, "/") + return importPath, pathConcat(path, relPath), nil } -func (d *decoder) mapRef(p token.Pos, str string, ref []string) []ast.Label { - fn := d.cfg.Map - if fn == nil { - fn = jsonSchemaRef - } - a, err := fn(p, ref) - if err != nil { - if str == "" { - str = "#/" + strings.Join(ref, "/") - } - d.addErr(errors.Newf(p, "invalid reference %q: %v", str, err)) - return nil - } +func defaultMap(p token.Pos, a []string) ([]ast.Label, error) { if len(a) == 0 { - // TODO: should we allow inserting at root level? - if str == "" { - str = "#/" + strings.Join(ref, "/") - } - d.addErr(errors.Newf(p, - "invalid empty reference returned by map for %q", str)) - return nil + return nil, nil } - return a -} - -func jsonSchemaRef(p token.Pos, a []string) ([]ast.Label, error) { // TODO: technically, references could reference a // non-definition. We disallow this case for the standard // JSON Schema interpretation. We could detect cases that // are not definitions and then resolve those as literal // values. if len(a) != 2 || (a[0] != "definitions" && a[0] != "$defs") { - return nil, errors.Newf(p, - // Don't mention the ability to use $defs, as this definition seems - // to already have been withdrawn from the JSON Schema spec. - "$ref must be of the form #/definitions/...") + // It's an internal reference (or a nested definition reference). + // Fall back to defining it in the internal namespace. + // TODO this is needlessly inefficient, as we're putting something + // back together that was already joined before defaultMap was + // invoked. This does avoid dual implementations though. + p := jsonPointerFromTokens(sliceValues(a)) + return []ast.Label{ast.NewIdent("_#defs"), ast.NewString(p)}, nil } name := a[1] if ast.IsValidIdent(name) && @@ -438,3 +214,29 @@ func jsonSchemaRef(p token.Pos, a []string) ([]ast.Label, error) { } return []ast.Label{ast.NewIdent(rootDefs), ast.NewString(name)}, nil } + +// DefaultMapURL implements the default schema ID to import +// path mapping. It trims off any ".json" suffix and uses the +// package name "schema" if the final component of the path +// isn't a valid CUE identifier. +// +// Deprecated: The [Config.MapURL] API is superceded in +// factor of [Config.MapRef]. +func DefaultMapURL(u *url.URL) (string, cue.Path, error) { + p := u.Path + base := path.Base(p) + if !ast.IsValidIdent(base) { + base = strings.TrimSuffix(base, ".json") + if !ast.IsValidIdent(base) { + // Find something more clever to do there. For now just + // pick "schema" as the package name. + base = "schema" + } + p += ":" + base + } + if u.Opaque != "" { + // TODO don't use base64 unless we really have to. + return base64.RawURLEncoding.EncodeToString([]byte(u.Opaque)), cue.Path{}, nil + } + return u.Host + p, cue.Path{}, nil +} diff --git a/vendor/cuelang.org/go/encoding/jsonschema/resolveref_v1.22.go b/vendor/cuelang.org/go/encoding/jsonschema/resolveref_v1.22.go new file mode 100644 index 0000000000..b66b30518b --- /dev/null +++ b/vendor/cuelang.org/go/encoding/jsonschema/resolveref_v1.22.go @@ -0,0 +1,46 @@ +//go:build !go1.23 + +package jsonschema + +import "net/url" + +// resolveReference is exactly like [url.URL.ResolveReference] +// except that it fixes https://go.dev/issue/66084, which +// has been fixed in Go 1.23 (https://go.dev/cl/572915) but not go1.22 +// TODO(go1.23) remove this and use ResolveReference directly] +func resolveReference(u, ref *url.URL) *url.URL { + if !hitsBug(u, ref) { + return u.ResolveReference(ref) + } + url := *ref + if ref.Scheme == "" { + url.Scheme = u.Scheme + } + if ref.Path == "" && !ref.ForceQuery && ref.RawQuery == "" { + url.RawQuery = u.RawQuery + if ref.Fragment == "" { + url.Fragment = u.Fragment + url.RawFragment = u.RawFragment + } + } + url.Opaque = u.Opaque + url.User = nil + url.Host = "" + url.Path = "" + return &url +} + +// This mirrors the structure of the stdlib [url.URL.ResolveReference] +// method. +func hitsBug(u, ref *url.URL) bool { + if ref.Scheme != "" || ref.Host != "" || ref.User != nil { + return false + } + if ref.Opaque != "" { + return false + } + if ref.Path == "" && u.Opaque != "" { + return true + } + return false +} diff --git a/vendor/cuelang.org/go/encoding/jsonschema/resolveref_v1.23.go b/vendor/cuelang.org/go/encoding/jsonschema/resolveref_v1.23.go new file mode 100644 index 0000000000..a878c93e7e --- /dev/null +++ b/vendor/cuelang.org/go/encoding/jsonschema/resolveref_v1.23.go @@ -0,0 +1,11 @@ +//go:build go1.23 + +// TODO(go1.12) remove this file. + +package jsonschema + +import "net/url" + +func resolveReference(u, ref *url.URL) *url.URL { + return u.ResolveReference(ref) +} diff --git a/vendor/cuelang.org/go/encoding/jsonschema/structbuilder.go b/vendor/cuelang.org/go/encoding/jsonschema/structbuilder.go new file mode 100644 index 0000000000..5cd875013b --- /dev/null +++ b/vendor/cuelang.org/go/encoding/jsonschema/structbuilder.go @@ -0,0 +1,282 @@ +package jsonschema + +import ( + "cmp" + "fmt" + + "cuelang.org/go/cue" + "cuelang.org/go/cue/ast" + "cuelang.org/go/cue/token" +) + +// structBuilder builds a struct value incrementally by +// putting values for its component paths. +// The [structBuilder.getRef] method can be used +// to obtain reliable references into the resulting struct. +type structBuilder struct { + root structBuilderNode + + // refIdents records all the identifiers that refer to entries + // at the top level of the struct, keyed by the selector + // they're referring to. + // + // The [Ident.Node] field needs to refer to the field value rather + // than the field label, and we don't know that until the syntax + // method has been invoked, so we fix up the [Ident.Node] fields when + // that happens. + refIdents map[cue.Selector][]*ast.Ident + + // rootRefIdents is like refIdents but for references to the + // struct root itself. + rootRefIdents []*ast.Ident +} + +// structBuilderNode represents one node in the tree of values +// being built. +type structBuilderNode struct { + // value holds the value associated with the node, if any. + // This does not include entries added underneath it by + // [structBuilder.put]. + value ast.Expr + + // comment holds any doc comment associated with the value. + comment *ast.CommentGroup + + // entries holds the children of this node, keyed by the + // name of each child's struct field selector. + entries map[cue.Selector]*structBuilderNode +} + +// put associates value with the given path. It reports whether +// the value was successfully put, returning false if a value +// already exists for the path. +func (b *structBuilder) put(p cue.Path, value ast.Expr, comment *ast.CommentGroup) bool { + e := b.entryForPath(p) + if e.value != nil { + // redefinition + return false + } + e.value = value + e.comment = comment + return true +} + +const rootIdentName = "_schema" + +// getRef returns CUE syntax for a reference to the path p within b. +// It ensures that, if possible, the identifier at the start of the +// reference expression has the correct target node. +func (b *structBuilder) getRef(p cue.Path) (ast.Expr, error) { + if err := p.Err(); err != nil { + return nil, fmt.Errorf("invalid path %v", p) + } + sels := p.Selectors() + if len(sels) == 0 { + // There's no natural name for the root element, + // so use an arbitrary one. + ref := ast.NewIdent(rootIdentName) + + b.rootRefIdents = append(b.rootRefIdents, ref) + return ref, nil + } + base, err := labelForSelector(sels[0]) + if err != nil { + return nil, err + } + baseExpr, ok := base.(*ast.Ident) + if !ok { + return nil, fmt.Errorf("initial element of path %q must be expressed as an identifier", p) + } + // The base identifier needs to refer to the + // first element of the path; the rest doesn't matter. + if b.refIdents == nil { + b.refIdents = make(map[cue.Selector][]*ast.Ident) + } + b.refIdents[sels[0]] = append(b.refIdents[sels[0]], baseExpr) + return pathRefSyntax(cue.MakePath(sels[1:]...), baseExpr) +} + +func (b *structBuilder) entryForPath(p cue.Path) *structBuilderNode { + if err := p.Err(); err != nil { + panic(fmt.Errorf("invalid path %v", p)) + } + sels := p.Selectors() + + n := &b.root + for _, sel := range sels { + if n.entries == nil { + n.entries = make(map[cue.Selector]*structBuilderNode) + } + n1, ok := n.entries[sel] + if !ok { + n1 = &structBuilderNode{} + n.entries[sel] = n1 + } + n = n1 + } + return n +} + +// syntax returns an expression for the whole struct. +func (b *structBuilder) syntax() (*ast.File, error) { + var db declBuilder + if err := b.appendDecls(&b.root, &db); err != nil { + return nil, err + } + // Fix up references (we don't need to do this if the root is a single + // expression, because that only happens when there's nothing + // to refer to). + for _, decl := range db.decls { + if f, ok := decl.(*ast.Field); ok { + for _, ident := range b.refIdents[selectorForLabel(f.Label)] { + ident.Node = f.Value + } + } + } + + var f *ast.File + if len(b.rootRefIdents) == 0 { + // No reference to root, so can use declarations as they are. + f = &ast.File{ + Decls: db.decls, + } + } else { + rootExpr := exprFromDecls(db.decls) + // Fix up references to the root node. + for _, ident := range b.rootRefIdents { + ident.Node = rootExpr + } + rootRef, err := b.getRef(cue.Path{}) + if err != nil { + return nil, err + } + f = &ast.File{ + Decls: []ast.Decl{ + &ast.EmbedDecl{Expr: rootRef}, + &ast.Field{ + Label: ast.NewIdent(rootIdentName), + Value: rootExpr, + }, + }, + } + } + if b.root.comment != nil { + // If Doc is true, as it is for comments on fields, + // then the CUE formatting will join it to any import + // directives, which is not what we want, as then + // it will no longer appear as a comment on the file. + // So set Doc to false to prevent that happening. + b.root.comment.Doc = false + ast.SetComments(f, []*ast.CommentGroup{b.root.comment}) + } + + return f, nil +} + +func (b *structBuilder) appendDecls(n *structBuilderNode, db *declBuilder) (_err error) { + if n.value != nil { + if len(n.entries) > 0 { + // We've got a value associated with this node and also some entries inside it. + // We need to make a struct literal to hold the value and those entries + // because the value might be scalar and + // #x: string + // #x: #y: bool + // is not allowed. + // + // So make a new declBuilder instance with a fresh empty path + // to build the declarations to put inside a struct literal. + db0 := db + db = &declBuilder{} + defer func() { + if _err != nil { + return + } + db0.decls, _err = appendField(db0.decls, cue.MakePath(db0.path...), exprFromDecls(db.decls), n.comment) + }() + } + // Note: when the path is empty, we rely on the outer level + // to add any doc comment required. + db.decls, _err = appendField(db.decls, cue.MakePath(db.path...), n.value, n.comment) + if _err != nil { + return _err + } + } + // TODO slices.SortedFunc(maps.Keys(n.entries), cmpSelector) + for _, sel := range sortedKeys(n.entries, cmpSelector) { + entry := n.entries[sel] + db.pushPath(sel) + err := b.appendDecls(entry, db) + db.popPath() + if err != nil { + return err + } + } + return nil +} + +type declBuilder struct { + decls []ast.Decl + path []cue.Selector +} + +func (b *declBuilder) pushPath(sel cue.Selector) { + b.path = append(b.path, sel) +} + +func (b *declBuilder) popPath() { + b.path = b.path[:len(b.path)-1] +} + +func exprFromDecls(decls []ast.Decl) ast.Expr { + if len(decls) == 1 { + if decl, ok := decls[0].(*ast.EmbedDecl); ok { + // It's a single embedded expression which we can use directly. + return decl.Expr + } + } + return &ast.StructLit{ + Elts: decls, + } +} + +func appendDeclsExpr(decls []ast.Decl, expr ast.Expr) []ast.Decl { + switch expr := expr.(type) { + case *ast.StructLit: + decls = append(decls, expr.Elts...) + default: + elt := &ast.EmbedDecl{Expr: expr} + ast.SetRelPos(elt, token.NewSection) + decls = append(decls, elt) + } + return decls +} + +func appendField(decls []ast.Decl, path cue.Path, v ast.Expr, comment *ast.CommentGroup) ([]ast.Decl, error) { + if len(path.Selectors()) == 0 { + return appendDeclsExpr(decls, v), nil + } + expr, err := exprAtPath(path, v) + if err != nil { + return nil, err + } + // exprAtPath will always return a struct literal with exactly + // one element when the path is non-empty. + structLit := expr.(*ast.StructLit) + elt := structLit.Elts[0] + if comment != nil { + ast.SetComments(elt, []*ast.CommentGroup{comment}) + } + ast.SetRelPos(elt, token.NewSection) + return append(decls, elt), nil +} + +func cmpSelector(s1, s2 cue.Selector) int { + if s1 == s2 { + // Avoid String allocation when we can. + return 0 + } + if c := cmp.Compare(s1.Type(), s2.Type()); c != 0 { + return c + } + return cmp.Compare(s1.String(), s2.String()) +} diff --git a/vendor/cuelang.org/go/encoding/jsonschema/util.go b/vendor/cuelang.org/go/encoding/jsonschema/util.go new file mode 100644 index 0000000000..4320d0c4e6 --- /dev/null +++ b/vendor/cuelang.org/go/encoding/jsonschema/util.go @@ -0,0 +1,230 @@ +// Copyright 2024 CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package jsonschema + +import ( + "fmt" + "slices" + "strconv" + "strings" + + "cuelang.org/go/cue" + "cuelang.org/go/cue/ast" + "cuelang.org/go/cue/token" +) + +// TODO a bunch of stuff in this file is potentially suitable +// for more general use. Consider moving some of it +// to the cue package. + +func pathConcat(p1, p2 cue.Path) cue.Path { + sels1, sels2 := p1.Selectors(), p2.Selectors() + if len(sels1) == 0 { + return p2 + } + if len(sels2) == 0 { + return p1 + } + return cue.MakePath(append(slices.Clip(sels1), sels2...)...) +} + +func labelsToCUEPath(labels []ast.Label) (cue.Path, error) { + sels := make([]cue.Selector, len(labels)) + for i, label := range labels { + // Note: we can't use cue.Label because that doesn't + // allow hidden fields. + sels[i] = selectorForLabel(label) + } + path := cue.MakePath(sels...) + if err := path.Err(); err != nil { + return cue.Path{}, err + } + return path, nil +} + +// selectorForLabel is like [cue.Label] except that it allows +// hidden fields, which aren't allowed there because technically +// we can't work out what package to associate with the resulting +// selector. In our case we always imply the local package so +// we don't mind about that. +func selectorForLabel(label ast.Label) cue.Selector { + if label, _ := label.(*ast.Ident); label != nil && strings.HasPrefix(label.Name, "_") { + return cue.Hid(label.Name, "_") + } + return cue.Label(label) +} + +// pathRefSyntax returns the syntax for an expression which +// looks up the path inside the given root expression's value. +// It returns an error if the path contains any elements with +// type [cue.OptionalConstraint], [cue.RequiredConstraint], or [cue.PatternConstraint], +// none of which are expressible as a CUE index expression. +// +// TODO implement this properly and move to a method on [cue.Path]. +func pathRefSyntax(cuePath cue.Path, root ast.Expr) (ast.Expr, error) { + expr := root + for _, sel := range cuePath.Selectors() { + if sel.LabelType() == cue.IndexLabel { + expr = &ast.IndexExpr{ + X: expr, + Index: &ast.BasicLit{ + Kind: token.INT, + Value: sel.String(), + }, + } + } else { + lab, err := labelForSelector(sel) + if err != nil { + return nil, err + } + expr = &ast.SelectorExpr{ + X: expr, + Sel: lab, + } + } + } + return expr, nil +} + +// exprAtPath returns an expression that places the given +// expression at the given path. +// For example: +// +// declAtPath(cue.ParsePath("a.b.#c"), ast.NewIdent("foo")) +// +// would result in the declaration: +// +// a: b: #c: foo +// +// TODO this is potentially generally useful. It could +// be exposed as a method on [cue.Path], say +// `SyntaxForDefinition` or something. +func exprAtPath(path cue.Path, expr ast.Expr) (ast.Expr, error) { + sels := path.Selectors() + for i := len(sels) - 1; i >= 0; i-- { + sel := sels[i] + label, err := labelForSelector(sel) + if err != nil { + return nil, err + } + // A StructLit is inlined if both: + // - the Lbrace position is invalid + // - the Label position is valid. + rel := token.Blank + if i == 0 { + rel = token.Newline + } + ast.SetPos(label, token.NoPos.WithRel(rel)) + expr = &ast.StructLit{ + Elts: []ast.Decl{ + &ast.Field{ + Label: label, + Value: expr, + }, + }, + } + } + return expr, nil +} + +// TODO define this as a Label method on cue.Selector? +func labelForSelector(sel cue.Selector) (ast.Label, error) { + switch sel.LabelType() { + case cue.StringLabel, cue.DefinitionLabel, cue.HiddenLabel, cue.HiddenDefinitionLabel: + str := sel.String() + switch { + case strings.HasPrefix(str, `"`): + // It's quoted for a reason, so maintain the quotes. + return &ast.BasicLit{ + Kind: token.STRING, + Value: str, + }, nil + case ast.IsValidIdent(str): + return ast.NewIdent(str), nil + } + // Should never happen. + return nil, fmt.Errorf("cannot form expression for selector %q", sel) + default: + return nil, fmt.Errorf("cannot form label for selector %q with type %v", sel, sel.LabelType()) + } +} + +func cuePathToJSONPointer(p cue.Path) string { + return jsonPointerFromTokens(func(yield func(s string) bool) { + for _, sel := range p.Selectors() { + var token string + switch sel.Type() { + case cue.StringLabel: + token = sel.Unquoted() + case cue.IndexLabel: + token = strconv.Itoa(sel.Index()) + default: + panic(fmt.Errorf("cannot convert selector %v to JSON pointer", sel)) + } + if !yield(token) { + return + } + } + }) +} + +// relPath returns the path to v relative to root, +// which must be a direct ancestor of v. +func relPath(v, root cue.Value) cue.Path { + rootPath := root.Path().Selectors() + vPath := v.Path().Selectors() + if !sliceHasPrefix(vPath, rootPath) { + panic("value is not inside root") + } + return cue.MakePath(vPath[len(rootPath):]...) +} + +func sliceHasPrefix[E comparable](s1, s2 []E) bool { + if len(s2) > len(s1) { + return false + } + return slices.Equal(s1[:len(s2)], s2) +} + +// TODO remove this when we can use [slices.SortedFunc] and [maps.Keys]. +func sortedKeys[K comparable, V any](m map[K]V, cmp func(K, K) int) []K { + ks := make([]K, 0, len(m)) + for k := range m { + ks = append(ks, k) + } + slices.SortFunc(ks, cmp) + return ks +} + +// TODO(go1.23) use slices.Collect +func collectSlice[E any](seq func(func(E) bool)) []E { + var s []E + seq(func(v E) bool { + s = append(s, v) + return true + }) + return s +} + +// TODO(go1.23) use slices.Values +func sliceValues[Slice ~[]E, E any](s Slice) func(func(E) bool) { + return func(yield func(E) bool) { + for _, v := range s { + if !yield(v) { + return + } + } + } +} diff --git a/vendor/cuelang.org/go/encoding/jsonschema/valuemap.go b/vendor/cuelang.org/go/encoding/jsonschema/valuemap.go new file mode 100644 index 0000000000..22053c3b20 --- /dev/null +++ b/vendor/cuelang.org/go/encoding/jsonschema/valuemap.go @@ -0,0 +1,54 @@ +package jsonschema + +import ( + "cuelang.org/go/cue" + "cuelang.org/go/cue/token" +) + +// valueMap holds a map of values indexed by schema position +// (a.k.a. JSON Pointer). +// +// It's designed so that it's cheap in the common case that a lookup +// returns false and that there are many more lookups than +// entries in the map. +// +// It does that by using the source position of the +// schema as a first probe. Determining the source location of a value +// is very cheap, and in most practical cases, JSON Schema is being +// extracted from concrete JSON where there will be a bijective mapping +// between source location and path. +type valueMap[T any] struct { + byPos map[token.Pos]bool + byPath map[string]T +} + +func newValueMap[T any]() *valueMap[T] { + return &valueMap[T]{ + byPos: make(map[token.Pos]bool), + byPath: make(map[string]T), + } +} + +func (m *valueMap[T]) len() int { + return len(m.byPath) +} + +func (m *valueMap[T]) set(key cue.Value, v T) { + m.byPos[key.Pos()] = true + m.byPath[key.Path().String()] = v +} + +func (m *valueMap[T]) get(key cue.Value) T { + if !m.byPos[key.Pos()] { + return *new(T) + } + return m.byPath[key.Path().String()] +} + +func (m *valueMap[T]) lookup(key cue.Value) (T, bool) { + if !m.byPos[key.Pos()] { + return *new(T), false + } + v, ok := m.byPath[key.Path().String()] + return v, ok +} diff --git a/vendor/cuelang.org/go/encoding/jsonschema/version.go b/vendor/cuelang.org/go/encoding/jsonschema/version.go new file mode 100644 index 0000000000..d6dc767208 --- /dev/null +++ b/vendor/cuelang.org/go/encoding/jsonschema/version.go @@ -0,0 +1,91 @@ +// Copyright 2024 CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package jsonschema + +import ( + "fmt" + "strings" +) + +//go:generate go run golang.org/x/tools/cmd/stringer -type=Version -linecomment + +type Version int + +const ( + VersionUnknown Version = iota // unknown + VersionDraft4 // http://json-schema.org/draft-04/schema# + // Note: draft 5 never existed and should not be used. + VersionDraft6 // http://json-schema.org/draft-06/schema# + VersionDraft7 // http://json-schema.org/draft-07/schema# + VersionDraft2019_09 // https://json-schema.org/draft/2019-09/schema + VersionDraft2020_12 // https://json-schema.org/draft/2020-12/schema + + numJSONSchemaVersions // unknown + + // Note: OpenAPI stands alone: it's not in the regular JSON Schema lineage. + VersionOpenAPI // OpenAPI 3.0 +) + +const openAPI = versionSet(1 << VersionOpenAPI) + +type versionSet int + +// allVersions includes all regular versions of JSON Schema. +// It does not include OpenAPI v3.0 +const allVersions = versionSet(1<= Version(len(_Version_index)-1) { + return "Version(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _Version_name[_Version_index[i]:_Version_index[i+1]] +} diff --git a/vendor/cuelang.org/go/encoding/openapi/build.go b/vendor/cuelang.org/go/encoding/openapi/build.go index bd8bb5fc48..7cb06fb76e 100644 --- a/vendor/cuelang.org/go/encoding/openapi/build.go +++ b/vendor/cuelang.org/go/encoding/openapi/build.go @@ -19,6 +19,7 @@ import ( "math" "path" "regexp" + "slices" "sort" "strings" @@ -28,7 +29,6 @@ import ( "cuelang.org/go/cue/token" "cuelang.org/go/internal" "cuelang.org/go/internal/core/adt" - internalvalue "cuelang.org/go/internal/value" ) type buildContext struct { @@ -45,7 +45,7 @@ type buildContext struct { descFunc func(v cue.Value) string fieldFilter *regexp.Regexp - schemas *OrderedMap + schemas *orderedMap // Track external schemas. externalRefs map[string]*externalType @@ -57,11 +57,6 @@ type buildContext struct { // TODO: consider an option in the CUE API where optional fields are // recursively evaluated. cycleNodes []*adt.Vertex - - // imports caches values as returned by cue.Value.ReferencePath - // for use by ReferenceFunc. It's only initialised when ReferenceFunc - // is non-nil. - imports map[cue.Value]*cue.Instance } type externalType struct { @@ -71,13 +66,10 @@ type externalType struct { value cue.Value } -type oaSchema = OrderedMap - type typeFunc func(b *builder, a cue.Value) func schemas(g *Generator, inst cue.InstanceOrValue) (schemas *ast.StructLit, err error) { val := inst.Value() - _, isInstance := inst.(*cue.Instance) var fieldFilter *regexp.Regexp if g.FieldFilter != "" { fieldFilter, err = regexp.Compile(g.FieldFilter) @@ -107,41 +99,10 @@ func schemas(g *Generator, inst cue.InstanceOrValue) (schemas *ast.StructLit, er structural: g.ExpandReferences, nameFunc: g.NameFunc, descFunc: g.DescriptionFunc, - schemas: &OrderedMap{}, + schemas: &orderedMap{}, externalRefs: map[string]*externalType{}, fieldFilter: fieldFilter, } - if g.ReferenceFunc != nil { - if !isInstance { - panic("cannot use ReferenceFunc along with cue.Value") - } - if g.NameFunc != nil { - panic("cannot specify both ReferenceFunc and NameFunc") - } - - c.nameFunc = func(val cue.Value, path cue.Path) string { - sels := path.Selectors() - labels := make([]string, len(sels)) - for i, sel := range sels { - labels[i] = selectorLabel(sel) // TODO this is arguably incorrect. - } - inst, ok := c.imports[val] - if !ok { - r, n := internalvalue.ToInternal(val) - buildInst := r.GetInstanceFromNode(n) - var err error - inst, err = (*cue.Runtime)(r).Build(buildInst) - if err != nil { - panic("cannot build instance from value") - } - if c.imports == nil { - c.imports = make(map[cue.Value]*cue.Instance) - } - c.imports[val] = inst - } - return g.ReferenceFunc(inst, labels) - } - } switch g.Version { case "3.0.0": @@ -180,7 +141,7 @@ func schemas(g *Generator, inst cue.InstanceOrValue) (schemas *ast.StructLit, er if ref == "" { continue } - c.schemas.Set(ref, c.build(sel, i.Value())) + c.schemas.setExpr(ref, c.build(sel, i.Value())) } // keep looping until a fixed point is reached. @@ -192,7 +153,7 @@ func schemas(g *Generator, inst cue.InstanceOrValue) (schemas *ast.StructLit, er for k := range c.externalRefs { external = append(external, k) } - sort.Strings(external) + slices.Sort(external) for _, k := range external { ext := c.externalRefs[k] @@ -201,7 +162,7 @@ func schemas(g *Generator, inst cue.InstanceOrValue) (schemas *ast.StructLit, er last := len(sels) - 1 c.path = sels[:last] name := sels[last] - c.schemas.Set(ext.ref, c.build(name, cue.Dereference(ext.value))) + c.schemas.setExpr(ext.ref, c.build(name, cue.Dereference(ext.value))) } } @@ -418,7 +379,7 @@ func (b *builder) value(v cue.Value, f typeFunc) (isRef bool) { default: a := appendSplit(nil, cue.OrOp, v) for i, v := range a { - if _, r := v.Reference(); len(r) == 0 { + if _, r := v.ReferencePath(); len(r.Selectors()) == 0 { a[i] = v.Eval() } } @@ -526,13 +487,8 @@ func isConcrete(v cue.Value) bool { if !v.IsConcrete() { return false } - if v.Kind() == cue.StructKind { - return false // TODO: handle struct kinds - } - for list, _ := v.List(); list.Next(); { - if !isConcrete(list.Value()) { - return false - } + if v.Kind() == cue.StructKind || v.Kind() == cue.ListKind { + return false // TODO: handle struct and list kinds } return true } @@ -753,19 +709,19 @@ func (b *builder) object(v cue.Value) { required := []ast.Expr{} for i, _ := v.Fields(); i.Next(); { - required = append(required, ast.NewString(i.Label())) + required = append(required, ast.NewString(i.Selector().Unquoted())) } if len(required) > 0 { b.setFilter("Schema", "required", ast.NewList(required...)) } - var properties *OrderedMap + var properties *orderedMap if b.singleFields != nil { properties = b.singleFields.getMap("properties") } hasProps := properties != nil if !hasProps { - properties = &OrderedMap{} + properties = &orderedMap{} } for i, _ := v.Fields(cue.Optional(true), cue.Definitions(true)); i.Next(); { @@ -785,9 +741,9 @@ func (b *builder) object(v cue.Value) { if ref == "" { continue } - b.ctx.schemas.Set(ref, schema) + b.ctx.schemas.setExpr(ref, schema) case !b.isNonCore() || len(schema.Elts) > 0: - properties.Set(label, schema) + properties.setExpr(label, schema) } } @@ -795,7 +751,7 @@ func (b *builder) object(v cue.Value) { b.setSingle("properties", (*ast.StructLit)(properties), false) } - if t, ok := v.Elem(); ok && + if t := v.LookupPath(cue.MakePath(cue.AnyString)); t.Exists() && (b.core == nil || b.core.items == nil) && b.checkCycle(t) { schema := b.schema(nil, cue.AnyString, t) if len(schema.Elts) > 0 { @@ -897,7 +853,7 @@ func (b *builder) array(v cue.Value) { } if !hasMax || int64(len(items)) < maxLength { - if typ, ok := v.Elem(); ok && b.checkCycle(typ) { + if typ := v.LookupPath(cue.MakePath(cue.AnyIndex)); typ.Exists() && b.checkCycle(typ) { var core *builder if b.core != nil { core = b.core.items @@ -1110,8 +1066,8 @@ type builder struct { ctx *buildContext typ string format string - singleFields *oaSchema - current *oaSchema + singleFields *orderedMap + current *orderedMap allOf []*ast.StructLit deprecated bool @@ -1156,17 +1112,17 @@ func (b *builder) setType(t, format string) { } } -func setType(t *oaSchema, b *builder) { +func setType(t *orderedMap, b *builder) { if b.typ != "" { if b.core == nil || (b.core.typ != b.typ && !b.ctx.structural) { if !t.exists("type") { - t.Set("type", ast.NewString(b.typ)) + t.setExpr("type", ast.NewString(b.typ)) } } } if b.format != "" { if b.core == nil || b.core.format != b.format { - t.Set("format", ast.NewString(b.format)) + t.setExpr("format", ast.NewString(b.format)) } } } @@ -1182,25 +1138,25 @@ func (b *builder) setFilter(schema, key string, v ast.Expr) { // setSingle sets a value of which there should only be one. func (b *builder) setSingle(key string, v ast.Expr, drop bool) { if b.singleFields == nil { - b.singleFields = &OrderedMap{} + b.singleFields = &orderedMap{} } if b.singleFields.exists(key) { if !drop { b.failf(cue.Value{}, "more than one value added for key %q", key) } } - b.singleFields.Set(key, v) + b.singleFields.setExpr(key, v) } func (b *builder) set(key string, v ast.Expr) { if b.current == nil { - b.current = &OrderedMap{} + b.current = &orderedMap{} b.allOf = append(b.allOf, (*ast.StructLit)(b.current)) } else if b.current.exists(key) { - b.current = &OrderedMap{} + b.current = &orderedMap{} b.allOf = append(b.allOf, (*ast.StructLit)(b.current)) } - b.current.Set(key, v) + b.current.setExpr(key, v) } func (b *builder) kv(key string, value ast.Expr) *ast.StructLit { @@ -1212,14 +1168,14 @@ func (b *builder) setNot(key string, value ast.Expr) { } func (b *builder) finish() *ast.StructLit { - var t *OrderedMap + var t *orderedMap if b.filled != nil { return b.filled } switch len(b.allOf) { case 0: - t = &OrderedMap{} + t = &orderedMap{} case 1: hasRef := false @@ -1230,7 +1186,7 @@ func (b *builder) finish() *ast.StructLit { } } if !hasRef || b.singleFields == nil { - t = (*OrderedMap)(b.allOf[0]) + t = (*orderedMap)(b.allOf[0]) break } fallthrough @@ -1240,15 +1196,15 @@ func (b *builder) finish() *ast.StructLit { for _, s := range b.allOf { exprs = append(exprs, s) } - t = &OrderedMap{} - t.Set("allOf", ast.NewList(exprs...)) + t = &orderedMap{} + t.setExpr("allOf", ast.NewList(exprs...)) } if b.singleFields != nil { b.singleFields.Elts = append(b.singleFields.Elts, t.Elts...) t = b.singleFields } if b.deprecated { - t.Set("deprecated", ast.NewBool(true)) + t.setExpr("deprecated", ast.NewBool(true)) } setType(t, b) sortSchema((*ast.StructLit)(t)) diff --git a/vendor/cuelang.org/go/encoding/openapi/crd.go b/vendor/cuelang.org/go/encoding/openapi/crd.go index 1c04a5b5b1..9c9e2634fd 100644 --- a/vendor/cuelang.org/go/encoding/openapi/crd.go +++ b/vendor/cuelang.org/go/encoding/openapi/crd.go @@ -74,10 +74,10 @@ func (b *builder) coreSchema() *ast.StructLit { } case cue.StructKind: - p := &OrderedMap{} + p := &orderedMap{} for _, k := range b.keys { sub := b.properties[k] - p.Set(k, sub.coreSchemaWithName(cue.Str(k))) + p.setExpr(k, sub.coreSchemaWithName(cue.Str(k))) } if p.len() > 0 || b.items != nil { b.setType("object", "") @@ -113,8 +113,8 @@ func (b *builder) buildCore(v cue.Value) { defer b.popNode() if !b.ctx.expandRefs { - _, r := v.Reference() - if len(r) > 0 { + _, r := v.ReferencePath() + if len(r.Selectors()) > 0 { return } } @@ -128,7 +128,7 @@ func (b *builder) buildCore(v cue.Value) { switch b.kind { case cue.StructKind: - if typ, ok := v.Elem(); ok { + if typ := v.LookupPath(cue.MakePath(cue.AnyString)); typ.Exists() { if !b.checkCycle(typ) { return } @@ -140,7 +140,7 @@ func (b *builder) buildCore(v cue.Value) { b.buildCoreStruct(v) case cue.ListKind: - if typ, ok := v.Elem(); ok { + if typ := v.LookupPath(cue.MakePath(cue.AnyIndex)); typ.Exists() { if !b.checkCycle(typ) { return } @@ -169,7 +169,7 @@ func (b *builder) buildCoreStruct(v cue.Value) { } } for i, _ := v.Fields(cue.Optional(true), cue.Hidden(false)); i.Next(); { - label := i.Label() + label := i.Selector().Unquoted() sub, ok := b.properties[label] if !ok { sub = newCoreBuilder(b.ctx) diff --git a/vendor/cuelang.org/go/encoding/openapi/decode.go b/vendor/cuelang.org/go/encoding/openapi/decode.go index d60e82d686..279610fa0c 100644 --- a/vendor/cuelang.org/go/encoding/openapi/decode.go +++ b/vendor/cuelang.org/go/encoding/openapi/decode.go @@ -15,6 +15,7 @@ package openapi import ( + "fmt" "strings" "cuelang.org/go/cue" @@ -41,15 +42,28 @@ func Extract(data cue.InstanceOrValue, c *Config) (*ast.File, error) { } } - js, err := jsonschema.Extract(data, &jsonschema.Config{ - Root: oapiSchemas, - Map: openAPIMapping, - }) + v := data.Value() + versionValue := v.LookupPath(cue.MakePath(cue.Str("openapi"))) + if versionValue.Err() != nil { + return nil, fmt.Errorf("openapi field is required but not found") + } + version, err := versionValue.String() if err != nil { - return nil, err + return nil, fmt.Errorf("invalid openapi field (must be string): %v", err) + } + // A simple prefix match is probably OK for now, following + // the same logic used by internal/encoding.isOpenAPI. + // The specification says that the patch version should be disregarded: + // https://swagger.io/specification/v3/ + var schemaVersion jsonschema.Version + switch { + case strings.HasPrefix(version, "3.0."): + schemaVersion = jsonschema.VersionOpenAPI + case strings.HasPrefix(version, "3.1."): + schemaVersion = jsonschema.VersionDraft2020_12 + default: + return nil, fmt.Errorf("unknown OpenAPI version %q", version) } - - v := data.Value() doc, _ := v.LookupPath(cue.MakePath(cue.Str("info"), cue.Str("title"))).String() // Required if s, _ := v.LookupPath(cue.MakePath(cue.Str("info"), cue.Str("description"))).String(); s != "" { @@ -61,10 +75,21 @@ func Extract(data cue.InstanceOrValue, c *Config) (*ast.File, error) { p := &ast.Package{Name: ast.NewIdent(c.PkgName)} p.AddComment(cg) add(p) - } else { + } else if cg != nil { add(cg) } + js, err := jsonschema.Extract(data, &jsonschema.Config{ + Root: oapiSchemas, + Map: openAPIMapping, + DefaultVersion: schemaVersion, + StrictFeatures: c.StrictFeatures, + // OpenAPI 3.0 is stricter than JSON Schema about allowed keywords. + StrictKeywords: schemaVersion == jsonschema.VersionOpenAPI || c.StrictKeywords, + }) + if err != nil { + return nil, err + } preamble := js.Preamble() body := js.Decls[len(preamble):] for _, d := range preamble { diff --git a/vendor/cuelang.org/go/encoding/openapi/openapi.go b/vendor/cuelang.org/go/encoding/openapi/openapi.go index 49d71cd490..f4efc39791 100644 --- a/vendor/cuelang.org/go/encoding/openapi/openapi.go +++ b/vendor/cuelang.org/go/encoding/openapi/openapi.go @@ -36,16 +36,6 @@ type Config struct { // Info may be a *ast.StructLit or any type that marshals to JSON. Info interface{} - // ReferenceFunc allows users to specify an alternative representation - // for references. An empty string tells the generator to expand the type - // in place and, if applicable, not generate a schema for that entity. - // - // If this field is non-nil and a cue.Value is passed as the InstanceOrValue, - // there will be a panic. - // - // Deprecated: use NameFunc instead. - ReferenceFunc func(inst *cue.Instance, path []string) string - // NameFunc allows users to specify an alternative representation // for references. It is called with the value passed to the top level // method or function and the path to the entity being generated. @@ -81,6 +71,16 @@ type Config struct { // OpenAPI Schema. It is an error for an CUE value to refer to itself // if this option is used. ExpandReferences bool + + // StrictFeatures reports an error for features that are known + // to be unsupported. + StrictFeatures bool + + // StrictKeywords reports an error when unknown keywords + // are encountered. For OpenAPI 3.0, this is implicitly always + // true, as that specification explicitly prohibits unknown keywords + // other than "x-" prefixed keywords. + StrictKeywords bool } type Generator = Config @@ -91,11 +91,19 @@ func Gen(inst cue.InstanceOrValue, c *Config) ([]byte, error) { if c == nil { c = defaultConfig } - all, err := c.All(inst) + all, err := schemas(c, inst) if err != nil { return nil, err } - return internaljson.Marshal(all) + top, err := c.compose(inst, all) + if err != nil { + return nil, err + } + topValue := inst.Value().Context().BuildExpr(top) + if err := topValue.Err(); err != nil { + return nil, err + } + return internaljson.Marshal(topValue) } // Generate generates the set of OpenAPI schema for all top-level types of the @@ -103,6 +111,9 @@ func Gen(inst cue.InstanceOrValue, c *Config) ([]byte, error) { // // Note: only a limited number of top-level types are supported so far. func Generate(inst cue.InstanceOrValue, c *Config) (*ast.File, error) { + if c == nil { + c = defaultConfig + } all, err := schemas(c, inst) if err != nil { return nil, err @@ -114,19 +125,6 @@ func Generate(inst cue.InstanceOrValue, c *Config) (*ast.File, error) { return &ast.File{Decls: top.Elts}, nil } -// All generates an OpenAPI definition from the given instance. -// -// Note: only a limited number of top-level types are supported so far. -// Deprecated: use Generate -func (g *Generator) All(inst cue.InstanceOrValue) (*OrderedMap, error) { - all, err := schemas(g, inst) - if err != nil { - return nil, err - } - top, err := g.compose(inst, all) - return (*OrderedMap)(top), err -} - func toCUE(name string, x interface{}) (v ast.Expr, err error) { b, err := internaljson.Marshal(x) if err == nil { @@ -147,11 +145,8 @@ func (c *Config) compose(inst cue.InstanceOrValue, schemas *ast.StructLit) (x *a var title, version string var info *ast.StructLit - for i, _ := val.Fields(cue.Definitions(true)); i.Next(); { - if i.IsDefinition() { - continue - } - label := i.Label() + for i, _ := val.Fields(); i.Next(); { + label := i.Selector().Unquoted() attr := i.Value().Attribute("openapi") if s, _ := attr.String(0); s != "" { label = s @@ -174,7 +169,6 @@ func (c *Config) compose(inst cue.InstanceOrValue, schemas *ast.StructLit) (x *a } } - // Support of OrderedMap is mostly for backwards compatibility. switch x := c.Info.(type) { case nil: if title == "" { @@ -198,17 +192,13 @@ func (c *Config) compose(inst cue.InstanceOrValue, schemas *ast.StructLit) (x *a "version", ast.NewString(version), ) } else { - m := (*OrderedMap)(info) - m.Set("title", ast.NewString(title)) - m.Set("version", ast.NewString(version)) + m := (*orderedMap)(info) + m.setExpr("title", ast.NewString(title)) + m.setExpr("version", ast.NewString(version)) } case *ast.StructLit: info = x - case *OrderedMap: - info = (*ast.StructLit)(x) - case OrderedMap: - info = (*ast.StructLit)(&x) default: x, err := toCUE("info section", x) if err != nil { @@ -230,15 +220,6 @@ func (c *Config) compose(inst cue.InstanceOrValue, schemas *ast.StructLit) (x *a ), errs } -// Schemas extracts component/schemas from the CUE top-level types. -func (g *Generator) Schemas(inst cue.InstanceOrValue) (*OrderedMap, error) { - comps, err := schemas(g, inst) - if err != nil { - return nil, err - } - return (*OrderedMap)(comps), err -} - var defaultConfig = &Config{} // TODO diff --git a/vendor/cuelang.org/go/encoding/openapi/orderedmap.go b/vendor/cuelang.org/go/encoding/openapi/orderedmap.go index 22966841b7..d6ddf53450 100644 --- a/vendor/cuelang.org/go/encoding/openapi/orderedmap.go +++ b/vendor/cuelang.org/go/encoding/openapi/orderedmap.go @@ -15,91 +15,22 @@ package openapi import ( - "fmt" - "cuelang.org/go/cue/ast" - "cuelang.org/go/cue/literal" - "cuelang.org/go/cue/token" - internaljson "cuelang.org/go/internal/encoding/json" ) -// An OrderedMap is a set of key-value pairs that preserves the order in which -// items were added. It marshals to JSON as an object. +// An orderedMap is a set of key-value pairs that preserves the order in which +// items were added. // // Deprecated: the API now returns an ast.File. This allows OpenAPI to be // represented as JSON, YAML, or CUE data, in addition to being able to use // all the ast-related tooling. -type OrderedMap ast.StructLit - -// KeyValue associates a value with a key. -type KeyValue struct { - Key string - Value interface{} -} - -// TODO: these functions are here to support backwards compatibility with Istio. -// At some point, once this is removed from Istio, this can be removed. - -func fromLegacy(x interface{}) ast.Expr { - switch x := x.(type) { - case *OrderedMap: - return (*ast.StructLit)(x) - case []*OrderedMap: - a := make([]ast.Expr, len(x)) - for i, v := range x { - a[i] = fromLegacy(v) - } - return ast.NewList(a...) - case string: - return ast.NewString(x) - case ast.Expr: - return x - default: - panic(fmt.Sprintf("unsupported type %T", x)) - } -} - -func toLegacy(x ast.Expr) interface{} { - switch x := x.(type) { - case *ast.StructLit: - return (*OrderedMap)(x) - case *ast.ListLit: - a := make([]*OrderedMap, len(x.Elts)) - for i, v := range x.Elts { - e, ok := v.(*ast.StructLit) - if !ok { - return x - } - a[i] = (*OrderedMap)(e) - } - return a - case *ast.BasicLit: - if x.Kind == token.STRING { - str, err := literal.Unquote(x.Value) - if err != nil { - return x - } - return str - } - } - return x -} +type orderedMap ast.StructLit -func (m *OrderedMap) len() int { +func (m *orderedMap) len() int { return len(m.Elts) } -// Pairs returns the KeyValue pairs associated with m. -func (m *OrderedMap) Pairs() []KeyValue { - kvs := make([]KeyValue, len(m.Elts)) - for i, e := range m.Elts { - kvs[i].Key = label(e) - kvs[i].Value = toLegacy(e.(*ast.Field).Value) - } - return kvs -} - -func (m *OrderedMap) find(key string) *ast.Field { +func (m *orderedMap) find(key string) *ast.Field { for _, v := range m.Elts { f, ok := v.(*ast.Field) if !ok { @@ -113,29 +44,7 @@ func (m *OrderedMap) find(key string) *ast.Field { return nil } -// Set sets a key value pair. If a pair with the same key already existed, it -// will be replaced with the new value. Otherwise, the new value is added to -// the end. The value must be of type string, ast.Expr, or *OrderedMap. -// -// Deprecated: use cuelang.org/go/cue/ast to manipulate ASTs. -func (m *OrderedMap) Set(key string, x interface{}) { - switch x := x.(type) { - case *OrderedMap: - m.setExpr(key, (*ast.StructLit)(x)) - case string: - m.setExpr(key, ast.NewString(x)) - case ast.Expr: - m.setExpr(key, x) - default: - v, err := toCUE("Set", x) - if err != nil { - panic(err) - } - m.setExpr(key, v) - } -} - -func (m *OrderedMap) setExpr(key string, expr ast.Expr) { +func (m *orderedMap) setExpr(key string, expr ast.Expr) { if f := m.find(key); f != nil { f.Value = expr return @@ -146,36 +55,16 @@ func (m *OrderedMap) setExpr(key string, expr ast.Expr) { }) } -// SetAll replaces existing key-value pairs with the given ones. The keys must -// be unique. -func (m *OrderedMap) SetAll(kvs []KeyValue) { - var a []ast.Decl - for _, kv := range kvs { - a = append(a, &ast.Field{ - Label: ast.NewString(kv.Key), - Value: fromLegacy(kv.Value), - }) - } - m.Elts = a -} - // exists reports whether a key-value pair exists for the given key. -func (m *OrderedMap) exists(key string) bool { +func (m *orderedMap) exists(key string) bool { return m.find(key) != nil } // exists reports whether a key-value pair exists for the given key. -func (m *OrderedMap) getMap(key string) *OrderedMap { +func (m *orderedMap) getMap(key string) *orderedMap { f := m.find(key) if f == nil { return nil } - return (*OrderedMap)(f.Value.(*ast.StructLit)) -} - -// MarshalJSON implements json.Marshaler. -func (m *OrderedMap) MarshalJSON() (b []byte, err error) { - // This is a pointer receiever to enforce that we only store pointers to - // OrderedMap in the output. - return internaljson.Encode((*ast.StructLit)(m)) + return (*orderedMap)(f.Value.(*ast.StructLit)) } diff --git a/vendor/cuelang.org/go/encoding/protobuf/pbinternal/attribute.go b/vendor/cuelang.org/go/encoding/protobuf/pbinternal/attribute.go index e3d36bd1be..54a1949586 100644 --- a/vendor/cuelang.org/go/encoding/protobuf/pbinternal/attribute.go +++ b/vendor/cuelang.org/go/encoding/protobuf/pbinternal/attribute.go @@ -60,7 +60,7 @@ type Info struct { } func FromIter(i *cue.Iterator) (info Info, err error) { - return FromValue(i.Label(), i.Value()) + return FromValue(i.Selector().Unquoted(), i.Value()) } func FromValue(name string, v cue.Value) (info Info, err error) { diff --git a/vendor/cuelang.org/go/encoding/protobuf/protobuf.go b/vendor/cuelang.org/go/encoding/protobuf/protobuf.go index efb7924e80..477f98a93e 100644 --- a/vendor/cuelang.org/go/encoding/protobuf/protobuf.go +++ b/vendor/cuelang.org/go/encoding/protobuf/protobuf.go @@ -216,7 +216,7 @@ func NewExtractor(c *Config) *Extractor { } // Err returns the errors accumulated during testing. The returned error may be -// of type cuelang.org/go/cue/errors.List. +// of type [errors.List]. func (b *Extractor) Err() error { return b.errs } @@ -402,7 +402,7 @@ func (b *Extractor) getInst(p *protoConverter) *build.Instance { // Extract parses a single proto file and returns its contents translated to a CUE // file. If src is not nil, it will use this as the contents of the file. It may -// be a string, []byte or io.Reader. Otherwise Extract will open the given file +// be a string, []byte or [io.Reader]. Otherwise Extract will open the given file // name at the fully qualified path. // // Extract assumes the proto file compiles with protoc and may not report an error diff --git a/vendor/cuelang.org/go/encoding/protobuf/textproto/decoder.go b/vendor/cuelang.org/go/encoding/protobuf/textproto/decoder.go index e917342d30..01f63efc16 100644 --- a/vendor/cuelang.org/go/encoding/protobuf/textproto/decoder.go +++ b/vendor/cuelang.org/go/encoding/protobuf/textproto/decoder.go @@ -39,14 +39,14 @@ type Option func(*options) type options struct { } -// NewDecoder returns a new Decoder +// NewDecoder returns a new [Decoder]. func NewDecoder(option ...Option) *Decoder { d := &Decoder{} _ = d.m // work around linter bug. return d } -// A Decoder caches conversions of cue.Value between calls to its methods. +// A Decoder caches conversions of [cue.Value] between calls to its methods. type Decoder struct { m map[*adt.Vertex]*mapping } @@ -143,7 +143,7 @@ func (d *decoder) parseSchema(schema cue.Value) *mapping { m := &mapping{children: map[string]*fieldInfo{}} - i, err := schema.Fields() + i, err := schema.Fields(cue.Optional(true)) if err != nil { d.addErr(err) return nil @@ -393,7 +393,7 @@ func (d *decoder) decodeValue(f *fieldInfo, n *pbast.Node) (x ast.Expr) { switch f.ValueType { case pbinternal.String, pbinternal.Bytes: - s, err := unquote.Unquote(n) + s, _, err := unquote.Unquote(n) if err != nil { d.addErrf(n.Start, "invalid string or bytes: %v", err) } diff --git a/vendor/cuelang.org/go/encoding/protobuf/textproto/encoder.go b/vendor/cuelang.org/go/encoding/protobuf/textproto/encoder.go index 787b45148d..7994089898 100644 --- a/vendor/cuelang.org/go/encoding/protobuf/textproto/encoder.go +++ b/vendor/cuelang.org/go/encoding/protobuf/textproto/encoder.go @@ -118,11 +118,11 @@ func (e *encoder) encodeMsg(parent *pbast.Node, v cue.Value) { var key *pbast.Node switch info.KeyType { case pbinternal.String, pbinternal.Bytes: - key = pbast.StringNode("key", i.Label()) + key = pbast.StringNode("key", i.Selector().Unquoted()) default: key = &pbast.Node{ Name: "key", - Values: []*pbast.Value{{Value: i.Label()}}, + Values: []*pbast.Value{{Value: i.Selector().Unquoted()}}, } } n.Children = append(n.Children, key) diff --git a/vendor/cuelang.org/go/encoding/toml/decode.go b/vendor/cuelang.org/go/encoding/toml/decode.go new file mode 100644 index 0000000000..8c7da995a7 --- /dev/null +++ b/vendor/cuelang.org/go/encoding/toml/decode.go @@ -0,0 +1,508 @@ +// Copyright 2024 The CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package toml converts TOML to and from CUE. +// +// WARNING: THIS PACKAGE IS EXPERIMENTAL. +// ITS API MAY CHANGE AT ANY TIME. +package toml + +import ( + "fmt" + "io" + "strconv" + "strings" + "time" + + toml "github.com/pelletier/go-toml/v2/unstable" + + "cuelang.org/go/cue/ast" + "cuelang.org/go/cue/errors" + "cuelang.org/go/cue/literal" + "cuelang.org/go/cue/token" +) + +// TODO(mvdan): schema and decode options + +// NewDecoder creates a decoder from a stream of TOML input. +func NewDecoder(filename string, r io.Reader) *Decoder { + // Note that we don't consume the reader here, + // as there's no need, and we can't return an error either. + return &Decoder{r: r, filename: filename, seenTableKeys: make(map[string]bool)} +} + +// Decoder implements the decoding state. +// +// Note that TOML files and streams never decode multiple CUE nodes; +// subsequent calls to [Decoder.Decode] may return [io.EOF]. +type Decoder struct { + r io.Reader + + filename string + + decoded bool // whether [Decoder.Decoded] has been called already + parser toml.Parser + + // seenTableKeys tracks which rooted keys we have already decoded as tables, + // as duplicate table keys in TOML are not allowed. + seenTableKeys map[rootedKey]bool + + // topFile is the top-level CUE file we are decoding into. + // TODO(mvdan): make an *ast.File once the decoder returns ast.Node rather than ast.Expr. + topFile *ast.StructLit + + // tokenFile is used to create positions which can be used for error values and syntax tree nodes. + tokenFile *token.File + + // openTableArrays keeps track of all the declared table arrays so that + // later headers can append a new table array element, or add a field + // to the last element in a table array. + // + // TODO(mvdan): an unsorted slice means we do two linear searches per header key. + // For N distinct `[[keys]]`, this means a decoding runtime of O(2*N*N). + // Consider either sorting this array so we can do a binary search for O(N*log2(N)), + // or perhaps a tree, although for a nesting level D, that could cause O(N*D), + // and a tree would use more slices and so more allocations. + // + // Note that a map is not a good option either, because even though it makes + // exact lookups cheap, prefix matches are still linear and relatively slow. + // A sorted slice allows both mechanisms to use a form of binary search. + openTableArrays []openTableArray + + // currentTableKey is the rooted key for the current table where the following + // TOML `key = value` lines will be inserted. + currentTableKey rootedKey + + // currentTable is the CUE struct literal for currentTableKey. + // It is nil before the first [header] or [[header]], + // in which case any key-values are inserted in topFile. + currentTable *ast.StructLit +} + +// rootedKey is a dot-separated path from the root of the TOML document. +// The string elements in between the dots may be quoted to avoid ambiguity. +// For the time being, this is just an alias for the sake of documentation. +// +// A path into an array element is like "arr.3", +// which looks very similar to a table's "tbl.key", +// particularly since a table key can be any string. +// However, we just need these keys to detect duplicates, +// and a path cannot be both an array and table, so it's OK. +type rootedKey = string + +// openTableArray records information about a declared table array. +type openTableArray struct { + rkey rootedKey + level int // the level of nesting, 1 or higher, e.g. 2 for key="foo.bar" + list *ast.ListLit + lastTable *ast.StructLit +} + +// TODO(mvdan): support decoding comments + +// Decode parses the input stream as TOML and converts it to a CUE [*ast.File]. +// Because TOML files only contain a single top-level expression, +// subsequent calls to this method may return [io.EOF]. +func (d *Decoder) Decode() (ast.Expr, error) { + if d.decoded { + return nil, io.EOF + } + d.decoded = true + // TODO(mvdan): unfortunately go-toml does not support streaming as of v2.2.2. + data, err := io.ReadAll(d.r) + if err != nil { + return nil, err + } + d.tokenFile = token.NewFile(d.filename, 0, len(data)) + d.tokenFile.SetLinesForContent(data) + d.parser.Reset(data) + // Note that if the input is empty the result will be the same + // as for an empty table: an empty struct. + // The TOML spec and other decoders also work this way. + d.topFile = &ast.StructLit{} + for d.parser.NextExpression() { + if err := d.nextRootNode(d.parser.Expression()); err != nil { + return nil, err + } + } + if err := d.parser.Error(); err != nil { + if err, ok := err.(*toml.ParserError); ok { + shape := d.parser.Shape(d.parser.Range(err.Highlight)) + return nil, d.posErrf(shape.Start, "%s", err.Message) + } + return nil, err + } + return d.topFile, nil +} + +func (d *Decoder) shape(tnode *toml.Node) toml.Shape { + if tnode.Raw.Length == 0 { + // Otherwise the Shape method call below happily returns a position like 1:1, + // which is worse than no position information as it confuses the user. + panic("Decoder.nodePos was given an empty toml.Node as position") + } + return d.parser.Shape(tnode.Raw) +} + +func (d *Decoder) nodeErrf(tnode *toml.Node, format string, args ...any) error { + return d.posErrf(d.shape(tnode).Start, format, args...) +} + +func (d *Decoder) posErrf(pos toml.Position, format string, args ...any) error { + return errors.Newf(d.tokenFile.Pos(pos.Offset, token.NoRelPos), format, args...) +} + +// nextRootNode is called for every top-level expression from the TOML parser. +// +// This method does not return a syntax tree node directly, +// because some kinds of top-level expressions like comments and table headers +// require recording some state in the decoder to produce a node at a later time. +func (d *Decoder) nextRootNode(tnode *toml.Node) error { + switch tnode.Kind { + // Key-Values in TOML are in the form of: + // + // foo.title = "Foo" + // foo.bar.baz = "value" + // + // We decode them as "inline" structs in CUE, which keeps the original shape: + // + // foo: title: "Foo" + // foo: bar: baz: "value" + // + // An alternative would be to join struct literals, which avoids some repetition, + // but also introduces extra lines and may break some comment positions: + // + // foo: { + // title: "Foo" + // bar: baz: "value" + // } + case toml.KeyValue: + // Top-level fields begin a new line. + field, err := d.decodeField(d.currentTableKey, tnode, token.Newline) + if err != nil { + return err + } + if d.currentTable != nil { + d.currentTable.Elts = append(d.currentTable.Elts, field) + } else { + d.topFile.Elts = append(d.topFile.Elts, field) + } + + case toml.Table: + // Tables always begin a new line. + key, keyElems := d.decodeKey("", tnode.Key()) + // All table keys must be unique, including for the top-level table. + if d.seenTableKeys[key] { + return d.nodeErrf(tnode.Child(), "duplicate key: %s", key) + } + d.seenTableKeys[key] = true + + // We want a multi-line struct with curly braces, + // just like TOML's tables are on multiple lines. + d.currentTable = &ast.StructLit{ + // No positions, as TOML doesn't have table delimiters. + Lbrace: token.NoPos.WithRel(token.Blank), + Rbrace: token.NoPos.WithRel(token.Newline), + } + array := d.findArrayPrefix(key) + if array != nil { // [last_array.new_table] + if array.rkey == key { + return d.nodeErrf(tnode.Child(), "cannot redeclare table array %q as a table", key) + } + subKeyElems := keyElems[array.level:] + topField, leafField := d.inlineFields(subKeyElems, token.Newline) + array.lastTable.Elts = append(array.lastTable.Elts, topField) + leafField.Value = d.currentTable + } else { // [new_table] + topField, leafField := d.inlineFields(keyElems, token.Newline) + d.topFile.Elts = append(d.topFile.Elts, topField) + leafField.Value = d.currentTable + } + d.currentTableKey = key + + case toml.ArrayTable: + // Table array elements always begin a new line. + key, keyElems := d.decodeKey("", tnode.Key()) + if d.seenTableKeys[key] { + return d.nodeErrf(tnode.Child(), "cannot redeclare key %q as a table array", key) + } + // Each struct inside a table array sits on separate lines. + d.currentTable = &ast.StructLit{ + // No positions, as TOML doesn't have table delimiters. + Lbrace: token.NoPos.WithRel(token.Newline), + Rbrace: token.NoPos.WithRel(token.Newline), + } + if array := d.findArrayPrefix(key); array != nil && array.level == len(keyElems) { + // [[last_array]] - appending to an existing array. + d.currentTableKey = key + "." + strconv.Itoa(len(array.list.Elts)) + array.lastTable = d.currentTable + array.list.Elts = append(array.list.Elts, d.currentTable) + } else { + // Creating a new array via either [[new_array]] or [[last_array.new_array]]. + // We want a multi-line list with square braces, + // since TOML's table arrays are on multiple lines. + list := &ast.ListLit{ + // No positions, as TOML doesn't have array table delimiters. + Lbrack: token.NoPos.WithRel(token.Blank), + Rbrack: token.NoPos.WithRel(token.Newline), + } + if array == nil { + // [[new_array]] - at the top level + topField, leafField := d.inlineFields(keyElems, token.Newline) + d.topFile.Elts = append(d.topFile.Elts, topField) + leafField.Value = list + } else { + // [[last_array.new_array]] - on the last array element + subKeyElems := keyElems[array.level:] + topField, leafField := d.inlineFields(subKeyElems, token.Newline) + array.lastTable.Elts = append(array.lastTable.Elts, topField) + leafField.Value = list + } + + d.currentTableKey = key + ".0" + list.Elts = append(list.Elts, d.currentTable) + d.openTableArrays = append(d.openTableArrays, openTableArray{ + rkey: key, + level: len(keyElems), + list: list, + lastTable: d.currentTable, + }) + } + + default: + return fmt.Errorf("encoding/toml.Decoder.nextRootNode: unknown %s %#v", tnode.Kind, tnode) + } + return nil +} + +// decodeField decodes a single table key and its value as a struct field. +func (d *Decoder) decodeField(rkey rootedKey, tnode *toml.Node, relPos token.RelPos) (*ast.Field, error) { + rkey, keyElems := d.decodeKey(rkey, tnode.Key()) + if d.findArray(rkey) != nil { + return nil, d.nodeErrf(tnode.Child().Next(), "cannot redeclare table array %q as a table", rkey) + } + topField, leafField := d.inlineFields(keyElems, relPos) + // All table keys must be unique, including inner table ones. + if d.seenTableKeys[rkey] { + return nil, d.nodeErrf(tnode.Child().Next(), "duplicate key: %s", rkey) + } + d.seenTableKeys[rkey] = true + value, err := d.decodeExpr(rkey, tnode.Value()) + if err != nil { + return nil, err + } + leafField.Value = value + return topField, nil +} + +// findArray returns an existing table array if one exists at exactly the given key. +func (d *Decoder) findArray(rkey rootedKey) *openTableArray { + for i, arr := range d.openTableArrays { + if arr.rkey == rkey { + return &d.openTableArrays[i] + } + } + return nil +} + +// findArray returns an existing table array if one exists at exactly the given key +// or as a prefix to the given key. +func (d *Decoder) findArrayPrefix(rkey rootedKey) *openTableArray { + // TODO(mvdan): see the performance TODO on [Decoder.openTableArrays]. + + // Prefer an exact match over a relative prefix match. + if arr := d.findArray(rkey); arr != nil { + return arr + } + // The longest relative key match wins. + maxLevel := 0 + var maxLevelArr *openTableArray + for i, arr := range d.openTableArrays { + if strings.HasPrefix(rkey, arr.rkey+".") && arr.level > maxLevel { + maxLevel = arr.level + maxLevelArr = &d.openTableArrays[i] + } + } + if maxLevel > 0 { + return maxLevelArr + } + return nil +} + +// tomlKey represents a name with a position which forms part of a TOML dotted key, +// such as "foo" from "[foo.bar.baz]". +type tomlKey struct { + name string + shape toml.Shape +} + +// decodeKey extracts a rootedKey from a TOML node key iterator, +// appending to the given parent key and returning the unquoted string elements. +func (d *Decoder) decodeKey(rkey rootedKey, iter toml.Iterator) (rootedKey, []tomlKey) { + var elems []tomlKey + for iter.Next() { + node := iter.Node() + name := string(node.Data) + // TODO(mvdan): use an append-like API once we have benchmarks + if len(rkey) > 0 { + rkey += "." + } + rkey += quoteLabelIfNeeded(name) + elems = append(elems, tomlKey{name, d.shape(node)}) + } + return rkey, elems +} + +// inlineFields constructs a single-line chain of CUE fields joined with structs, +// so that an input like: +// +// ["foo", "bar.baz", "zzz"] +// +// results in the CUE fields: +// +// foo: "bar.baz": zzz: +// +// The "top" field, in this case "foo", can then be added as an element to a struct. +// The "leaf" field, in this case "zzz", leaves its value as nil to be filled out. +func (d *Decoder) inlineFields(tkeys []tomlKey, relPos token.RelPos) (top, leaf *ast.Field) { + curField := &ast.Field{ + Label: d.label(tkeys[0], relPos), + } + + topField := curField + for _, tkey := range tkeys[1:] { + nextField := &ast.Field{ + Label: d.label(tkey, token.Blank), // on the same line + } + curField.Value = &ast.StructLit{Elts: []ast.Decl{nextField}} + curField = nextField + } + return topField, curField +} + +// quoteLabelIfNeeded quotes a label name only if it needs quoting. +// +// TODO(mvdan): this exists in multiple packages; move to cue/literal or cue/ast? +func quoteLabelIfNeeded(name string) string { + if ast.IsValidIdent(name) { + return name + } + return literal.Label.Quote(name) +} + +// label creates an ast.Label that represents a key with exactly the literal string name. +// This means a quoted string literal for the key "_", as TOML never means "top", +// as well as for any keys beginning with an underscore, as we don't want to hide any fields. +// cue/format knows how to quote any other identifiers correctly. +func (d *Decoder) label(tkey tomlKey, relPos token.RelPos) ast.Label { + pos := d.tokenFile.Pos(tkey.shape.Start.Offset, relPos) + if strings.HasPrefix(tkey.name, "_") { + return &ast.BasicLit{ + ValuePos: pos, + Kind: token.STRING, + Value: literal.String.Quote(tkey.name), + } + } + return &ast.Ident{ + NamePos: pos, + Name: tkey.name, + } +} + +// decodeExpr decodes a single TOML value expression, found on the right side +// of a `key = value` line. +func (d *Decoder) decodeExpr(rkey rootedKey, tnode *toml.Node) (ast.Expr, error) { + // TODO(mvdan): we currently assume that TOML basic literals (string, int, float) + // are also valid CUE literals; we should double check this, perhaps via fuzzing. + data := string(tnode.Data) + var expr ast.Expr + switch tnode.Kind { + case toml.String: + expr = ast.NewString(data) + case toml.Integer: + expr = ast.NewLit(token.INT, data) + case toml.Float: + expr = ast.NewLit(token.FLOAT, data) + case toml.Bool: + expr = ast.NewBool(data == "true") + case toml.Array: + list := &ast.ListLit{} + elems := tnode.Children() + for elems.Next() { + key := rkey + "." + strconv.Itoa(len(list.Elts)) + elem, err := d.decodeExpr(key, elems.Node()) + if err != nil { + return nil, err + } + list.Elts = append(list.Elts, elem) + } + expr = list + case toml.InlineTable: + strct := &ast.StructLit{ + // We want a single-line struct, just like TOML's inline tables are on a single line. + Lbrace: token.NoPos.WithRel(token.Blank), + Rbrace: token.NoPos.WithRel(token.Blank), + } + elems := tnode.Children() + for elems.Next() { + // Inline table fields are on the same line. + field, err := d.decodeField(rkey, elems.Node(), token.Blank) + if err != nil { + return nil, err + } + strct.Elts = append(strct.Elts, field) + } + expr = strct + case toml.LocalDate, toml.LocalTime, toml.LocalDateTime, toml.DateTime: + // CUE does not have native date nor time literal kinds, + // so we decode these as strings exactly as they came in + // and we validate them with time.Format using the corresponding format string. + // Not only does this ensure that the resulting CUE can be used with our time package, + // but it also means that we can roundtrip a TOML timestamp without confusing it for a string. + var format ast.Expr + switch tnode.Kind { + case toml.LocalDate: + // TODO(mvdan): rename time.RFC3339Date to time.DateOnly to mirror Go + format = ast.NewSel(&ast.Ident{ + Name: "time", + Node: ast.NewImport(nil, "time"), + }, "RFC3339Date") + case toml.LocalTime: + // TODO(mvdan): add TimeOnly to CUE's time package to mirror Go + format = ast.NewString(time.TimeOnly) + case toml.LocalDateTime: + // RFC3339 minus the timezone; this seems like a format peculiar to TOML. + format = ast.NewString("2006-01-02T15:04:05") + default: // DateTime + format = ast.NewSel(&ast.Ident{ + Name: "time", + Node: ast.NewImport(nil, "time"), + }, "RFC3339") + } + expr = ast.NewBinExpr(token.AND, ast.NewString(data), ast.NewCall( + ast.NewSel(&ast.Ident{ + Name: "time", + Node: ast.NewImport(nil, "time"), + }, "Format"), format), + ) + default: + return nil, fmt.Errorf("encoding/toml.Decoder.decodeExpr: unknown %s %#v", tnode.Kind, tnode) + } + // TODO(mvdan): some go-toml nodes such as Kind=toml.Bool do not seem to have a Raw Range + // which would let us grab their position information; fix this upstream. + if tnode.Raw.Length > 0 { + ast.SetPos(expr, d.tokenFile.Pos(d.shape(tnode).Start.Offset, token.NoRelPos)) + } + return expr, nil +} diff --git a/vendor/cuelang.org/go/encoding/toml/encode.go b/vendor/cuelang.org/go/encoding/toml/encode.go new file mode 100644 index 0000000000..23f768f1c5 --- /dev/null +++ b/vendor/cuelang.org/go/encoding/toml/encode.go @@ -0,0 +1,47 @@ +// Copyright 2024 The CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package toml + +import ( + "io" + + "github.com/pelletier/go-toml/v2" + + "cuelang.org/go/cue" +) + +// TODO(mvdan): encode options + +// TODO(mvdan): the encoder below is based on map[string]any since go-toml/v2/unstable +// does not support printing or encoding Nodes; this means no support for comments, +// positions such as empty lines, or the relative order of fields. + +// NewEncoder creates an encoder to stream encoded TOML bytes. +func NewEncoder(w io.Writer) *Encoder { + return &Encoder{encoder: toml.NewEncoder(w)} +} + +// Encoder implements the encoding state. +type Encoder struct { + encoder *toml.Encoder +} + +func (e *Encoder) Encode(val cue.Value) error { + var v any + if err := val.Decode(&v); err != nil { + return err + } + return e.encoder.Encode(v) +} diff --git a/vendor/cuelang.org/go/encoding/yaml/yaml.go b/vendor/cuelang.org/go/encoding/yaml/yaml.go new file mode 100644 index 0000000000..a06da8384f --- /dev/null +++ b/vendor/cuelang.org/go/encoding/yaml/yaml.go @@ -0,0 +1,103 @@ +// Copyright 2019 The CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package yaml converts YAML encodings to and from CUE. When converting to CUE, +// comments and position information are retained. +package yaml + +import ( + "bytes" + "io" + + "cuelang.org/go/cue" + "cuelang.org/go/cue/ast" + cueyaml "cuelang.org/go/internal/encoding/yaml" + "cuelang.org/go/internal/source" + pkgyaml "cuelang.org/go/pkg/encoding/yaml" +) + +// Extract parses the YAML specified by src to a CUE expression. If +// there's more than one document, the documents will be returned as a +// list. The src argument may be a nil, string, []byte, or io.Reader. If +// src is nil, the result of reading the file specified by filename will +// be used. +func Extract(filename string, src interface{}) (*ast.File, error) { + data, err := source.ReadAll(filename, src) + if err != nil { + return nil, err + } + a := []ast.Expr{} + d := cueyaml.NewDecoder(filename, data) + for { + expr, err := d.Decode() + if err != nil { + if err != io.EOF { + return nil, err + } + if expr != nil { + a = append(a, expr) + } + break + } + a = append(a, expr) + } + f := &ast.File{Filename: filename} + switch len(a) { + case 0: + case 1: + switch x := a[0].(type) { + case *ast.StructLit: + f.Decls = x.Elts + default: + f.Decls = []ast.Decl{&ast.EmbedDecl{Expr: x}} + } + default: + f.Decls = []ast.Decl{&ast.EmbedDecl{Expr: &ast.ListLit{Elts: a}}} + } + return f, nil +} + +// Encode returns the YAML encoding of v. +func Encode(v cue.Value) ([]byte, error) { + n := v.Syntax(cue.Final()) + b, err := cueyaml.Encode(n) + return b, err +} + +// EncodeStream returns the YAML encoding of iter, where consecutive values +// of iter are separated with a `---`. +func EncodeStream(iter cue.Iterator) ([]byte, error) { + // TODO: return an io.Reader and allow asynchronous processing. + buf := &bytes.Buffer{} + for i := 0; iter.Next(); i++ { + if i > 0 { + buf.WriteString("---\n") + } + n := iter.Value().Syntax(cue.Final()) + b, err := cueyaml.Encode(n) + if err != nil { + return nil, err + } + buf.Write(b) + } + return buf.Bytes(), nil +} + +// Validate validates the YAML and confirms it matches the constraints +// specified by v. For YAML streams, all values must match v. +func Validate(b []byte, v cue.Value) error { + // TODO(mvdan): encoding/yaml should not import pkg/encoding/yaml. + _, err := pkgyaml.Validate(b, v) + return err +} diff --git a/vendor/cuelang.org/go/internal/astinternal/debug.go b/vendor/cuelang.org/go/internal/astinternal/debug.go new file mode 100644 index 0000000000..24e4398237 --- /dev/null +++ b/vendor/cuelang.org/go/internal/astinternal/debug.go @@ -0,0 +1,578 @@ +// Copyright 2021 CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package astinternal + +import ( + "fmt" + gotoken "go/token" + "reflect" + "strconv" + "strings" + + "cuelang.org/go/cue/ast" + "cuelang.org/go/cue/token" + "cuelang.org/go/internal" +) + +// AppendDebug writes a multi-line Go-like representation of a syntax tree node, +// including node position information and any relevant Go types. +func AppendDebug(dst []byte, node ast.Node, config DebugConfig) []byte { + d := &debugPrinter{ + cfg: config, + buf: dst, + } + if config.IncludeNodeRefs { + d.nodeRefs = make(map[ast.Node]int) + d.addNodeRefs(reflect.ValueOf(node)) + } + if d.value(reflect.ValueOf(node), nil) { + d.newline() + } + return d.buf +} + +// DebugConfig configures the behavior of [AppendDebug]. +type DebugConfig struct { + // Filter is called before each value in a syntax tree. + // Values for which the function returns false are omitted. + Filter func(reflect.Value) bool + + // OmitEmpty causes empty strings, empty structs, empty lists, + // nil pointers, invalid positions, and missing tokens to be omitted. + OmitEmpty bool + + // IncludeNodeRefs causes a Node reference in an identifier + // to indicate which (if any) ast.Node it refers to. + IncludeNodeRefs bool + + // IncludePointers causes all nodes to be printed with their pointer + // values; setting this also implies [DebugConfig.IncludeNodeRefs] + // and references will be printed as pointers. + IncludePointers bool +} + +type debugPrinter struct { + buf []byte + cfg DebugConfig + level int + nodeRefs map[ast.Node]int + refID int +} + +// value produces the given value, omitting type information if +// its type is the same as implied type. It reports whether +// anything was produced. +func (d *debugPrinter) value(v reflect.Value, impliedType reflect.Type) bool { + start := d.pos() + d.value0(v, impliedType) + return d.pos() > start +} + +func (d *debugPrinter) value0(v reflect.Value, impliedType reflect.Type) { + if d.cfg.Filter != nil && !d.cfg.Filter(v) { + return + } + // Skip over interfaces and pointers, stopping early if nil. + concreteType := v.Type() + refName := "" + ptrVal := uintptr(0) + for { + k := v.Kind() + if k != reflect.Interface && k != reflect.Pointer { + break + } + if v.IsNil() { + if !d.cfg.OmitEmpty { + d.printf("nil") + } + return + } + if k == reflect.Pointer { + if n, ok := v.Interface().(ast.Node); ok { + ptrVal = v.Pointer() + if id, ok := d.nodeRefs[n]; ok { + refName = refIDToName(id) + } + } + } + v = v.Elem() + if k == reflect.Interface { + // For example, *ast.Ident can be the concrete type behind an ast.Expr. + concreteType = v.Type() + } + } + + if d.cfg.OmitEmpty && v.IsZero() { + return + } + + t := v.Type() + switch v := v.Interface().(type) { + // Simple types which can stringify themselves. + case token.Pos: + d.printf("%s(%q", t, v) + // Show relative positions too, if there are any, as they affect formatting. + if v.HasRelPos() { + d.printf(", %v", v.RelPos()) + } + d.printf(")") + return + case token.Token: + d.printf("%s(%q)", t, v) + return + } + + switch t.Kind() { + default: + // We assume all other kinds are basic in practice, like string or bool. + if t.PkgPath() != "" { + // Mention defined and non-predeclared types, for clarity. + d.printf("%s(%#v)", t, v) + } else { + d.printf("%#v", v) + } + + case reflect.Slice, reflect.Struct: + valueStart := d.pos() + // We print the concrete type when it differs from an implied type. + if concreteType != impliedType { + d.printf("%s", concreteType) + } + if d.cfg.IncludePointers { + if ptrVal != 0 { + d.printf("@%#x", ptrVal) + } + } else if refName != "" { + d.printf("@%s", refName) + } + d.printf("{") + d.level++ + var anyElems bool + if t.Kind() == reflect.Slice { + anyElems = d.sliceElems(v, t.Elem()) + } else { + anyElems = d.structFields(v) + } + d.level-- + if !anyElems && d.cfg.OmitEmpty { + d.truncate(valueStart) + } else { + if anyElems { + d.newline() + } + d.printf("}") + } + } +} + +func (d *debugPrinter) sliceElems(v reflect.Value, elemType reflect.Type) (anyElems bool) { + for i := 0; i < v.Len(); i++ { + ev := v.Index(i) + elemStart := d.pos() + d.newline() + // Note: a slice literal implies the type of its elements + // so we can avoid mentioning the type + // of each element if it matches. + if d.value(ev, elemType) { + anyElems = true + } else { + d.truncate(elemStart) + } + } + return anyElems +} + +func (d *debugPrinter) structFields(v reflect.Value) (anyElems bool) { + t := v.Type() + for i := 0; i < v.NumField(); i++ { + f := t.Field(i) + if !gotoken.IsExported(f.Name) { + continue + } + if f.Name == "Node" { + nodeVal := v.Field(i) + if (!d.cfg.IncludeNodeRefs && !d.cfg.IncludePointers) || nodeVal.IsNil() { + continue + } + d.newline() + if d.cfg.IncludePointers { + if nodeVal.Kind() == reflect.Interface { + nodeVal = nodeVal.Elem() + } + d.printf("Node: @%#v (%v)", nodeVal.Pointer(), nodeVal.Elem().Type()) + } else { + d.printf("Node: @%s (%v)", refIDToName(d.nodeRefs[nodeVal.Interface().(ast.Node)]), nodeVal.Elem().Type()) + } + continue + } + switch f.Name { + // These fields are cyclic, and they don't represent the syntax anyway. + case "Scope", "Unresolved": + continue + } + elemStart := d.pos() + d.newline() + d.printf("%s: ", f.Name) + if d.value(v.Field(i), nil) { + anyElems = true + } else { + d.truncate(elemStart) + } + } + val := v.Addr().Interface() + if val, ok := val.(ast.Node); ok { + // Comments attached to a node aren't a regular field, but are still useful. + // The majority of nodes won't have comments, so skip them when empty. + if comments := ast.Comments(val); len(comments) > 0 { + anyElems = true + d.newline() + d.printf("Comments: ") + d.value(reflect.ValueOf(comments), nil) + } + } + return anyElems +} + +func (d *debugPrinter) printf(format string, args ...any) { + d.buf = fmt.Appendf(d.buf, format, args...) +} + +func (d *debugPrinter) newline() { + d.buf = fmt.Appendf(d.buf, "\n%s", strings.Repeat("\t", d.level)) +} + +func (d *debugPrinter) pos() int { + return len(d.buf) +} + +func (d *debugPrinter) truncate(pos int) { + d.buf = d.buf[:pos] +} + +// addNodeRefs does a first pass over the value looking for +// [ast.Ident] nodes that refer to other nodes. +// This means when we find such a node, we can include +// an anchor name for it +func (d *debugPrinter) addNodeRefs(v reflect.Value) { + // Skip over interfaces and pointers, stopping early if nil. + for ; v.Kind() == reflect.Interface || v.Kind() == reflect.Pointer; v = v.Elem() { + if v.IsNil() { + return + } + } + + t := v.Type() + switch v := v.Interface().(type) { + case token.Pos, token.Token: + // Simple types which can't contain an ast.Node. + return + case ast.Ident: + if v.Node != nil { + if _, ok := d.nodeRefs[v.Node]; !ok { + d.refID++ + d.nodeRefs[v.Node] = d.refID + } + } + return + } + + switch t.Kind() { + case reflect.Slice: + for i := 0; i < v.Len(); i++ { + d.addNodeRefs(v.Index(i)) + } + case reflect.Struct: + t := v.Type() + for i := 0; i < v.NumField(); i++ { + f := t.Field(i) + if !gotoken.IsExported(f.Name) { + continue + } + switch f.Name { + // These fields don't point to any nodes that Node can refer to. + case "Scope", "Node", "Unresolved": + continue + } + d.addNodeRefs(v.Field(i)) + } + } +} + +func refIDToName(id int) string { + if id == 0 { + return "unknown" + } + return fmt.Sprintf("ref%03d", id) +} + +func DebugStr(x interface{}) (out string) { + if n, ok := x.(ast.Node); ok { + comments := "" + for _, g := range ast.Comments(n) { + comments += DebugStr(g) + } + if comments != "" { + defer func() { out = "<" + comments + out + ">" }() + } + } + switch v := x.(type) { + case *ast.File: + out := "" + out += DebugStr(v.Decls) + return out + + case *ast.Package: + out := "package " + out += DebugStr(v.Name) + return out + + case *ast.LetClause: + out := "let " + out += DebugStr(v.Ident) + out += "=" + out += DebugStr(v.Expr) + return out + + case *ast.Alias: + out := DebugStr(v.Ident) + out += "=" + out += DebugStr(v.Expr) + return out + + case *ast.BottomLit: + return "_|_" + + case *ast.BasicLit: + return v.Value + + case *ast.Interpolation: + for _, e := range v.Elts { + out += DebugStr(e) + } + return out + + case *ast.EmbedDecl: + out += DebugStr(v.Expr) + return out + + case *ast.ImportDecl: + out := "import " + if v.Lparen != token.NoPos { + out += "( " + out += DebugStr(v.Specs) + out += " )" + } else { + out += DebugStr(v.Specs) + } + return out + + case *ast.Comprehension: + out := DebugStr(v.Clauses) + out += DebugStr(v.Value) + return out + + case *ast.StructLit: + out := "{" + out += DebugStr(v.Elts) + out += "}" + return out + + case *ast.ListLit: + out := "[" + out += DebugStr(v.Elts) + out += "]" + return out + + case *ast.Ellipsis: + out := "..." + if v.Type != nil { + out += DebugStr(v.Type) + } + return out + + case *ast.ForClause: + out := "for " + if v.Key != nil { + out += DebugStr(v.Key) + out += ": " + } + out += DebugStr(v.Value) + out += " in " + out += DebugStr(v.Source) + return out + + case *ast.IfClause: + out := "if " + out += DebugStr(v.Condition) + return out + + case *ast.Field: + out := DebugStr(v.Label) + if t, ok := internal.ConstraintToken(v); ok { + out += t.String() + } + if v.Value != nil { + switch v.Token { + case token.ILLEGAL, token.COLON: + out += ": " + default: + out += fmt.Sprintf(" %s ", v.Token) + } + out += DebugStr(v.Value) + for _, a := range v.Attrs { + out += " " + out += DebugStr(a) + } + } + return out + + case *ast.Attribute: + return v.Text + + case *ast.Ident: + return v.Name + + case *ast.SelectorExpr: + return DebugStr(v.X) + "." + DebugStr(v.Sel) + + case *ast.CallExpr: + out := DebugStr(v.Fun) + out += "(" + out += DebugStr(v.Args) + out += ")" + return out + + case *ast.ParenExpr: + out := "(" + out += DebugStr(v.X) + out += ")" + return out + + case *ast.UnaryExpr: + return v.Op.String() + DebugStr(v.X) + + case *ast.BinaryExpr: + out := DebugStr(v.X) + op := v.Op.String() + if 'a' <= op[0] && op[0] <= 'z' { + op = fmt.Sprintf(" %s ", op) + } + out += op + out += DebugStr(v.Y) + return out + + case []*ast.CommentGroup: + var a []string + for _, c := range v { + a = append(a, DebugStr(c)) + } + return strings.Join(a, "\n") + + case *ast.CommentGroup: + str := "[" + if v.Doc { + str += "d" + } + if v.Line { + str += "l" + } + str += strconv.Itoa(int(v.Position)) + var a = []string{} + for _, c := range v.List { + a = append(a, c.Text) + } + return str + strings.Join(a, " ") + "] " + + case *ast.IndexExpr: + out := DebugStr(v.X) + out += "[" + out += DebugStr(v.Index) + out += "]" + return out + + case *ast.SliceExpr: + out := DebugStr(v.X) + out += "[" + out += DebugStr(v.Low) + out += ":" + out += DebugStr(v.High) + out += "]" + return out + + case *ast.ImportSpec: + out := "" + if v.Name != nil { + out += DebugStr(v.Name) + out += " " + } + out += DebugStr(v.Path) + return out + + case *ast.Func: + return fmt.Sprintf("func(%v): %v", DebugStr(v.Args), DebugStr(v.Ret)) + + case []ast.Decl: + if len(v) == 0 { + return "" + } + out := "" + for _, d := range v { + out += DebugStr(d) + out += sep + } + return out[:len(out)-len(sep)] + + case []ast.Clause: + if len(v) == 0 { + return "" + } + out := "" + for _, c := range v { + out += DebugStr(c) + out += " " + } + return out + + case []ast.Expr: + if len(v) == 0 { + return "" + } + out := "" + for _, d := range v { + out += DebugStr(d) + out += sep + } + return out[:len(out)-len(sep)] + + case []*ast.ImportSpec: + if len(v) == 0 { + return "" + } + out := "" + for _, d := range v { + out += DebugStr(d) + out += sep + } + return out[:len(out)-len(sep)] + + default: + if v == nil { + return "" + } + return fmt.Sprintf("<%T>", x) + } +} + +const sep = ", " diff --git a/vendor/cuelang.org/go/internal/astinternal/debugstr.go b/vendor/cuelang.org/go/internal/astinternal/debugstr.go deleted file mode 100644 index 83091af5c1..0000000000 --- a/vendor/cuelang.org/go/internal/astinternal/debugstr.go +++ /dev/null @@ -1,285 +0,0 @@ -// Copyright 2021 CUE Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package astinternal - -import ( - "fmt" - "strconv" - "strings" - - "cuelang.org/go/cue/ast" - "cuelang.org/go/cue/token" - "cuelang.org/go/internal" -) - -func DebugStr(x interface{}) (out string) { - if n, ok := x.(ast.Node); ok { - comments := "" - for _, g := range ast.Comments(n) { - comments += DebugStr(g) - } - if comments != "" { - defer func() { out = "<" + comments + out + ">" }() - } - } - switch v := x.(type) { - case *ast.File: - out := "" - out += DebugStr(v.Decls) - return out - - case *ast.Package: - out := "package " - out += DebugStr(v.Name) - return out - - case *ast.LetClause: - out := "let " - out += DebugStr(v.Ident) - out += "=" - out += DebugStr(v.Expr) - return out - - case *ast.Alias: - out := DebugStr(v.Ident) - out += "=" - out += DebugStr(v.Expr) - return out - - case *ast.BottomLit: - return "_|_" - - case *ast.BasicLit: - return v.Value - - case *ast.Interpolation: - for _, e := range v.Elts { - out += DebugStr(e) - } - return out - - case *ast.EmbedDecl: - out += DebugStr(v.Expr) - return out - - case *ast.ImportDecl: - out := "import " - if v.Lparen != token.NoPos { - out += "( " - out += DebugStr(v.Specs) - out += " )" - } else { - out += DebugStr(v.Specs) - } - return out - - case *ast.Comprehension: - out := DebugStr(v.Clauses) - out += DebugStr(v.Value) - return out - - case *ast.StructLit: - out := "{" - out += DebugStr(v.Elts) - out += "}" - return out - - case *ast.ListLit: - out := "[" - out += DebugStr(v.Elts) - out += "]" - return out - - case *ast.Ellipsis: - out := "..." - if v.Type != nil { - out += DebugStr(v.Type) - } - return out - - case *ast.ForClause: - out := "for " - if v.Key != nil { - out += DebugStr(v.Key) - out += ": " - } - out += DebugStr(v.Value) - out += " in " - out += DebugStr(v.Source) - return out - - case *ast.IfClause: - out := "if " - out += DebugStr(v.Condition) - return out - - case *ast.Field: - out := DebugStr(v.Label) - if t, ok := internal.ConstraintToken(v); ok { - out += t.String() - } - if v.Value != nil { - switch v.Token { - case token.ILLEGAL, token.COLON: - out += ": " - default: - out += fmt.Sprintf(" %s ", v.Token) - } - out += DebugStr(v.Value) - for _, a := range v.Attrs { - out += " " - out += DebugStr(a) - } - } - return out - - case *ast.Attribute: - return v.Text - - case *ast.Ident: - return v.Name - - case *ast.SelectorExpr: - return DebugStr(v.X) + "." + DebugStr(v.Sel) - - case *ast.CallExpr: - out := DebugStr(v.Fun) - out += "(" - out += DebugStr(v.Args) - out += ")" - return out - - case *ast.ParenExpr: - out := "(" - out += DebugStr(v.X) - out += ")" - return out - - case *ast.UnaryExpr: - return v.Op.String() + DebugStr(v.X) - - case *ast.BinaryExpr: - out := DebugStr(v.X) - op := v.Op.String() - if 'a' <= op[0] && op[0] <= 'z' { - op = fmt.Sprintf(" %s ", op) - } - out += op - out += DebugStr(v.Y) - return out - - case []*ast.CommentGroup: - var a []string - for _, c := range v { - a = append(a, DebugStr(c)) - } - return strings.Join(a, "\n") - - case *ast.CommentGroup: - str := "[" - if v.Doc { - str += "d" - } - if v.Line { - str += "l" - } - str += strconv.Itoa(int(v.Position)) - var a = []string{} - for _, c := range v.List { - a = append(a, c.Text) - } - return str + strings.Join(a, " ") + "] " - - case *ast.IndexExpr: - out := DebugStr(v.X) - out += "[" - out += DebugStr(v.Index) - out += "]" - return out - - case *ast.SliceExpr: - out := DebugStr(v.X) - out += "[" - out += DebugStr(v.Low) - out += ":" - out += DebugStr(v.High) - out += "]" - return out - - case *ast.ImportSpec: - out := "" - if v.Name != nil { - out += DebugStr(v.Name) - out += " " - } - out += DebugStr(v.Path) - return out - - case *ast.Func: - return fmt.Sprintf("func(%v): %v", DebugStr(v.Args), DebugStr(v.Ret)) - - case []ast.Decl: - if len(v) == 0 { - return "" - } - out := "" - for _, d := range v { - out += DebugStr(d) - out += sep - } - return out[:len(out)-len(sep)] - - case []ast.Clause: - if len(v) == 0 { - return "" - } - out := "" - for _, c := range v { - out += DebugStr(c) - out += " " - } - return out - - case []ast.Expr: - if len(v) == 0 { - return "" - } - out := "" - for _, d := range v { - out += DebugStr(d) - out += sep - } - return out[:len(out)-len(sep)] - - case []*ast.ImportSpec: - if len(v) == 0 { - return "" - } - out := "" - for _, d := range v { - out += DebugStr(d) - out += sep - } - return out[:len(out)-len(sep)] - - default: - if v == nil { - return "" - } - return fmt.Sprintf("<%T>", x) - } -} - -const sep = ", " diff --git a/vendor/cuelang.org/go/internal/attrs.go b/vendor/cuelang.org/go/internal/attrs.go index 6e50e3f1d0..b3d1918eaf 100644 --- a/vendor/cuelang.org/go/internal/attrs.go +++ b/vendor/cuelang.org/go/internal/attrs.go @@ -16,13 +16,13 @@ package internal import ( "fmt" - "strconv" "strings" "cuelang.org/go/cue/errors" "cuelang.org/go/cue/literal" "cuelang.org/go/cue/scanner" "cuelang.org/go/cue/token" + "github.com/cockroachdb/apd/v3" ) // AttrKind indicates the location of an attribute within CUE source. @@ -52,6 +52,7 @@ type Attr struct { Kind AttrKind Fields []KeyValue Err errors.Error + Pos token.Pos } // NewNonExisting creates a non-existing attribute. @@ -109,9 +110,15 @@ func (a *Attr) Int(pos int) (int64, error) { if err := a.hasPos(pos); err != nil { return 0, err } - // TODO: use CUE's literal parser once it exists, allowing any of CUE's - // number types. - return strconv.ParseInt(a.Fields[pos].Text(), 10, 64) + var ni literal.NumInfo + if err := literal.ParseNum(a.Fields[pos].Text(), &ni); err != nil { + return 0, err + } + var d apd.Decimal + if err := ni.Decimal(&d); err != nil { + return 0, err + } + return d.Int64() } // Flag reports whether an entry with the given name exists at position pos or @@ -153,6 +160,7 @@ func ParseAttrBody(pos token.Pos, s string) (a Attr) { tmpFile.AddLine(len(s) - 1) } a.Body = s + a.Pos = pos var scan scanner.Scanner scan.Init(tmpFile, []byte(s), nil, scanner.DontInsertCommas) for { diff --git a/vendor/cuelang.org/go/internal/buildattr/buildattr.go b/vendor/cuelang.org/go/internal/buildattr/buildattr.go new file mode 100644 index 0000000000..87d4c92a73 --- /dev/null +++ b/vendor/cuelang.org/go/internal/buildattr/buildattr.go @@ -0,0 +1,117 @@ +// Package buildattr implements support for interpreting the @if +// build attributes in CUE files. +package buildattr + +import ( + "cuelang.org/go/cue/ast" + "cuelang.org/go/cue/errors" + "cuelang.org/go/cue/parser" + "cuelang.org/go/cue/token" +) + +// ShouldIgnoreFile reports whether a File contains an @ignore() file-level +// attribute and hence should be ignored. +func ShouldIgnoreFile(f *ast.File) bool { + ignore, _, _ := getBuildAttr(f) + return ignore +} + +// ShouldBuildFile reports whether a File should be included based on its +// attributes. It uses tagIsSet to determine whether a given attribute +// key should be treated as set. +// +// It also returns the build attribute if one was found. +func ShouldBuildFile(f *ast.File, tagIsSet func(key string) bool) (bool, *ast.Attribute, errors.Error) { + ignore, a, err := getBuildAttr(f) + if ignore || err != nil { + return false, a, err + } + if a == nil { + return true, nil, nil + } + + _, body := a.Split() + + expr, parseErr := parser.ParseExpr("", body) + if parseErr != nil { + return false, a, errors.Promote(parseErr, "") + } + + include, err := shouldInclude(expr, tagIsSet) + if err != nil { + return false, a, err + } + return include, a, nil +} + +func getBuildAttr(f *ast.File) (ignore bool, a *ast.Attribute, err errors.Error) { + for _, d := range f.Decls { + switch x := d.(type) { + case *ast.Attribute: + switch key, _ := x.Split(); key { + case "ignore": + return true, x, nil + case "if": + if a != nil { + err := errors.Newf(d.Pos(), "multiple @if attributes") + err = errors.Append(err, + errors.Newf(a.Pos(), "previous declaration here")) + return false, a, err + } + a = x + } + case *ast.Package: + return false, a, nil + case *ast.CommentGroup: + default: + // If it's anything else, then we know we won't see a package + // clause so avoid scanning more than we need to (this + // could be a large file with no package clause) + return false, a, nil + } + } + return false, a, nil +} + +func shouldInclude(expr ast.Expr, tagIsSet func(key string) bool) (bool, errors.Error) { + switch x := expr.(type) { + case *ast.Ident: + return tagIsSet(x.Name), nil + + case *ast.ParenExpr: + return shouldInclude(x.X, tagIsSet) + + case *ast.BinaryExpr: + switch x.Op { + case token.LAND, token.LOR: + a, err := shouldInclude(x.X, tagIsSet) + if err != nil { + return false, err + } + b, err := shouldInclude(x.Y, tagIsSet) + if err != nil { + return false, err + } + if x.Op == token.LAND { + return a && b, nil + } + return a || b, nil + + default: + return false, errors.Newf(token.NoPos, "invalid operator %v in build attribute", x.Op) + } + + case *ast.UnaryExpr: + if x.Op != token.NOT { + return false, errors.Newf(token.NoPos, "invalid operator %v in build attribute", x.Op) + } + v, err := shouldInclude(x.X, tagIsSet) + if err != nil { + return false, err + } + return !v, nil + + default: + return false, errors.Newf(token.NoPos, "invalid type %T in build attribute", expr) + } +} diff --git a/vendor/cuelang.org/go/internal/core/adt/binop.go b/vendor/cuelang.org/go/internal/core/adt/binop.go index fefcd48838..0c75c0f843 100644 --- a/vendor/cuelang.org/go/internal/core/adt/binop.go +++ b/vendor/cuelang.org/go/internal/core/adt/binop.go @@ -32,12 +32,14 @@ func BinOp(c *OpContext, op Op, left, right Value) Value { return &Bottom{ Code: IncompleteError, Err: c.Newf(msg, left, op), + Node: c.vertex, } } if right.Concreteness() > Concrete { return &Bottom{ Code: IncompleteError, Err: c.Newf(msg, right, op), + Node: c.vertex, } } @@ -64,7 +66,7 @@ func BinOp(c *OpContext, op Op, left, right Value) Value { case leftKind == BytesKind: return cmpTonode(c, op, bytes.Compare(c.bytesValue(left, op), c.bytesValue(right, op))) - case leftKind&NumKind != 0 && rightKind&NumKind != 0: + case leftKind&NumberKind != 0 && rightKind&NumberKind != 0: // n := c.newNum() return cmpTonode(c, op, c.Num(left, op).X.Cmp(&c.Num(right, op).X)) @@ -102,7 +104,7 @@ func BinOp(c *OpContext, op Op, left, right Value) Value { case leftKind == BytesKind: return cmpTonode(c, op, bytes.Compare(c.bytesValue(left, op), c.bytesValue(right, op))) - case leftKind&NumKind != 0 && rightKind&NumKind != 0: + case leftKind&NumberKind != 0 && rightKind&NumberKind != 0: // n := c.newNum() return cmpTonode(c, op, c.Num(left, op).X.Cmp(&c.Num(right, op).X)) @@ -131,7 +133,7 @@ func BinOp(c *OpContext, op Op, left, right Value) Value { case leftKind == BytesKind && rightKind == BytesKind: return cmpTonode(c, op, bytes.Compare(c.bytesValue(left, op), c.bytesValue(right, op))) - case leftKind&NumKind != 0 && rightKind&NumKind != 0: + case leftKind&NumberKind != 0 && rightKind&NumberKind != 0: // n := c.newNum(left, right) return cmpTonode(c, op, c.Num(left, op).X.Cmp(&c.Num(right, op).X)) } @@ -158,7 +160,7 @@ func BinOp(c *OpContext, op Op, left, right Value) Value { case AddOp: switch { - case leftKind&NumKind != 0 && rightKind&NumKind != 0: + case leftKind&NumberKind != 0 && rightKind&NumberKind != 0: return c.Add(c.Num(left, op), c.Num(right, op)) case leftKind == StringKind && rightKind == StringKind: @@ -173,49 +175,7 @@ func BinOp(c *OpContext, op Op, left, right Value) Value { return c.newBytes(b) case leftKind == ListKind && rightKind == ListKind: - // TODO: get rid of list addition. Semantically it is somewhat - // unclear and, as it turns out, it is also hard to get right. - // Simulate addition with comprehensions now. - if err := c.Err(); err != nil { - return err - } - - x := MakeIdentLabel(c, "x", "") - - // for x in expr { x } - forClause := func(src Expr) *Comprehension { - s := &StructLit{Decls: []Decl{ - &FieldReference{UpCount: 1, Label: x}, - }} - return &Comprehension{ - Clauses: []Yielder{ - &ForClause{ - Value: x, - Src: src, - }, - }, - Value: s, - } - } - - list := &ListLit{ - Elems: []Elem{ - forClause(left), - forClause(right), - }, - } - - n := c.newInlineVertex(nil, nil, MakeConjunct(c.Env(0), list, c.ci)) - n.CompleteArcs(c) - - // NOTE: if we set isData to true, whoever processes the result will - // avoid having to process the expressions again. This improves - // performance. It also change the a potential cycle error message - // to a more concrete messages as if this result was unified as is. - // TODO: uncomment this and see if we like the result. - // n.isData = true - - return n + return c.NewErrf("Addition of lists is superseded by list.Concat; see https://cuelang.org/e/v0.11-list-arithmetic") } case SubtractOp: @@ -224,7 +184,7 @@ func BinOp(c *OpContext, op Op, left, right Value) Value { case MultiplyOp: switch { // float - case leftKind&NumKind != 0 && rightKind&NumKind != 0: + case leftKind&NumberKind != 0 && rightKind&NumberKind != 0: return c.Mul(c.Num(left, op), c.Num(right, op)) case leftKind == StringKind && rightKind == IntKind: @@ -243,44 +203,14 @@ func BinOp(c *OpContext, op Op, left, right Value) Value { const as = "bytes multiplication" return c.newBytes(bytes.Repeat(c.bytesValue(right, as), int(c.uint64(left, as)))) - case leftKind == ListKind && rightKind == IntKind: - left, right = right, left - fallthrough - case leftKind == IntKind && rightKind == ListKind: - // TODO: get rid of list multiplication. - - list := &ListLit{} - x := MakeIdentLabel(c, "x", "") - - for i := c.uint64(left, "list multiplier"); i > 0; i-- { - st := &StructLit{Decls: []Decl{ - &FieldReference{UpCount: 1, Label: x}, - }} - list.Elems = append(list.Elems, - &Comprehension{ - Clauses: []Yielder{ - &ForClause{ - Value: x, - Src: right, - }, - }, - Value: st, - }, - ) - } - if err := c.Err(); err != nil { - return err - } - - n := c.newInlineVertex(nil, nil, MakeConjunct(c.Env(0), list, c.ci)) - n.CompleteArcs(c) - - return n + fallthrough + case leftKind == ListKind && rightKind == IntKind: + return c.NewErrf("Multiplication of lists is superseded by list.Repeat; see https://cuelang.org/e/v0.11-list-arithmetic") } case FloatQuotientOp: - if leftKind&NumKind != 0 && rightKind&NumKind != 0 { + if leftKind&NumberKind != 0 && rightKind&NumberKind != 0 { return c.Quo(c.Num(left, op), c.Num(right, op)) } diff --git a/vendor/cuelang.org/go/internal/core/adt/closed.go b/vendor/cuelang.org/go/internal/core/adt/closed.go index fe2baf2004..6db1eebf18 100644 --- a/vendor/cuelang.org/go/internal/core/adt/closed.go +++ b/vendor/cuelang.org/go/internal/core/adt/closed.go @@ -84,16 +84,13 @@ func (v *Vertex) IsInOneOf(mask SpanType) bool { // IsRecursivelyClosed returns true if this value is either a definition or unified // with a definition. func (v *Vertex) IsRecursivelyClosed() bool { - return v.Closed || v.IsInOneOf(DefinitionSpan) + return v.ClosedRecursive || v.IsInOneOf(DefinitionSpan) } type closeNodeType uint8 const ( // a closeRef node is created when there is a non-definition reference. - // These nodes are not necessary for computing results, but may be - // relevant down the line to group closures through embedded values and - // to track position information for failures. closeRef closeNodeType = iota // closeDef indicates this node was introduced as a result of referencing @@ -102,8 +99,6 @@ const ( // closeEmbed indicates this node was added as a result of an embedding. closeEmbed - - _ = closeRef // silence the linter ) // TODO: merge with closeInfo: this is a leftover of the refactoring. @@ -127,6 +122,11 @@ type CloseInfo struct { // NOTE: only used when using closeContext. FromDef bool + // GroupUnify indicates that this conjunct needs to spawn its own + // closeContext. This is necessary when programmatically combining + // top-level values, such as with Value.Unify. + GroupUnify bool + // FieldTypes indicates which kinds of fields (optional, dynamic, patterns, // etc.) are contained in this conjunct. FieldTypes OptionalType @@ -243,21 +243,23 @@ func (c CloseInfo) SpawnRef(arc *Vertex, isDef bool, x Expr) CloseInfo { // // TODO(performance): this should be merged with resolve(). But for now keeping // this code isolated makes it easier to see what it is for. -func IsDef(x Expr) bool { +func IsDef(x Expr) (isDef bool, depth int) { switch r := x.(type) { case *FieldReference: - return r.Label.IsDef() + isDef = r.Label.IsDef() case *SelectorExpr: + isDef, depth = IsDef(r.X) + depth++ if r.Sel.IsDef() { - return true + isDef = true } - return IsDef(r.X) case *IndexExpr: - return IsDef(r.X) + isDef, depth = IsDef(r.X) + depth++ } - return false + return isDef, depth } // A SpanType is used to indicate whether a CUE value is within the scope of @@ -294,6 +296,10 @@ type closeInfo struct { root SpanType span SpanType + + // decl is the parent declaration which contains the conjuct which + // gave rise to this closeInfo. + decl Decl } // closeStats holds the administrative fields for a closeInfo value. Each @@ -330,9 +336,10 @@ func isClosed(v *Vertex) bool { // We could have used IsRecursivelyClosed here, but (effectively) // implementing it again here allows us to only have to iterate over // Structs once. - if v.Closed { + if v.ClosedRecursive || v.ClosedNonRecursive { return true } + // TODO(evalv3): this can be removed once we delete the evalv2 code. for _, s := range v.Structs { if s.IsClosed || s.IsInOneOf(DefinitionSpan) { return true diff --git a/vendor/cuelang.org/go/internal/core/adt/composite.go b/vendor/cuelang.org/go/internal/core/adt/composite.go index ec2fe461b6..4e728285e8 100644 --- a/vendor/cuelang.org/go/internal/core/adt/composite.go +++ b/vendor/cuelang.org/go/internal/core/adt/composite.go @@ -16,6 +16,7 @@ package adt import ( "fmt" + "slices" "cuelang.org/go/cue/ast" "cuelang.org/go/cue/errors" @@ -158,10 +159,10 @@ type Vertex struct { // state *nodeContext - // cc manages the closedness logic for this Vertex. It is created + // _cc manages the closedness logic for this Vertex. It is created // by rootCloseContext. // TODO: move back to nodeContext, but be sure not to clone it. - cc *closeContext + _cc *closeContext // Label is the feature leading to this vertex. Label Feature @@ -181,10 +182,14 @@ type Vertex struct { // ignored. isData bool - // Closed indicates whether this Vertex is recursively closed. This is the - // case, for instance, if it is a node in a definition or if one of the - // conjuncts, or ancestor conjuncts, is a definition. - Closed bool + // ClosedRecursive indicates whether this Vertex is recursively closed. + // This is the case, for instance, if it is a node in a definition or if one + // of the conjuncts, or ancestor conjuncts, is a definition. + ClosedRecursive bool + + // ClosedNonRecursive indicates that this Vertex has been closed for this + // level only. This supports the close builtin. + ClosedNonRecursive bool // HasEllipsis indicates that this Vertex is open by means of an ellipsis. // TODO: combine this field with Closed once we removed the old evaluator. @@ -205,8 +210,24 @@ type Vertex struct { // Used for cycle detection. IsDynamic bool + // IsPatternConstraint indicates that this Vertex is an entry in + // Vertex.PatternConstraints. + IsPatternConstraint bool + + // nonRooted indicates that this Vertex originates within the context of + // a dynamic, or inlined, Vertex (e.g. `{out: ...}.out``). Note that, + // through reappropriation, this Vertex may become rooted down the line. + // Use the !IsDetached method to determine whether this Vertex became + // rooted. nonRooted bool // indicates that there is no path from the root of the tree. + // anonymous indicates that this Vertex is being computed within a + // addressable context, or in other words, a context for which there is + // a path from the root of the file. Typically, the only addressable + // contexts are fields. Examples of fields that are not addressable are + // the for source of comprehensions and let fields or let clauses. + anonymous bool + // hasPendingArc is set if this Vertex has a void arc (e.g. for comprehensions) hasPendingArc bool @@ -259,7 +280,7 @@ type Vertex struct { // TODO: all access to Conjuncts should go through functions like // VisitLeafConjuncts and VisitAllConjuncts. We should probably make this // an unexported field. - Conjuncts []Conjunct + Conjuncts ConjunctGroup // Structs is a slice of struct literals that contributed to this value. // This information is used to compute the topological sort of arcs. @@ -282,31 +303,49 @@ func equalDeref(a, b *Vertex) bool { return deref(a) == deref(b) } +func (v *Vertex) cc() *closeContext { + return v._cc +} + // rootCloseContext creates a closeContext for this Vertex or returns the // existing one. func (v *Vertex) rootCloseContext(ctx *OpContext) *closeContext { - if v.cc == nil { - v.cc = &closeContext{ - group: (*ConjunctGroup)(&v.Conjuncts), + if v._cc == nil { + v._cc = &closeContext{ + group: &v.Conjuncts, parent: nil, src: v, parentConjuncts: v, + decl: v, } - v.cc.incDependent(ctx, ROOT, nil) // matched in REF(decrement:nodeDone) + v._cc.incDependent(ctx, ROOT, nil) // matched in REF(decrement:nodeDone) } - return v.cc + + if p := v.Parent; p != nil { + pcc := p.rootCloseContext(ctx) + v._cc.depth = pcc.depth + 1 + } + + return v._cc } // newInlineVertex creates a Vertex that is needed for computation, but for // which there is no CUE path defined from the root Vertex. func (ctx *OpContext) newInlineVertex(parent *Vertex, v BaseValue, a ...Conjunct) *Vertex { - return &Vertex{ - Parent: parent, + n := &Vertex{ BaseValue: v, IsDynamic: true, ArcType: ArcMember, Conjuncts: a, } + if !ctx.isDevVersion() { + n.Parent = parent + } + if ctx.inDetached > 0 { + n.anonymous = true + } + return n + } // updateArcType updates v.ArcType if t is more restrictive. @@ -318,11 +357,16 @@ func (v *Vertex) updateArcType(t ArcType) { return } s := v.state - if (s != nil || v.isFinal()) && s.ctx.isDevVersion() { + // NOTE: this condition does not occur in V2. + if s != nil && v.isFinal() { c := s.ctx if s.scheduler.frozen.meets(arcTypeKnown) { + p := token.NoPos + if src := c.Source(); src != nil { + p = src.Pos() + } parent := v.Parent - parent.reportFieldCycleError(c, c.Source().Pos(), v.Label) + parent.reportFieldCycleError(c, p, v.Label) return } } @@ -356,12 +400,38 @@ func (v *Vertex) IsDefined(c *OpContext) bool { return v.isDefined() } -// Rooted reports whether there is a path from the root of the tree to this -// Vertex. +// Rooted reports if it is known there is a path from the root of the tree to +// this Vertex. If this returns false, it may still be rooted if the node +// originated from an inline struct, but was later reappropriated. func (v *Vertex) Rooted() bool { return !v.nonRooted && !v.Label.IsLet() && !v.IsDynamic } +// IsDetached reports whether this Vertex does not have a path from the root. +func (v *Vertex) IsDetached() bool { + // v might have resulted from an inline struct that was subsequently shared. + // In this case, it is still rooted. + for v != nil { + if v.Rooted() { + return false + } + // Already take into account the provisionally assigned parent. + if v.state != nil && v.state.parent != nil { + v = v.state.parent + } else { + v = v.Parent + } + } + + return true +} + +// MayAttach reports whether this Vertex may attach to another arc. +// The behavior is undefined if IsDetached is true. +func (v *Vertex) MayAttach() bool { + return !v.Label.IsLet() && !v.anonymous +} + type ArcType uint8 const ( @@ -478,6 +548,9 @@ type StructInfo struct { Disable bool Embedding bool + + // Decl contains this Struct + Decl Decl } // TODO(perf): this could be much more aggressive for eliminating structs that @@ -492,6 +565,8 @@ func (s *StructInfo) useForAccept() bool { // vertexStatus indicates the evaluation progress of a Vertex. type vertexStatus int8 +//go:generate go run golang.org/x/tools/cmd/stringer -type=vertexStatus + const ( // unprocessed indicates a Vertex has not been processed before. // Value must be nil. @@ -522,26 +597,22 @@ const ( finalized ) -func (s vertexStatus) String() string { - switch s { - case unprocessed: - return "unprocessed" - case evaluating: - return "evaluating" - case partial: - return "partial" - case conjuncts: - return "conjuncts" - case evaluatingArcs: - return "evaluatingArcs" - case finalized: - return "finalized" - default: - return "unknown" - } +// Wrap creates a Vertex that takes w as a shared value. This allows users +// to set different flags for a wrapped Vertex. +func (c *OpContext) Wrap(v *Vertex, id CloseInfo) *Vertex { + w := c.newInlineVertex(nil, nil, v.Conjuncts...) + n := w.getState(c) + n.share(makeAnonymousConjunct(nil, v, nil), v, CloseInfo{}) + return w } +// Status returns the status of the current node. When reading the status, one +// should always use this method over directly reading status field. +// +// NOTE: this only matters for EvalV3 and beyonds, so a lot of the old code +// might still access it directly. func (v *Vertex) Status() vertexStatus { + v = v.DerefValue() return v.status } @@ -552,13 +623,13 @@ func (v *Vertex) ForceDone() { // IsUnprocessed reports whether v is unprocessed. func (v *Vertex) IsUnprocessed() bool { - return v.status == unprocessed + return v.Status() == unprocessed } func (v *Vertex) updateStatus(s vertexStatus) { if !isCyclePlaceholder(v.BaseValue) { if !v.IsErr() && v.state != nil { - Assertf(v.state.ctx, v.status <= s+1, "attempt to regress status from %d to %d", v.Status(), s) + Assertf(v.state.ctx, v.Status() <= s+1, "attempt to regress status from %d to %d", v.Status(), s) } } @@ -592,14 +663,14 @@ func (v *Vertex) setParentDone() { // VisitLeafConjuncts visits all conjuncts that are leafs of the ConjunctGroup tree. func (v *Vertex) VisitLeafConjuncts(f func(Conjunct) bool) { - visitConjuncts(v.Conjuncts, f) + VisitConjuncts(v.Conjuncts, f) } -func visitConjuncts(a []Conjunct, f func(Conjunct) bool) bool { +func VisitConjuncts(a []Conjunct, f func(Conjunct) bool) bool { for _, c := range a { switch x := c.x.(type) { case *ConjunctGroup: - if !visitConjuncts(*x, f) { + if !VisitConjuncts(*x, f) { return false } default: @@ -629,6 +700,11 @@ func visitAllConjuncts(a []Conjunct, f func(c Conjunct, isLeaf bool)) { } } +// HasConjuncts reports whether v has any conjuncts. +func (v *Vertex) HasConjuncts() bool { + return len(v.Conjuncts) > 0 +} + // SingleConjunct reports whether there is a single leaf conjunct and returns 1 // if so. It will return 0 if there are no conjuncts or 2 if there are more than // 1. @@ -649,6 +725,13 @@ func (v *Vertex) SingleConjunct() (c Conjunct, count int) { return c, count } +// ConjunctAt assumes a Vertex represents a top-level Vertex, such as one +// representing a file or a let expressions, where all conjuncts appear at the +// top level. It may panic if this condition is not met. +func (v *Vertex) ConjunctAt(i int) Conjunct { + return v.Conjuncts[i] +} + // Value returns the Value of v without definitions if it is a scalar // or itself otherwise. func (v *Vertex) Value() Value { @@ -682,8 +765,7 @@ func (v *Vertex) isFinal() bool { // TODO(deref): the accounting of what is final should be recorded // in the original node. Remove this dereference once the old // evaluator has been removed. - v = v.DerefValue() - return v.status == finalized + return v.Status() == finalized } func (x *Vertex) IsConcrete() bool { @@ -694,7 +776,7 @@ func (x *Vertex) IsConcrete() bool { // it tells whether optional field matching and non-regular fields, like // definitions and hidden fields, should be ignored. func (v *Vertex) IsData() bool { - return v.isData || len(v.Conjuncts) == 0 + return v.isData || !v.HasConjuncts() } // ToDataSingle creates a new Vertex that represents just the regular fields @@ -711,6 +793,8 @@ func (v *Vertex) ToDataSingle() *Vertex { // ToDataAll returns a new v where v and all its descendents contain only // the regular fields. func (v *Vertex) ToDataAll(ctx *OpContext) *Vertex { + v.Finalize(ctx) + arcs := make([]*Vertex, 0, len(v.Arcs)) for _, a := range v.Arcs { if !a.IsDefined(ctx) { @@ -727,13 +811,20 @@ func (v *Vertex) ToDataAll(ctx *OpContext) *Vertex { w.BaseValue = toDataAll(ctx, w.BaseValue) w.Arcs = arcs w.isData = true - w.Conjuncts = make([]Conjunct, len(v.Conjuncts)) + w.Conjuncts = slices.Clone(v.Conjuncts) + + // Converting to dat drops constraints and non-regular fields. This means + // that the domain on which they are defined is reduced, which will change + // closedness properties. We therefore remove closedness. Note that data, + // in general and JSON specifically, is not closed. + w.ClosedRecursive = false + w.ClosedNonRecursive = false + // TODO(perf): this is not strictly necessary for evaluation, but it can // hurt performance greatly. Drawback is that it may disable ordering. for _, s := range w.Structs { s.Disable = true } - copy(w.Conjuncts, v.Conjuncts) for i, c := range w.Conjuncts { if v, _ := c.x.(Value); v != nil { w.Conjuncts[i].x = toDataAll(ctx, v).(Value) @@ -750,12 +841,20 @@ func toDataAll(ctx *OpContext, v BaseValue) BaseValue { case *Vertex: return x.ToDataAll(ctx) - // The following cases are always erroneous, but we handle them anyway - // to avoid issues with the closedness algorithm down the line. case *Disjunction: d := *x - d.Values = make([]Value, len(x.Values)) - for i, v := range x.Values { + values := x.Values + // Data mode involves taking default values and if there is an + // unambiguous default value, we should convert that to data as well. + switch x.NumDefaults { + case 0: + case 1: + return toDataAll(ctx, values[0]) + default: + values = values[:x.NumDefaults] + } + d.Values = make([]Value, len(values)) + for i, v := range values { switch x := v.(type) { case *Vertex: d.Values[i] = x.ToDataAll(ctx) @@ -776,6 +875,54 @@ func toDataAll(ctx *OpContext, v BaseValue) BaseValue { } } +// IsFinal reports whether value v can still become more specific, when only +// considering regular fields. +// +// TODO: move this functionality as a method on cue.Value. +func IsFinal(v Value) bool { + return isFinal(v, false) +} + +func isFinal(v Value, isClosed bool) bool { + switch x := v.(type) { + case *Vertex: + closed := isClosed || x.ClosedNonRecursive || x.ClosedRecursive + + // TODO(evalv3): this is for V2 compatibility. Remove once V2 is gone. + closed = closed || x.IsClosedList() || x.IsClosedStruct() + + // This also dereferences the value. + if v, ok := x.BaseValue.(Value); ok { + return isFinal(v, closed) + } + + // If it is not closed, it can still become more specific. + if !closed { + return false + } + + for _, a := range x.Arcs { + if !a.Label.IsRegular() { + continue + } + if a.ArcType > ArcMember && !a.IsErr() { + return false + } + if !isFinal(a, false) { + return false + } + } + return true + + case *Bottom: + // Incomplete errors could be resolved by making a struct more specific. + return x.Code <= StructuralCycleError + + default: + return v.Concreteness() <= Concrete + } +} + // func (v *Vertex) IsEvaluating() bool { // return v.Value == cycle // } @@ -842,6 +989,18 @@ func (v *Vertex) setValue(ctx *OpContext, state vertexStatus, value BaseValue) * return nil } +func (n *nodeContext) setBaseValue(value BaseValue) { + n.node.BaseValue = value +} + +// swapBaseValue swaps the BaseValue of a node with the given value and returns +// the previous value. +func (n *nodeContext) swapBaseValue(value BaseValue) (saved BaseValue) { + saved = n.node.BaseValue + n.setBaseValue(value) + return saved +} + // ToVertex wraps v in a new Vertex, if necessary. func ToVertex(v Value) *Vertex { switch x := v.(type) { @@ -928,7 +1087,7 @@ func (v *Vertex) IsOptional(label Feature) bool { } func (v *Vertex) accepts(ok, required bool) bool { - return ok || (!required && !v.Closed) + return ok || (!required && !v.ClosedRecursive) } func (v *Vertex) IsClosedStruct() bool { @@ -946,7 +1105,7 @@ func (v *Vertex) IsClosedStruct() bool { return false case *Vertex: - return v.Closed && !v.HasEllipsis + return v.ClosedRecursive && !v.HasEllipsis case *StructMarker: if x.NeedClose { @@ -1151,6 +1310,7 @@ func (v *Vertex) GetArc(c *OpContext, f Feature, t ArcType) (arc *Vertex, isNew Label: f, ArcType: t, nonRooted: v.IsDynamic || v.Label.IsLet() || v.nonRooted, + anonymous: v.anonymous || v.Label.IsLet(), } v.Arcs = append(v.Arcs, arc) if t == ArcPending { @@ -1168,6 +1328,20 @@ func (v *Vertex) Source() ast.Node { return nil } +// InsertConjunct is a low-level method to insert a conjunct into a Vertex. +// It should only be used by the compiler. It does not consider any logic +// that is necessary if a conjunct is added to a Vertex that is already being +// evaluated. +func (v *Vertex) InsertConjunct(c Conjunct) { + v.Conjuncts = append(v.Conjuncts, c) +} + +// InsertConjunctsFrom is a low-level method to insert a conjuncts into a Vertex +// from another Vertex. +func (v *Vertex) InsertConjunctsFrom(w *Vertex) { + v.Conjuncts = append(v.Conjuncts, w.Conjuncts...) +} + // AddConjunct adds the given Conjuncts to v if it doesn't already exist. func (v *Vertex) AddConjunct(c Conjunct) *Bottom { if v.BaseValue != nil && !isCyclePlaceholder(v.BaseValue) { @@ -1175,7 +1349,10 @@ func (v *Vertex) AddConjunct(c Conjunct) *Bottom { // change the order of fields in some cases. // // This is likely a bug in the evaluator and should not happen. - return &Bottom{Err: errors.Newf(token.NoPos, "cannot add conjunct")} + return &Bottom{ + Err: errors.Newf(token.NoPos, "cannot add conjunct"), + Node: v, + } } if !v.hasConjunct(c) { v.addConjunctUnchecked(c) @@ -1193,19 +1370,23 @@ func (v *Vertex) hasConjunct(c Conjunct) (added bool) { default: v.ArcType = ArcMember } - return hasConjunct(v.Conjuncts, c) + return findConjunct(v.Conjuncts, c) >= 0 } -func hasConjunct(cs []Conjunct, c Conjunct) bool { - for _, x := range cs { +// findConjunct reports the position of c within cs or -1 if it is not found. +// +// NOTE: we are not comparing closeContexts. The intended use of this function +// is only to add to list of conjuncts within a closeContext. +func findConjunct(cs []Conjunct, c Conjunct) int { + for i, x := range cs { // TODO: disregard certain fields from comparison (e.g. Refs)? - if x.CloseInfo.closeInfo == c.CloseInfo.closeInfo && + if x.CloseInfo.closeInfo == c.CloseInfo.closeInfo && // V2 x.x == c.x && x.Env.Up == c.Env.Up && x.Env.Vertex == c.Env.Vertex { - return true + return i } } - return false + return -1 } func (n *nodeContext) addConjunction(c Conjunct, index int) { @@ -1277,6 +1458,16 @@ func (v *Vertex) AddStruct(s *StructLit, env *Environment, ci CloseInfo) *Struct Env: env, CloseInfo: ci, } + if env.Vertex != nil { + // be careful to avoid promotion of nil env.Vertex to non-nil + // info.Decl + info.Decl = env.Vertex + } + if cc := ci.cc; cc != nil && cc.decl != nil { + info.Decl = cc.decl + } else if ci := ci.closeInfo; ci != nil && ci.decl != nil { + info.Decl = ci.decl + } for _, t := range v.Structs { if *t == info { // TODO: check for different identity. return t @@ -1300,7 +1491,10 @@ func appendPath(a []Feature, v *Vertex) []Feature { return a } a = appendPath(a, v.Parent) - if v.Label != 0 { + // Skip if the node is a structure-shared node that has been assingned to + // the parent as it's new location: in this case the parent node will + // have the desired label. + if v.Label != 0 && v.Parent.BaseValue != v { // A Label may be 0 for programmatically inserted nodes. a = append(a, v.Label) } @@ -1318,6 +1512,11 @@ type Conjunct struct { CloseInfo CloseInfo } +// MakeConjunct creates a conjunct from current Environment and CloseInfo of c. +func (c *OpContext) MakeConjunct(x Expr) Conjunct { + return MakeConjunct(c.e, x, c.ci) +} + // TODO(perf): replace with composite literal if this helps performance. // MakeRootConjunct creates a conjunct from the given environment and node. @@ -1354,7 +1553,7 @@ func (c *Conjunct) Field() Node { // Elem retrieves the Elem form of the contained conjunct. // If it is a Field, it will return the field value. -func (c *Conjunct) Elem() Elem { +func (c Conjunct) Elem() Elem { switch x := c.x.(type) { case interface{ expr() Expr }: return x.expr() diff --git a/vendor/cuelang.org/go/internal/core/adt/comprehension.go b/vendor/cuelang.org/go/internal/core/adt/comprehension.go index 5cdd2ed61c..d2a4ddc05c 100644 --- a/vendor/cuelang.org/go/internal/core/adt/comprehension.go +++ b/vendor/cuelang.org/go/internal/core/adt/comprehension.go @@ -160,6 +160,7 @@ func (n *nodeContext) insertComprehension( if !n.ctx.isDevVersion() { ci = ci.SpawnEmbed(c) ci.closeInfo.span |= ComprehensionSpan + ci.decl = c } var decls []Decl @@ -216,7 +217,11 @@ func (n *nodeContext) insertComprehension( conjunct := MakeConjunct(env, c, ci) n.assertInitialized() arc := n.insertFieldUnchecked(f.Label, ArcMember, conjunct) - arc.MultiLet = f.IsMulti + if n.ctx.isDevVersion() { + arc.MultiLet = true + } else { + arc.MultiLet = f.IsMulti + } fields = append(fields, f) @@ -463,29 +468,20 @@ func (n *nodeContext) processComprehensionInner(d *envYield, state vertexStatus) d.inserted = true if len(d.envs) == 0 { - c := d.leaf - for p := c.arcCC; p != nil; p = p.parent { - // because the parent referrer will reach a zero count before this - // node will reach a zero count, we need to propagate the arcType. - p.updateArcType(ArcNotPresent) - } + c := d.leaf.arcCC + // because the parent referrer will reach a zero count before this + // node will reach a zero count, we need to propagate the arcType. + c.updateArcType(ctx, ArcNotPresent) return nil } v := n.node - f := v.Label for c := d.leaf; c.parent != nil; c = c.parent { // because the parent referrer will reach a zero count before this // node will reach a zero count, we need to propagate the arcType. - for arc, p := c.arcCC, c.cc; p != nil; arc, p = arc.parent, p.parent { - // TODO: remove this line once we use the arcType of the - // closeContext in notAllowedError. - arc.src.updateArcType(c.arcType) - t := arc.arcType - arc.updateArcType(c.arcType) - if p.isClosed && t >= ArcPending && !matchPattern(ctx, p.Expr, f) { - ctx.notAllowedError(p.src, arc.src) - } + if p := c.arcCC; p != nil { + p.src.updateArcType(c.arcType) + p.updateArcType(ctx, c.arcType) } v.updateArcType(c.arcType) if v.ArcType == ArcNotPresent { @@ -500,6 +496,9 @@ func (n *nodeContext) processComprehensionInner(d *envYield, state vertexStatus) } id := d.id + // TODO: should we treat comprehension values as optional? + // It seems so, but it causes some hangs. + // id.setOptional(nil) for _, env := range d.envs { if n.node.ArcType == ArcNotPresent { diff --git a/vendor/cuelang.org/go/internal/core/adt/conjunct.go b/vendor/cuelang.org/go/internal/core/adt/conjunct.go index b0701a69e7..5150f2b8e3 100644 --- a/vendor/cuelang.org/go/internal/core/adt/conjunct.go +++ b/vendor/cuelang.org/go/internal/core/adt/conjunct.go @@ -18,6 +18,8 @@ import ( "fmt" "cuelang.org/go/cue/ast" + "cuelang.org/go/cue/errors" + "cuelang.org/go/cue/token" ) // This file contains functionality for processing conjuncts to insert the @@ -78,10 +80,13 @@ func (n *nodeContext) scheduleConjunct(c Conjunct, id CloseInfo) { if c.CloseInfo.FromDef { t |= closeDef } - if c.CloseInfo.FromEmbed { + // NOTE: the check for OpenInline is not strictly necessary, but it + // clarifies that using id.FromEmbed is not used when OpenInline is not + // used. + if c.CloseInfo.FromEmbed || (n.ctx.OpenInline && id.FromEmbed) { t |= closeEmbed } - if t != 0 { + if t != 0 || c.CloseInfo.GroupUnify { id, _ = id.spawnCloseContext(n.ctx, t) } if !id.cc.done { @@ -90,7 +95,13 @@ func (n *nodeContext) scheduleConjunct(c Conjunct, id CloseInfo) { } if id.cc.src != n.node { - panic("inconsistent state: nodes differ") + // TODO(#3406): raise a panic again. + // out: d & { d } + // d: { + // kind: "foo" | "bar" + // { kind: "foo" } | { kind: "bar" } + // } + // panic("inconsistent state: nodes differ") } default: @@ -113,7 +124,7 @@ func (n *nodeContext) scheduleConjunct(c Conjunct, id CloseInfo) { env := c.Env if id.cc.isDef { - n.node.Closed = true + n.node.ClosedRecursive = true } switch x := c.Elem().(type) { @@ -175,22 +186,27 @@ func (n *nodeContext) scheduleConjunct(c Conjunct, id CloseInfo) { n.unshare() // At this point we known we have at least an empty list. - n.updateCyclicStatus(id) + n.updateCyclicStatusV3(id) env := &Environment{ Up: env, Vertex: n.node, } + n.updateNodeType(ListKind, x, id) n.scheduleTask(handleListLit, env, x, id) case *DisjunctionExpr: n.unshare() + id := id + id.setOptionalV3(n) // TODO(perf): reuse envDisjunct values so that we can also reuse the // disjunct slice. + n.ctx.holeID++ d := envDisjunct{ env: env, cloneID: id, + holeID: n.ctx.holeID, src: x, expr: x, } @@ -228,7 +244,7 @@ func (n *nodeContext) scheduleConjunct(c Conjunct, id CloseInfo) { func (n *nodeContext) scheduleStruct(env *Environment, s *StructLit, ci CloseInfo) { - n.updateCyclicStatus(ci) + n.updateCyclicStatusV3(ci) // NOTE: This is a crucial point in the code: // Unification dereferencing happens here. The child nodes are set to @@ -270,10 +286,14 @@ loop2: case *Comprehension, Expr: // No need to increment and decrement, as there will be at least // one entry. - if _, ok := s.Src.(*ast.File); !ok { + if _, ok := s.Src.(*ast.File); !ok && s.Src != nil { // If this is not a file, the struct indicates the scope/ // boundary at which closedness should apply. This is not true // for files. + // We should also not spawn if this is a nested Comprehension, + // where the spawn is already done as it may lead to spurious + // field not allowed errors. We can detect this with a nil s.Src. + // TODO(evalv3): use a more principled detection mechanism. // TODO: set this as a flag in StructLit so as to not have to // do the somewhat dangerous cast here. ci, _ = ci.spawnCloseContext(n.ctx, 0) @@ -293,6 +313,11 @@ loop2: n.aStruct = s n.aStructID = ci } + ci := ci + if x.ArcType == ArcOptional { + ci.setOptionalV3(n) + } + fc := MakeConjunct(childEnv, x, ci) // fc.CloseInfo.cc = nil // TODO: should we add this? n.insertArc(x.Label, x.ArcType, fc, ci, true) @@ -303,6 +328,7 @@ loop2: case *Comprehension: ci, cc := ci.spawnCloseContext(n.ctx, closeEmbed) + cc.decl = x cc.incDependent(n.ctx, DEFER, nil) defer cc.decDependent(n.ctx, DEFER, nil) n.insertComprehension(childEnv, x, ci) @@ -312,6 +338,7 @@ loop2: // Can be added unconditionally to patterns. ci.cc.isDef = false ci.cc.isClosed = false + ci.cc.isDefOrig = false case *DynamicField: if x.ArcType == ArcMember { @@ -321,6 +348,8 @@ loop2: n.scheduleTask(handleDynamic, childEnv, x, ci) case *BulkOptionalField: + ci := ci + ci.setOptionalV3(n) // All do not depend on each other, so can be added at once. n.scheduleTask(handlePatternConstraint, childEnv, x, ci) @@ -328,6 +357,7 @@ loop2: case Expr: // TODO: perhaps special case scalar Values to avoid creating embedding. ci, cc := ci.spawnCloseContext(n.ctx, closeEmbed) + cc.decl = x // TODO: do we need to increment here? cc.incDependent(n.ctx, DEFER, nil) // decrement deferred below @@ -339,7 +369,7 @@ loop2: } } if hasEllipsis { - ci.cc.hasEllipsis = true + ci.cc.isTotal = true } if !hasEmbed { n.aStruct = s @@ -356,6 +386,9 @@ loop2: func (n *nodeContext) scheduleVertexConjuncts(c Conjunct, arc *Vertex, closeInfo CloseInfo) { // disjunctions, we need to dereference he underlying node. if deref(n.node) == deref(arc) { + if n.isShared { + n.addShared(closeInfo) + } return } @@ -394,14 +427,30 @@ func (n *nodeContext) scheduleVertexConjuncts(c Conjunct, arc *Vertex, closeInfo } n.arcMap = append(n.arcMap, key) - if IsDef(c.Expr()) { - // TODO: or should we always insert the wrapper (for errors)? - ci, dc := closeInfo.spawnCloseContext(n.ctx, closeDef) - closeInfo = ci - - dc.incDependent(n.ctx, DEFER, nil) // decrement deferred below - defer dc.decDependent(n.ctx, DEFER, nil) + mode := closeRef + isDef, relDepth := IsDef(c.Expr()) + // Also check arc.Label: definitions themselves do not have the FromDef + // and corresponding closeContexts to reflect their closedness. This means + // that if we are structure sharing, we may end up with a Vertex that is + // a definition without the reference reflecting that. We need to handle + // this case here and create a closeContext accordingly. Note that if an + // intermediate node refers to a definition, things are evaluated at least + // once and the closeContext is in place. + // See eval/closedness.txtar/test patterns.*.indirect. + // TODO: investigate whether we should add the corresponding closeContexts + // within definitions as well to avoid having to deal with these special + // cases. + if isDef || arc.Label.IsDef() { + mode = closeDef } + depth := VertexDepth(arc) - relDepth + + // TODO: or should we always insert the wrapper (for errors)? + ci, dc := closeInfo.spawnCloseContext(n.ctx, mode) + closeInfo = ci + + dc.incDependent(n.ctx, DEFER, nil) // decrement deferred below + defer dc.decDependent(n.ctx, DEFER, nil) if !n.node.nonRooted || n.node.IsDynamic { if state := arc.getBareState(n.ctx); state != nil { @@ -409,37 +458,81 @@ func (n *nodeContext) scheduleVertexConjuncts(c Conjunct, arc *Vertex, closeInfo } } - if d, ok := arc.BaseValue.(*Disjunction); ok && false { - n.scheduleConjunct(MakeConjunct(c.Env, d, closeInfo), closeInfo) - } else { - for i := 0; i < len(arc.Conjuncts); i++ { - c := arc.Conjuncts[i] + // Use explicit index in case Conjuncts grows during iteration. + for i := 0; i < len(arc.Conjuncts); i++ { + c := arc.Conjuncts[i] + n.insertAndSkipConjuncts(c, closeInfo, depth) + } - // Note that we are resetting the tree here. We hereby assume that - // closedness conflicts resulting from unifying the referenced arc were - // already caught there and that we can ignore further errors here. - // c.CloseInfo = closeInfo + if state := arc.getBareState(n.ctx); state != nil { + n.toComplete = true + } +} - // We can use the original, but we know it will not be used +// insertAndSkipConjuncts cuts the conjunct tree at the given relative depth. +// The CUE spec defines references to be closed if they cross definition +// boundaries. The conjunct tree tracks the origin of conjuncts, for instance, +// whether they originate from a definition or embedding. This allows these +// properties to hold even if a conjunct was referred indirectly. +// +// However, references within a referred Vertex, even though their conjunct +// tree reflects the full history, should exclude any of the tops of this +// tree that were not "crossed". +// +// TODO(evalv3): Consider this example: +// +// #A: { +// b: {} +// c: b & { +// d: 1 +// } +// } +// x: #A +// x: b: g: 1 +// +// Here, x.b is set to contain g. This is disallowed by #A and this will fail. +// However, if we were to leave out x.b.g, x.b.c would still reference x.b +// through #A. Even though, x.b is closed and empty, this should not cause an +// error, as the reference should not apply to fields that were added within +// #A itself. Just because #A is reference should not alter its correctness. +// +// The algorithm to detect this keeps track of the relative depth of references. +// Whenever a reference is resolved, all conjuncts that correspond to a given +// depth less than the depth of the referred node are skipped. +// +// Note that the relative depth of references can be applied to any node, +// even if this reference was defined in another struct. +func (n *nodeContext) insertAndSkipConjuncts(c Conjunct, id CloseInfo, depth int) { + if c.CloseInfo.cc == nil { + n.scheduleConjunct(c, id) + return + } - n.scheduleConjunct(c, closeInfo) + if c.CloseInfo.cc.depth <= depth { + if x, ok := c.Elem().(*ConjunctGroup); ok { + for _, c := range *x { + n.insertAndSkipConjuncts(c, id, depth) + } + return } } - if state := arc.getBareState(n.ctx); state != nil { - n.toComplete = true - } + n.scheduleConjunct(c, id) } -func (n *nodeContext) addNotify2(v *Vertex, c CloseInfo) []receiver { +func (n *nodeContext) addNotify2(v *Vertex, c CloseInfo) { + // scheduleConjunct should ensure that the closeContext of of c is aligned + // with v. We rely on this to be the case here. We enforce this invariant + // here for clarity and to ensure correctness. + n.ctx.Assertf(token.NoPos, c.cc.src == v, "close context not aligned with vertex") + // No need to do the notification mechanism if we are already complete. - old := n.notify switch { case n.node.isFinal(): - return old + return case !n.node.isInProgress(): case n.meets(allAncestorsProcessed): - return old + return } // Create a "root" closeContext to reflect the entry point of the @@ -450,47 +543,59 @@ func (n *nodeContext) addNotify2(v *Vertex, c CloseInfo) []receiver { // is even possible by adding a panic. root := n.node.rootCloseContext(n.ctx) if root.isDecremented { - return old + return } for _, r := range n.notify { - if r.v == v && r.cc == c.cc { - return old + if r.cc == c.cc { + return } } cc := c.cc - if root.linkNotify(n.ctx, v, cc, c.CycleInfo) { - n.notify = append(n.notify, receiver{v, cc}) + // TODO: it should not be necessary to register for notifications for + // let expressions, so we could also filter for !n.node.Label.IsLet(). + // However, somehow this appears to result in slightly better error + // messages. + if root.addNotifyDependency(n.ctx, cc) { + // TODO: this is mostly identical to the slice in the root closeContext. + // Use only one once V2 is removed. + n.notify = append(n.notify, receiver{cc.src, cc}) } - - return old } // Literal conjuncts +// NoSharingSentinel is a sentinel value that is used to disable sharing of +// nodes. We make this an error to make it clear that we discard the value. +var NoShareSentinel = &Bottom{ + Err: errors.Newf(token.NoPos, "no sharing"), +} + func (n *nodeContext) insertValueConjunct(env *Environment, v Value, id CloseInfo) { - n.updateCyclicStatus(id) + n.updateCyclicStatusV3(id) ctx := n.ctx switch x := v.(type) { case *Vertex: - if m, ok := x.BaseValue.(*StructMarker); ok { + if x.ClosedNonRecursive { + n.node.ClosedNonRecursive = true + var cc *closeContext + id, cc = id.spawnCloseContext(n.ctx, 0) + cc.incDependent(n.ctx, DEFER, nil) + defer cc.decDependent(n.ctx, DEFER, nil) + cc.isClosedOnce = true + + if v, ok := x.BaseValue.(*Vertex); ok { + n.insertValueConjunct(env, v, id) + return + } + } + if _, ok := x.BaseValue.(*StructMarker); ok { n.aStruct = x n.aStructID = id - if m.NeedClose { - // TODO: In the new evaluator this is used to mark a struct - // as closed in the debug output. Once the old evaluator is - // gone, we could simplify this. - id.IsClosed = true - if ctx.isDevVersion() { - var cc *closeContext - id, cc = id.spawnCloseContext(n.ctx, 0) - cc.isClosedOnce = true - } - } } if !x.IsData() { @@ -505,7 +610,7 @@ func (n *nodeContext) insertValueConjunct(env *Environment, v Value, id CloseInf panic(fmt.Sprintf("invalid type %T", x.BaseValue)) case *ListMarker: - n.updateCyclicStatus(id) + n.updateCyclicStatusV3(id) // TODO: arguably we know now that the type _must_ be a list. n.scheduleTask(handleListVertex, env, x, id) @@ -529,6 +634,10 @@ func (n *nodeContext) insertValueConjunct(env *Environment, v Value, id CloseInf return case *Bottom: + if x == NoShareSentinel { + n.unshare() + return + } id.cc.hasNonTop = true n.addBottom(x) return @@ -549,9 +658,14 @@ func (n *nodeContext) insertValueConjunct(env *Environment, v Value, id CloseInf case *Disjunction: // TODO(perf): reuse envDisjunct values so that we can also reuse the // disjunct slice. + id := id + id.setOptionalV3(n) + + n.ctx.holeID++ d := envDisjunct{ env: env, cloneID: id, + holeID: n.ctx.holeID, src: x, value: x, } @@ -584,13 +698,13 @@ func (n *nodeContext) insertValueConjunct(env *Environment, v Value, id CloseInf switch x.Op { case LessThanOp, LessEqualOp: if y := n.upperBound; y != nil { - n.upperBound = nil v := SimplifyBounds(ctx, n.kind, x, y) if err := valueError(v); err != nil { err.AddPosition(v) err.AddPosition(n.upperBound) err.AddClosedPositions(id) } + n.upperBound = nil n.insertValueConjunct(env, v, id) return } @@ -598,13 +712,13 @@ func (n *nodeContext) insertValueConjunct(env *Environment, v Value, id CloseInf case GreaterThanOp, GreaterEqualOp: if y := n.lowerBound; y != nil { - n.lowerBound = nil v := SimplifyBounds(ctx, n.kind, x, y) if err := valueError(v); err != nil { err.AddPosition(v) err.AddPosition(n.lowerBound) err.AddClosedPositions(id) } + n.lowerBound = nil n.insertValueConjunct(env, v, id) return } @@ -615,7 +729,7 @@ func (n *nodeContext) insertValueConjunct(env *Environment, v Value, id CloseInf k := 0 match := false for _, c := range n.checks { - if y, ok := c.(*BoundValue); ok { + if y, ok := c.x.(*BoundValue); ok { switch z := SimplifyBounds(ctx, n.kind, x, y); { case z == y: match = true @@ -628,21 +742,43 @@ func (n *nodeContext) insertValueConjunct(env *Environment, v Value, id CloseInf } n.checks = n.checks[:k] if !match { - n.checks = append(n.checks, x) + n.checks = append(n.checks, MakeConjunct(env, x, id)) } return } case Validator: // This check serves as simplifier, but also to remove duplicates. + cx := MakeConjunct(env, x, id) + kind := x.Kind() + // A validator that is inserted in a closeContext should behave like top + // in the sense that the closeContext should not be closed if no other + // value is present that would erase top (cc.hasNonTop): if a field is + // only associated with a validator, we leave it to the validator to + // decide what fields are allowed. + if kind&(ListKind|StructKind) != 0 { + id.cc.hasTop = true + } + for i, y := range n.checks { - if b := SimplifyValidator(ctx, x, y); b != nil { + if b, ok := SimplifyValidator(ctx, cx, y); ok { n.checks[i] = b return } } - n.updateNodeType(x.Kind(), x, id) - n.checks = append(n.checks, x) + + n.checks = append(n.checks, cx) + + // We use set the type of the validator argument here to ensure that + // validation considers the ultimate value of embedded validators, + // rather than assuming that the struct in which an expression is + // embedded is always a struct. + // TODO(validatorType): get rid of setting n.hasTop here. + k := x.Kind() + if k == TopKind { + n.hasTop = true + } + n.updateNodeType(k, x, id) case *Vertex: // handled above. diff --git a/vendor/cuelang.org/go/internal/core/adt/constraints.go b/vendor/cuelang.org/go/internal/core/adt/constraints.go index fe78f4dd75..07b3bc8eb2 100644 --- a/vendor/cuelang.org/go/internal/core/adt/constraints.go +++ b/vendor/cuelang.org/go/internal/core/adt/constraints.go @@ -93,14 +93,27 @@ func (n *nodeContext) insertConstraint(pattern Value, c Conjunct) bool { } if constraint == nil { - constraint = &Vertex{} + constraint = &Vertex{ + // See "Self-referencing patterns" in cycle.go + IsPatternConstraint: true, + } pcs.Pairs = append(pcs.Pairs, PatternConstraint{ Pattern: pattern, Constraint: constraint, }) - } else if constraint.hasConjunct(c) { + } else { + found := false + constraint.VisitLeafConjuncts(func(x Conjunct) bool { + if c.CloseInfo.cc == x.CloseInfo.cc && c.x == x.x { + found = true + return false + } + return true + }) // The constraint already existed and the conjunct was already added. - return false + if found { + return false + } } constraint.addConjunctUnchecked(c) @@ -109,6 +122,8 @@ func (n *nodeContext) insertConstraint(pattern Value, c Conjunct) bool { // matchPattern reports whether f matches pattern. The result reflects // whether unification of pattern with f converted to a CUE value succeeds. +// The caller should check separately whether f matches any other arcs +// that are not covered by pattern. func matchPattern(ctx *OpContext, pattern Value, f Feature) bool { if pattern == nil || !f.IsRegular() { return false @@ -134,6 +149,9 @@ func matchPattern(ctx *OpContext, pattern Value, f Feature) bool { // This is an optimization an intended to be faster than regular CUE evaluation // for the majority of cases where pattern constraints are used. func matchPatternValue(ctx *OpContext, pattern Value, f Feature, label Value) (result bool) { + if v, ok := pattern.(*Vertex); ok { + v.unify(ctx, scalarKnown, finalize) + } pattern = Unwrap(pattern) label = Unwrap(label) @@ -155,11 +173,13 @@ func matchPatternValue(ctx *OpContext, pattern Value, f Feature, label Value) (r // TODO: hoist and reuse with the identical code in optional.go. if x == cycle { err := ctx.NewPosf(pos(pattern), "cyclic pattern constraint") - for _, c := range ctx.vertex.Conjuncts { + ctx.vertex.VisitLeafConjuncts(func(c Conjunct) bool { addPositions(err, c) - } + return true + }) ctx.AddBottom(&Bottom{ - Err: err, + Err: err, + Node: ctx.vertex, }) } if ctx.errs == nil { @@ -182,7 +202,7 @@ func matchPatternValue(ctx *OpContext, pattern Value, f Feature, label Value) (r str := label.(*String).Str return x.validateStr(ctx, str) - case NumKind: + case NumberKind: return x.validateInt(ctx, int64(f.Index())) } diff --git a/vendor/cuelang.org/go/internal/core/adt/context.go b/vendor/cuelang.org/go/internal/core/adt/context.go index 9e42ba9402..93b402063a 100644 --- a/vendor/cuelang.org/go/internal/core/adt/context.go +++ b/vendor/cuelang.org/go/internal/core/adt/context.go @@ -16,11 +16,8 @@ package adt import ( "fmt" - "log" "reflect" "regexp" - "sort" - "strings" "github.com/cockroachdb/apd/v3" "golang.org/x/text/encoding/unicode" @@ -33,122 +30,6 @@ import ( "cuelang.org/go/internal/cuedebug" ) -// DebugSort specifies that arcs be sorted consistently between implementations. -// -// 0: default -// 1: sort by Feature: this should be consistent between implementations where -// there is no change in the compiler and indexing code. -// 2: alphabetical -// -// TODO: move to DebugFlags -var DebugSort int - -func DebugSortArcs(c *OpContext, n *Vertex) { - if n.IsList() { - return - } - switch a := n.Arcs; DebugSort { - case 1: - sort.SliceStable(a, func(i, j int) bool { - return a[i].Label < a[j].Label - }) - case 2: - sort.SliceStable(a, func(i, j int) bool { - return a[i].Label.SelectorString(c.Runtime) < - a[j].Label.SelectorString(c.Runtime) - }) - } -} - -func DebugSortFields(c *OpContext, a []Feature) { - switch DebugSort { - case 1: - sort.SliceStable(a, func(i, j int) bool { - return a[i] < a[j] - }) - case 2: - sort.SliceStable(a, func(i, j int) bool { - return a[i].SelectorString(c.Runtime) < - a[j].SelectorString(c.Runtime) - }) - } -} - -// Assert panics if the condition is false. Assert can be used to check for -// conditions that are considers to break an internal variant or unexpected -// condition, but that nonetheless probably will be handled correctly down the -// line. For instance, a faulty condition could lead to error being caught -// down the road, but resulting in an inaccurate error message. In production -// code it is better to deal with the bad error message than to panic. -// -// It is advisable for each use of Assert to document how the error is expected -// to be handled down the line. -func Assertf(c *OpContext, b bool, format string, args ...interface{}) { - if c.Strict && !b { - panic(fmt.Sprintf("assertion failed: "+format, args...)) - } -} - -// Assertf either panics or reports an error to c if the condition is not met. -func (c *OpContext) Assertf(pos token.Pos, b bool, format string, args ...interface{}) { - if !b { - if c.Strict { - panic(fmt.Sprintf("assertion failed: "+format, args...)) - } - c.addErrf(0, pos, format, args...) - } -} - -func init() { - log.SetFlags(log.Lshortfile) -} - -var pMap = map[*Vertex]int{} - -func (c *OpContext) Logf(v *Vertex, format string, args ...interface{}) { - if c.LogEval == 0 { - return - } - if v == nil { - s := fmt.Sprintf(strings.Repeat("..", c.nest)+format, args...) - _ = log.Output(2, s) - return - } - p := pMap[v] - if p == 0 { - p = len(pMap) + 1 - pMap[v] = p - } - a := append([]interface{}{ - strings.Repeat("..", c.nest), - p, - v.Label.SelectorString(c), - v.Path(), - }, args...) - for i := 2; i < len(a); i++ { - switch x := a[i].(type) { - case Node: - a[i] = c.Str(x) - case Feature: - a[i] = x.SelectorString(c) - } - } - s := fmt.Sprintf("%s [%d] %s/%v"+format, a...) - _ = log.Output(2, s) -} - -// PathToString creates a pretty-printed path of the given list of features. -func (c *OpContext) PathToString(path []Feature) string { - var b strings.Builder - for i, f := range path { - if i > 0 { - b.WriteByte('.') - } - b.WriteString(f.SelectorString(c)) - } - return b.String() -} - // Runtime defines an interface for low-level representation conversion and // lookup. type Runtime interface { @@ -167,7 +48,9 @@ type Runtime interface { // type if available. LoadType(t reflect.Type) (src ast.Expr, expr Expr, ok bool) - Settings() (internal.EvaluatorVersion, cuedebug.Config) + // ConfigureOpCtx configures the [*OpContext] with details such as + // evaluator version, debug options etc. + ConfigureOpCtx(ctx *OpContext) } type Config struct { @@ -180,22 +63,26 @@ func New(v *Vertex, cfg *Config) *OpContext { if cfg.Runtime == nil { panic("nil Runtime") } - version, flags := cfg.Runtime.Settings() + ctx := &OpContext{ Runtime: cfg.Runtime, Format: cfg.Format, vertex: v, - Version: version, - Config: flags, taskContext: schedConfig, } + cfg.Runtime.ConfigureOpCtx(ctx) + ctx.stats.EvalVersion = ctx.Version if v != nil { ctx.e = &Environment{Up: nil, Vertex: v} } return ctx } +// See also: [unreachableForDev] func (c *OpContext) isDevVersion() bool { + if c.Version == internal.EvalVersionUnset { + panic("OpContext was not provided with an evaluator version") + } return c.Version == internal.DevVersion } @@ -208,7 +95,8 @@ type OpContext struct { Format func(Runtime, Node) string cuedebug.Config - Version internal.EvaluatorVersion // Copied from Runtime + Version internal.EvaluatorVersion // Copied from Runtime + TopoSort bool // Copied from Runtime taskContext @@ -228,6 +116,12 @@ type OpContext struct { // structural cycle errors. vertex *Vertex + // list of vertices that need to be finalized. + // TODO: remove this again once we have a proper way of detecting references + // across optional boundaries in hasAncestorV3. We can probably do this + // with an optional depth counter. + toFinalize []*Vertex + // These fields are used associate scratch fields for computing closedness // of a Vertex. These fields could have been included in StructInfo (like // Tomabechi's unification algorithm), but we opted for an indirection to @@ -249,6 +143,10 @@ type OpContext struct { // encountered. A value of 0 indicates we are not within such field. optionalMark int + // holdID is a unique identifier for the current "hole", a choice of + // disjunct to be made when processing disjunctions. + holeID int + // inDisjunct indicates that non-monotonic checks should be skipped. // This is used if we want to do some extra work to eliminate disjunctions // early. The result of unification should be thrown away if this check is @@ -262,6 +160,16 @@ type OpContext struct { // enabled. inConstraint int + // inLiteralSelectee indicates that we are evaluating a literal struct + // as the receiver of a selector. This is used to turn off closedness + // checking in compatibility mode. + inLiteralSelectee int + + // inDetached indicates that inline structs evaluated in the current context + // should never be shared. This is the case, for instance, with the source + // for the for clause in a comprehension. + inDetached int + // inValidator defines whether full evaluation need to be enforced, for // instance when comparing against bottom. inValidator int @@ -273,9 +181,16 @@ type OpContext struct { // TODO: strictly separate validators and functions. IsValidator bool + // ==== Debugging ==== + logID int // sequence number for log messages + // ErrorGraphs contains an analysis, represented as a Mermaid graph, for // each node that has an error. ErrorGraphs map[string]string + + currentDisjunctionID int // sequence number for call to processDisjunctions + + disjunctStack []disjunctInfo // stack of disjunct IDs } func (c *OpContext) CloseInfo() CloseInfo { return c.ci } @@ -382,7 +297,11 @@ func (c *OpContext) addErrf(code ErrorCode, pos token.Pos, msg string, args ...i } func (c *OpContext) addErr(code ErrorCode, err errors.Error) { - c.AddBottom(&Bottom{Code: code, Err: err}) + c.AddBottom(&Bottom{ + Code: code, + Err: err, + Node: c.vertex, + }) } // AddBottom records an error in OpContext. @@ -393,7 +312,10 @@ func (c *OpContext) AddBottom(b *Bottom) { // AddErr records an error in OpContext. It returns errors collected so far. func (c *OpContext) AddErr(err errors.Error) *Bottom { if err != nil { - c.AddBottom(&Bottom{Err: err}) + c.AddBottom(&Bottom{ + Err: err, + Node: c.vertex, + }) } return c.errs } @@ -404,7 +326,12 @@ func (c *OpContext) NewErrf(format string, args ...interface{}) *Bottom { // TODO: consider renaming ot NewBottomf: this is now confusing as we also // have Newf. err := c.Newf(format, args...) - return &Bottom{Src: c.src, Err: err, Code: EvalError} + return &Bottom{ + Src: c.src, + Err: err, + Code: EvalError, + Node: c.vertex, + } } // AddErrf records an error in OpContext. It returns errors collected so far. @@ -524,14 +451,23 @@ func (c *OpContext) Lookup(env *Environment, r Resolver) (*Vertex, *Bottom) { // // TODO(errors): return boolean instead: only the caller has enough information // to generate a proper error message. -func (c *OpContext) Validate(check Validator, value Value) *Bottom { +func (c *OpContext) Validate(check Conjunct, value Value) *Bottom { // TODO: use a position stack to push both values. - saved := c.src + + // TODO(evalv3): move to PushConjunct once the migration is complete. + // Using PushConjunct also saves and restores the error, which may be + // impactful, so we want to do this in a separate commit. + // saved := c.PushConjunct(check) + + src := c.src + ci := c.ci c.src = check.Source() + c.ci = check.CloseInfo - err := check.validate(c, value) + err := check.x.(Validator).validate(c, value) - c.src = saved + c.src = src + c.ci = ci return err } @@ -615,6 +551,7 @@ func (c *OpContext) Evaluate(env *Environment, x Expr) (result Value, complete b val = &Bottom{ Code: IncompleteError, Err: c.Newf("UNANTICIPATED ERROR"), + Node: env.Vertex, } } @@ -628,6 +565,20 @@ func (c *OpContext) Evaluate(env *Environment, x Expr) (result Value, complete b return val, true } +// EvaluateKeepState does an evaluate, but leaves any errors an cycle info +// within the context. +func (c *OpContext) EvaluateKeepState(x Expr) (result Value) { + src := c.src + c.src = x.Source() + + result, ci := c.evalStateCI(x, final(partial, concreteKnown)) + + c.src = src + c.ci = ci + + return result +} + func (c *OpContext) evaluateRec(v Conjunct, state combinedFlags) Value { x := v.Expr() s := c.PushConjunct(v) @@ -639,6 +590,7 @@ func (c *OpContext) evaluateRec(v Conjunct, state combinedFlags) Value { val = &Bottom{ Code: IncompleteError, Err: c.Newf("UNANTICIPATED ERROR"), + Node: c.vertex, } } _ = c.PopState(s) @@ -658,10 +610,18 @@ func (c *OpContext) value(x Expr, state combinedFlags) (result Value) { } func (c *OpContext) evalState(v Expr, state combinedFlags) (result Value) { + result, _ = c.evalStateCI(v, state) + return result +} + +func (c *OpContext) evalStateCI(v Expr, state combinedFlags) (result Value, ci CloseInfo) { savedSrc := c.src c.src = v.Source() err := c.errs c.errs = nil + // Save the old CloseInfo and restore after evaluate to avoid detecting + // spurious cycles. + saved := c.ci defer func() { c.errs = CombineErrors(c.src, c.errs, err) @@ -692,23 +652,29 @@ func (c *OpContext) evalState(v Expr, state combinedFlags) (result Value) { result = c.errs } c.src = savedSrc + + // TODO(evalv3): this c.ci should be passed to the caller who may need + // it to continue cycle detection for partially evaluated values. + // Either this or we must prove that this is covered by structural cycle + // detection. + c.ci = saved }() switch x := v.(type) { case Value: - return x + return x, c.ci case Evaluator: v := x.evaluate(c, state) - return v + return v, c.ci case Resolver: arc := x.resolve(c, state) if c.HasErr() { - return nil + return nil, c.ci } if arc == nil { - return nil + return nil, c.ci } // TODO(deref): what is the right level of dereferencing here? // DerefValue seems to work too. @@ -719,31 +685,29 @@ func (c *OpContext) evalState(v Expr, state combinedFlags) (result Value) { // TODO: is this indirect necessary? // arc = arc.Indirect() - // Save the old CloseInfo and restore after evaluate to avoid detecting - // spurious cycles. - saved := c.ci n := arc.state if c.isDevVersion() { n = arc.getState(c) - } - if n != nil { - c.ci, _ = n.markCycle(arc, nil, x, c.ci) + if n != nil { + c.ci, _ = n.detectCycleV3(arc, nil, x, c.ci) + } + } else { + if n != nil { + c.ci, _ = n.markCycle(arc, nil, x, c.ci) + } } c.ci.Inline = true if c.isDevVersion() { if s := arc.getState(c); s != nil { - needs := state.conditions() + needs := state.conditions() | arcTypeKnown runMode := state.runMode() - arc.unify(c, needs|arcTypeKnown, attemptOnly) // to set scalar - if runMode == finalize { - // arc.unify(c, needs, attemptOnly) // to set scalar - // Freeze node. + arc.unify(c, needs, attemptOnly) // to set scalar arc.state.freeze(needs) } else { - arc.unify(c, needs, runMode) + arc.unify(c, needs, runMode) // to set scalar } v := arc @@ -753,8 +717,8 @@ func (c *OpContext) evalState(v Expr, state combinedFlags) (result Value) { } err := c.Newf("cycle with field %v", x) b := &Bottom{Code: CycleError, Err: err} - v.setValue(c, v.status, b) - return b + s.setBaseValue(b) + return b, c.ci // TODO: use this instead, as is usual for incomplete errors, // and also move this block one scope up to also apply to // defined arcs. In both cases, though, doing so results in @@ -763,13 +727,13 @@ func (c *OpContext) evalState(v Expr, state combinedFlags) (result Value) { // return nil } c.undefinedFieldError(v, IncompleteError) - return nil + return nil, c.ci } } } v := c.evaluate(arc, x, state) - c.ci = saved - return v + + return v, c.ci default: // This can only happen, really, if v == nil, which is not allowed. @@ -851,11 +815,22 @@ func (c *OpContext) unifyNode(v Expr, state combinedFlags) (result Value) { if c.isDevVersion() { if n := v.getState(c); n != nil { + // A lookup counts as new structure. See the commend in Section + // "Lookups in inline cycles" in cycle.go. + n.hasNonCycle = true + // Always yield to not get spurious errors. n.process(arcTypeKnown, yield) + // It is possible that the node is only midway through + // evaluating a disjunction. In this case, we want to ensure + // that disjunctions are finalized, so that disjunction shows + // up in BaseValue. + if len(n.disjuncts) > 0 { + n.node.unify(c, arcTypeKnown, yield) + } } } else { - if v.isUndefined() || state.vertexStatus() > v.status { + if v.isUndefined() || state.vertexStatus() > v.Status() { c.unify(v, state) } } @@ -948,7 +923,9 @@ func (c *OpContext) lookup(x *Vertex, pos token.Pos, l Feature, flags combinedFl c.unify(a, deprecated(c, partial)) } - if a.IsConstraint() { + // TODO(refRequired): see comment in unify.go:Vertex.lookup near the + // namesake TODO. + if a.ArcType == ArcOptional { code := IncompleteError if hasCycle { code = CycleError @@ -959,6 +936,7 @@ func (c *OpContext) lookup(x *Vertex, pos token.Pos, l Feature, flags combinedFl Permanent: x.status >= conjuncts, Err: c.NewPosf(pos, "cannot reference optional field: %s", label), + Node: x, }) } } else { @@ -1005,6 +983,7 @@ func (c *OpContext) lookup(x *Vertex, pos token.Pos, l Feature, flags combinedFl Code: code, Permanent: permanent, Err: err, + Node: x, }) } return a @@ -1055,7 +1034,16 @@ func pos(x Node) token.Pos { return x.Source().Pos() } +// node is called by SelectorExpr.resolve and IndexExpr.resolve. func (c *OpContext) node(orig Node, x Expr, scalar bool, state combinedFlags) *Vertex { + if c.OpenInline { + if _, ok := x.(Resolver); !ok { + c.ci.FromEmbed = true + c.inLiteralSelectee++ + defer func() { c.inLiteralSelectee-- }() + } + } + // TODO: always get the vertex. This allows a whole bunch of trickery // down the line. v := c.unifyNode(x, state) @@ -1099,7 +1087,13 @@ func (c *OpContext) node(orig Node, x Expr, scalar bool, state combinedFlags) *V if node == nil { panic("unexpected markers with nil node") } - + // Needed for package dep: dep does partial evaluation of expressions + // while traversing values. Not evaluating the node here could lead + // to a lookup in an unevaluated node, resulting in erroneously failing + // lookups. + if c.isDevVersion() && nv.nonRooted { + nv.CompleteArcsOnly(c) + } default: if kind := v.Kind(); kind&StructKind != 0 { c.addErrf(IncompleteError, pos(x), @@ -1131,6 +1125,11 @@ func (c *OpContext) RawElems(v Value) []*Vertex { } func (c *OpContext) list(v Value) *Vertex { + if v != nil { + if a, ok := c.getDefault(v); ok { + v = a + } + } x, ok := v.(*Vertex) if !ok || !x.IsList() { c.typeError(v, ListKind) @@ -1149,7 +1148,7 @@ func (c *OpContext) scalar(v Value) Value { return v } -var zero = &Num{K: NumKind} +var zero = &Num{K: NumberKind} func (c *OpContext) Num(v Value, as interface{}) *Num { v = Unwrap(v) @@ -1158,7 +1157,7 @@ func (c *OpContext) Num(v Value, as interface{}) *Num { } x, ok := v.(*Num) if !ok { - c.typeErrorAs(v, NumKind, as) + c.typeErrorAs(v, NumberKind, as) return zero } return x @@ -1236,7 +1235,7 @@ func (c *OpContext) ToBytes(v Value) []byte { // ToString returns the string value of a scalar value. func (c *OpContext) ToString(v Value) string { - return c.toStringValue(v, StringKind|NumKind|BytesKind|BoolKind, nil) + return c.toStringValue(v, StringKind|NumberKind|BytesKind|BoolKind, nil) } diff --git a/vendor/cuelang.org/go/internal/core/adt/cycle.go b/vendor/cuelang.org/go/internal/core/adt/cycle.go index c22c535e2d..ceead75356 100644 --- a/vendor/cuelang.org/go/internal/core/adt/cycle.go +++ b/vendor/cuelang.org/go/internal/core/adt/cycle.go @@ -14,6 +14,348 @@ package adt +// TODO: +// - compiler support for detecting cross-pattern references. +// - handle propagation of cyclic references to root across disjunctions. + +// # Cycle detection algorithm V3 +// +// The cycle detection algorithm detects the following kind of cycles: +// +// - Structural cycles: cycles where a field, directly or indirectly, ends up +// referring to an ancestor node. For instance: +// +// a: b: a +// +// a: b: c +// c: a +// +// T: a?: T +// T: a: {} +// +// - Reference cycles: cycles where a field, directly or indirectly, end up +// referring to itself: +// a: a +// +// a: b +// b: a +// +// - Inline cycles: cycles within an expression, for instance: +// +// x: {y: x}.out +// +// Note that it is possible for the unification of two non-cyclic structs to be +// cyclic: +// +// y: { +// f: h: g +// g: _ +// } +// x: { +// f: _ +// g: f +// } +// +// Even though the above contains no cycles, the result of `x & y` is cyclic: +// +// f: h: g +// g: f +// +// Cycle detection is inherently a dynamic process. +// +// ## ALGORITHM OVERVIEW +// +// 1. Traversal with Path Tracking: +// • Perform a depth-first traversal of the CUE value graph. +// • Maintain a path (call stack) of ancestor nodes during traversal. +// For this purpose, we separately track the parent relation as well +// as marking nodes that are currently being processed. +// 2. Per-Conjunct Cycle Tracking: +// • For each conjunct in a node’s value (i.e., c1 & c2 & ... & cn), +// track cycles independently. +// • A node is considered non-cyclic if any of its conjuncts is +// non-cyclic. +// 3. Handling References: +// • When encountering a reference, check if it points to any node in the +// current path. +// • If yes, mark the conjunct as cyclic. +// • If no, add the referenced node to the path and continue traversal. +// 4. Handling Optional Constructs: +// • Conjuncts originating from optional fields, pattern constraints, and +// disjunctions are marked as optional. +// • Cycle tracking for optional conjuncts is identical to conjuncts for +// conjuncts not marked as optional up to the point a cycle is detected +// (i.e. all conjuncts are cyclic). +// • When a cycle is detected, the lists of referenced nodes are cleared +// for each conjuncts, which thereby are afforded one additional level +// of cycles. This allows for any optional paths to terminate. +// +// +// ## CALL STACK +// +// There are two key types of structural cycles: referencing an ancestor and +// repeated mixing in of cyclic types. We track these separately. +// +// We also keep track the non-cyclicity of conjuncts a bit differently for these +// cases. +// +// ### Ancestor References +// +// Ancestor references are relatively easy to detect by simply checking if a +// resolved reference is a direct parent, or is a node that is currently under +// evaluation. +// +// An ancestor cycle is considered to be a structural cycle if there are no +// new sibling conjuncts associated with new structure. +// +// ### Reoccurring references +// +// For reoccuring references, we need to maintain a per-conjunct list of +// references. When a reference was previously resolved in a conjunct, we may +// have a cycle and will mark the conjunct as such. +// +// A cycle from a reoccurring reference is a structural cycle if there are +// no incoming arcs from any non-cyclic conjunct. The need for this subtle +// distinction can be clarified by an example; +// +// crossRefNoCycle: t4: { +// T: X={ +// y: X.x +// } +// // Here C.x.y must consider any incoming arc: here T originates from +// // a non-cyclic conjunct, but once evaluated it becomes cyclic and +// // will be the only conjunct. This is not a cycle, though. We must +// // take into account that T was introduced from a non-cyclic +// // conjunct. +// C: T & { x: T } +// } +// +// +// ## OPTIONAL PATHS +// +// Cyclic references for conjuncts that originate from an "optional" path, such +// as optional fields and pattern constraints, may not necessary be cyclic, as +// on a next iteration such conjuncts _may_ still terminate. +// +// To allow for this kind of eventuality, optional conjuncts are processed in +// two phases: +// +// - they behave as normal conjuncts up to the point a cycle is detected +// - afterwards, their reference history is cleared and they are afforded to +// proceed until the next cycle is detected. +// +// Note that this means we may allow processing to proceed deeper than strictly +// necessary in some cases. +// +// Note that we only allow this for references: for cycles with ancestor nodes +// we immediately terminate for optional fields. This simplifies the algorithm. +// But it is also correct: in such cases either the whole node is in an optional +// path, in which case reporting an error is benign (as they are allowed), or +// the node corresponds to a non-optional field, in which case a cycle can be +// expected to reproduce another non-optional cycle, which will be an error. +// +// ### Examples +// +// These are not cyclic: +// +// 1. The structure is cyclic, but he optional field needs to be "fed" to +// continue the cycle: +// +// a: b?: a // a: {} +// +// b: [string]: b // b: {} +// +// c: 1 | {d: c} // c: 1 +// +// 2. The structure is cyclic. Conjunct `x: a` keeps detecting cycles, but +// is fed with new structure up until x.b.c.b.c.b. After this, this +// (optional) conjunct is allowed to proceed until the next cycle, which +// not be reached, as the `b?` is not unified with a concrete value. +// So the result of `x` is `{b: c: b: c: b: c: {}}`. +// +// a: b?: c: a +// x: a +// x: b: c: b: c: b: {} +// +// These are cyclic: +// +// 3. Here the optional conjunct triggers a new cycle of itself, but also +// of a conjunct that turns `b` into a regular field. It is thus a self- +// feeding cycle. +// +// a: b?: a +// a: b: _ +// +// c: [string]: c +// c: b: _ +// +// 4. Here two optional conjuncts end up feeding each other, resulting in a +// cycle. +// +// a: c: a | int +// a: a | int +// +// y1: c?: c: y1 +// x1: y1 +// x1: c: y1 +// +// y2: [string]: b: y2 +// x2: y2 +// x2: b: y2 +// +// +// ## INLINE CYCLES +// +// The semantics for treating inline cycles can be derived by rewriting CUE of +// the form +// +// x: {...}.out +// +// as +// +// x: _x.out +// _x: {...} +// +// A key difference is that as such structs are not "rooted" (they have no path +// from the root of the configuration tree) and thus any error should be caught +// and evaluated before doing a lookup in such structs to be correct. For the +// purpose of this algorithm, this especially pertains to structural cycles. +// +// TODO: implement: current handling of inline still loosly based on old +// algorithm. +// +// ### Examples +// +// Expanding these out with the above rules should give the same results. +// +// Cyclic: +// +// 1. This is an example of mutual recursion, triggered by n >= 2. +// +// fibRec: { +// nn: int, +// out: (fib & {n: nn}).out +// } +// fib: { +// n: int +// if n >= 2 { out: (fibRec & {nn: n - 2}).out } +// if n < 2 { out: n } +// } +// fib2: fib & {n: 2} +// +// is equivalent to +// +// fibRec: { +// nn: int, +// out: _out.out +// _out: fib & {n: nn} +// } +// fib: { +// n: int +// if n >= 2 { +// out: _out.out +// _out: fibRec & {nn: n - 2} +// } +// if n < 2 { out: n } +// } +// fib2: fib & {n: 2} +// +// Non-cyclic: +// +// 2. This is not dissimilar to the previous example, but since additions are +// done on separate lines, each field is only visited once and no cycle is +// triggered. +// +// f: { in: number, out: in } +// k00: 0 +// k10: (f & {in: k00}).out +// k20: (f & {in: k10}).out +// k10: (f & {in: k20}).out +// +// which is equivalent to +// +// f: { in: number, out: in } +// k0: 0 +// k1: _k1.out +// k2: _k2.out +// k1: _k3.out +// _k1: f +// _k2: f +// _k3: f +// _k1: in: k0 +// _k2: in: k1 +// _k3: in: k2 +// +// and thus is non-cyclic. +// +// ## EDGE CASES +// +// This section lists several edge cases, including interactions with the +// detection of self-reference cycles. +// +// Self-reference cycles, like `a: a`, evaluate to top. The evaluator detects +// this cases and drop such conjuncts, effectively treating them as top. +// +// ### Self-referencing patterns +// +// Self-references in patterns are typically handled automatically. But there +// are some edge cases where the are not: +// +// _self: x: [...and(x)] +// _self +// x: [1] +// +// Patterns are recorded in Vertex values that are themselves evaluated to +// allow them to be compared, such as in subsumption or filtering disjunctions. +// In the above case, `x` may be evaluated to be inserted in the pattern +// Vertex, but because the pattern is not itself `x`, node identity cannot be +// used to detect a self-reference. +// +// The current solution is to mark a node as a pattern constraint and treat +// structural cycles to such nodes as "reference cycles". As pattern constraints +// are optional, it is safe to ignore such errors. +// +// ### Lookups in inline cycles +// +// A lookup, especially in inline cycles, should be considered evidence of +// non-cyclicity. Consider the following example: +// +// { p: { x: p, y: 1 } }.p.x.y +// +// without considering a lookup as evidence of non-cyclicity, this would be +// resulting in a structural cycle. +// +// ## CORRECTNESS +// +// ### The algorithm will terminate +// +// First consider the algorithm without optional conjuncts. If a parent node is +// referenced, it will obviously be caught. The more interesting case is if a +// reference to a node is made which is later reintroduced. +// +// When a conjunct splits into multiple conjuncts, its entire cycle history is +// copied. This means that any cyclic conjunct will be marked as cyclic in +// perpetuity. Non-cyclic conjuncts will either remain non-cyclic or be turned +// into a cycle. A conjunct can only remain non-cyclic for a maximum of the +// number of nodes in a graph. For any structure to repeat, it must have a +// repeated reference. This means that eventually either all conjuncts will +// either terminate or become cyclic. +// +// Optional conjuncts do not materially alter this property. The only difference +// is that when a node-level cycle is detected, we continue processing of some +// conjuncts until this next cycle is reached. +// +// +// ## TODO +// +// - treatment of let fields +// - tighter termination for some mutual cycles in optional conjuncts. + +// DEPRECATED: V2 cycle detection. +// +// TODO(evalv3): remove these comments once we have fully moved to V3. +// + // Cycle detection: // // - Current algorithm does not allow for early non-cyclic conjunct detection. @@ -21,11 +363,6 @@ package adt // - Mark as cyclic if no evidence is found. // - Note that this also activates the same reference in other (parent) conjuncts. -// TODO: -// - get rid of nodeContext.{hasCycle|hasNonCycle}. -// - compiler support for detecting cross-pattern references. -// - handle propagation of cyclic references to root across disjunctions. - // CYCLE DETECTION ALGORITHM // // BACKGROUND @@ -209,9 +546,17 @@ package adt // Bob Carpenter, "The logic of typed feature structures." // Cambridge University Press, ISBN:0-521-41932-8 +// TODO: mark references as crossing optional boundaries, rather than +// approximating it during evaluation. + type CycleInfo struct { + // CycleType is used by the V3 cycle detection algorithm to track whether + // a cycle is detected and of which type. + CycleType CyclicType + // IsCyclic indicates whether this conjunct, or any of its ancestors, // had a violating cycle. + // TODO: make this a method and use CycleType == IsCyclic after V2 is removed. IsCyclic bool // Inline is used to detect expressions referencing themselves, for instance: @@ -259,6 +604,179 @@ type cyclicConjunct struct { arc *Vertex // cached Vertex } +// CycleType indicates the type of cycle detected. The CyclicType is associated +// with a conjunct and may only increase in value for child conjuncts. +type CyclicType uint8 + +const ( + NoCycle CyclicType = iota + + // like newStructure, but derived from a reference. If this is set, a cycle + // will move to maybeCyclic instead of isCyclic. + IsOptional + + // maybeCyclic is set if a cycle is detected within an optional field. + // + MaybeCyclic + + // IsCyclic marks that this conjunct has a structural cycle. + IsCyclic +) + +func (n *nodeContext) detectCycleV3(arc *Vertex, env *Environment, x Resolver, ci CloseInfo) (_ CloseInfo, skip bool) { + n.assertInitialized() + + // If we are pointing to a direct ancestor, and we are in an optional arc, + // we can immediately terminate, as a cycle error within an optional field + // is okay. If we are pointing to a direct ancestor in a non-optional arc, + // we also can terminate, as this is a structural cycle. + // TODO: use depth or check direct ancestry. + if n.hasAncestorV3(arc) { + return n.markCyclicV3(arc, env, x, ci) + } + + // As long as a node-wide cycle has not yet been detected, we allow cycles + // in optional fields to proceed unchecked. + if n.hasNonCyclic && ci.CycleType == MaybeCyclic { + return ci, false + } + + for r := ci.Refs; r != nil; r = r.Next { + if equalDeref(r.Arc, arc) { + if n.node.IsDynamic || ci.Inline { + n.reportCycleError() + return ci, true + } + + if equalDeref(r.Node, n.node) { + // reference cycle + return ci, true + } + + // If there are still any non-cyclic conjuncts, and if this conjunct + // is optional, we allow this to continue one more cycle. + if ci.CycleType == IsOptional && n.hasNonCyclic { + ci.CycleType = MaybeCyclic + // There my still be a cycle if the optional field is a pattern + // that unifies with itself, as in: + // + // [string]: c + // a: b + // b: _ + // c: a: int + // + // This is equivalent to a reference cycle. + if r.Depth == n.node.state.depth { + return ci, true + } + ci.Refs = nil + return ci, false + } + + return n.markCyclicPathV3(arc, env, x, ci) + } + } + + ci.Refs = &RefNode{ + Arc: deref(arc), + Ref: x, + Node: deref(n.node), + Next: ci.Refs, + Depth: n.depth, + } + + return ci, false +} + +// markCyclicV3 marks a conjunct as being cyclic. Also, it postpones processing +// the conjunct in the absence of evidence of a non-cyclic conjunct. +func (n *nodeContext) markCyclicV3(arc *Vertex, env *Environment, x Resolver, ci CloseInfo) (CloseInfo, bool) { + ci.CycleType = IsCyclic + ci.IsCyclic = true + + n.hasAnyCyclicConjunct = true + n.hasAncestorCycle = true + + if !n.hasNonCycle && env != nil { + // TODO: investigate if we can get rid of cyclicConjuncts in the new + // evaluator. + v := Conjunct{env, x, ci} + n.node.cc().incDependent(n.ctx, DEFER, nil) + n.cyclicConjuncts = append(n.cyclicConjuncts, cyclicConjunct{v, arc}) + return ci, true + } + return ci, false +} + +func (n *nodeContext) markCyclicPathV3(arc *Vertex, env *Environment, x Resolver, ci CloseInfo) (CloseInfo, bool) { + ci.CycleType = IsCyclic + ci.IsCyclic = true + + n.hasAnyCyclicConjunct = true + + if !n.hasNonCyclic && !n.hasNonCycle && env != nil { + // TODO: investigate if we can get rid of cyclicConjuncts in the new + // evaluator. + v := Conjunct{env, x, ci} + n.node.cc().incDependent(n.ctx, DEFER, nil) + n.cyclicConjuncts = append(n.cyclicConjuncts, cyclicConjunct{v, arc}) + return ci, true + } + return ci, false +} + +// hasDepthCycle uses depth counters to keep track of cycles: +// - it allows detecting reference cycles as well (state evaluating is +// no longer used in v3) +// - it can capture cycles across inline structs, which do not have +// Parent set. +// +// TODO: ensure that evalDepth is cleared when a node is finalized. +func (c *OpContext) hasDepthCycle(v *Vertex) bool { + if s := v.state; s != nil && v.status != finalized { + return s.evalDepth > 0 && s.evalDepth < c.evalDepth + } + return false +} + +// hasAncestorV3 checks whether a node is currently being processed. The code +// still assumes that is includes any node that is currently being processed. +func (n *nodeContext) hasAncestorV3(arc *Vertex) bool { + if n.ctx.hasDepthCycle(arc) { + return true + } + + // TODO: insert test conditions for Bloom filter that guarantee that all + // parent nodes have been marked as "hot", in which case we can avoid this + // traversal. + // if n.meets(allAncestorsProcessed) { + // return false + // } + + for p := n.node.Parent; p != nil; p = p.Parent { + // TODO(perf): deref arc only once. + if equalDeref(p, arc) { + return true + } + } + return false +} + +func (n *nodeContext) hasOnlyCyclicConjuncts() bool { + return (n.hasAncestorCycle && !n.hasNonCycle) || + (n.hasAnyCyclicConjunct && !n.hasNonCyclic) +} + +// setOptionalV3 marks a conjunct as being optional. The nodeContext is +// currently unused, but allows for checks to be added and to add logging during +// debugging. +func (c *CloseInfo) setOptionalV3(n *nodeContext) { + _ = n // See comment. + if c.CycleType == NoCycle { + c.CycleType = IsOptional + } +} + // markCycle checks whether the reference x is cyclic. There are two cases: // 1. it was previously used in this conjunct, and // 2. it directly references a parent node. @@ -280,6 +798,8 @@ type cyclicConjunct struct { // the conjunct seems to be fully cyclic so far or if there is a valid reference // cycle. func (n *nodeContext) markCycle(arc *Vertex, env *Environment, x Resolver, ci CloseInfo) (_ CloseInfo, skip bool) { + unreachableForDev(n.ctx) + n.assertInitialized() // TODO(perf): this optimization can work if we also check for any @@ -543,13 +1063,13 @@ outer: } } - n.hasCycle = true + n.hasAnyCyclicConjunct = true if !n.hasNonCycle && env != nil { // TODO: investigate if we can get rid of cyclicConjuncts in the new // evaluator. v := Conjunct{env, x, ci} if n.ctx.isDevVersion() { - n.node.cc.incDependent(n.ctx, DEFER, nil) + n.node.cc().incDependent(n.ctx, DEFER, nil) } n.cyclicConjuncts = append(n.cyclicConjuncts, cyclicConjunct{v, arc}) return ci, true @@ -575,35 +1095,51 @@ func getNonCyclicCount(c Conjunct) int { } } +// updateCyclicStatusV3 looks for proof of non-cyclic conjuncts to override +// a structural cycle. +func (n *nodeContext) updateCyclicStatusV3(c CloseInfo) { + if !c.IsCyclic { + n.hasNonCycle = true + for _, c := range n.cyclicConjuncts { + ci := c.c.CloseInfo + ci.cc = n.node.rootCloseContext(n.ctx) + n.scheduleVertexConjuncts(c.c, c.arc, ci) + n.node.cc().decDependent(n.ctx, DEFER, nil) + } + n.cyclicConjuncts = n.cyclicConjuncts[:0] + } +} + // updateCyclicStatus looks for proof of non-cyclic conjuncts to override // a structural cycle. func (n *nodeContext) updateCyclicStatus(c CloseInfo) { + unreachableForDev(n.ctx) + if !c.IsCyclic { n.hasNonCycle = true for _, c := range n.cyclicConjuncts { - if n.ctx.isDevVersion() { - ci := c.c.CloseInfo - ci.cc = n.node.rootCloseContext(n.ctx) - n.scheduleVertexConjuncts(c.c, c.arc, ci) - n.node.cc.decDependent(n.ctx, DEFER, nil) - } else { - n.addVertexConjuncts(c.c, c.arc, false) - } + n.addVertexConjuncts(c.c, c.arc, false) } n.cyclicConjuncts = n.cyclicConjuncts[:0] } } -func assertStructuralCycle(n *nodeContext) bool { +func assertStructuralCycleV3(n *nodeContext) bool { // TODO: is this the right place to put it? - if n.ctx.isDevVersion() { - for range n.cyclicConjuncts { - n.node.cc.decDependent(n.ctx, DEFER, nil) - } - n.cyclicConjuncts = n.cyclicConjuncts[:0] + for range n.cyclicConjuncts { + n.node.cc().decDependent(n.ctx, DEFER, nil) } + n.cyclicConjuncts = n.cyclicConjuncts[:0] - if n.hasCycle && !n.hasNonCycle { + if n.hasOnlyCyclicConjuncts() { + n.reportCycleError() + return true + } + return false +} + +func assertStructuralCycle(n *nodeContext) bool { + if n.hasAnyCyclicConjunct && !n.hasNonCycle { n.reportCycleError() return true } @@ -611,14 +1147,14 @@ func assertStructuralCycle(n *nodeContext) bool { } func (n *nodeContext) reportCycleError() { - n.node.BaseValue = CombineErrors(nil, - n.node.Value(), - &Bottom{ - Code: StructuralCycleError, - Err: n.ctx.Newf("structural cycle"), - Value: n.node.Value(), - // TODO: probably, this should have the referenced arc. - }) + b := &Bottom{ + Code: StructuralCycleError, + Err: n.ctx.Newf("structural cycle"), + Value: n.node.Value(), + Node: n.node, + // TODO: probably, this should have the referenced arc. + } + n.setBaseValue(CombineErrors(nil, n.node.Value(), b)) n.node.Arcs = nil } diff --git a/vendor/cuelang.org/go/internal/core/adt/debug.go b/vendor/cuelang.org/go/internal/core/adt/debug.go index 4d0728821b..9eeab5e7ae 100644 --- a/vendor/cuelang.org/go/internal/core/adt/debug.go +++ b/vendor/cuelang.org/go/internal/core/adt/debug.go @@ -68,7 +68,7 @@ func OpenNodeGraph(title, path, code, out, graph string) { } numberOpened++ - err := os.MkdirAll(path, 0755) + err := os.MkdirAll(path, 0777) if err != nil { log.Fatal(err) } @@ -140,158 +140,13 @@ func OpenNodeGraph(title, path, code, out, graph string) { // and all its dependencies that have not completed processing. // DO NOT DELETE: this is used to insert during debugging of the evaluator // to inspect a node. -func openDebugGraph(ctx *OpContext, v *Vertex, name string) { +func openDebugGraph(ctx *OpContext, cc *closeContext, name string) { + v := cc.src graph, _ := CreateMermaidGraph(ctx, v, true) - path := filepath.Join(".debug", "TestX", name) + path := filepath.Join(".debug", "TestX", name, fmt.Sprintf("%p", cc)) OpenNodeGraph(name, path, "in", "out", graph) } -// depKind is a type of dependency that is tracked with incDependent and -// decDependent. For each there should be matching pairs passed to these -// functions. The debugger, when used, tracks and verifies that these -// dependencies are balanced. -type depKind int - -const ( - // PARENT dependencies are used to track the completion of parent - // closedContexts within the closedness tree. - PARENT depKind = iota + 1 - - // ARC dependencies are used to track the completion of corresponding - // closedContexts in parent Vertices. - ARC - - // NOTIFY dependencies keep a note while dependent conjuncts are collected - NOTIFY // root node of source - - // TASK dependencies are used to track the completion of a task. - TASK - - // DISJUNCT is used to mark an incomplete disjunct. - DISJUNCT - - // EVAL tracks that the conjunct associated with a closeContext has been - // inserted using scheduleConjunct. A closeContext may not be deleted - // as long as the conjunct has not been evaluated yet. - // This prevents a node from being released if an ARC decrement happens - // before a node is evaluated. - EVAL - - // COMP tracks pending arcs in comprehensions. - COMP - - // ROOT dependencies are used to track that all nodes of parents are - // added to a tree. - ROOT // Always refers to self. - - // INIT dependencies are used to hold ownership of a closeContext during - // initialization and prevent it from being finalized when scheduling a - // node's conjuncts. - INIT - - // DEFER is used to track recursive processing of a node. - DEFER // Always refers to self. - - // TEST is used for testing notifications. - TEST // Always refers to self. -) - -func (k depKind) String() string { - switch k { - case PARENT: - return "PARENT" - case ARC: - return "ARC" - case NOTIFY: - return "NOTIFY" - case TASK: - return "TASK" - case DISJUNCT: - return "DISJUNCT" - case EVAL: - return "EVAL" - case COMP: - return "COMP" - case ROOT: - return "ROOT" - - case INIT: - return "INIT" - case DEFER: - return "DEFER" - case TEST: - return "TEST" - } - panic("unreachable") -} - -// ccDep is used to record counters which is used for debugging only. -// It is purpose is to be precise about matching inc/dec as well as to be able -// to traverse dependency. -type ccDep struct { - dependency *closeContext - kind depKind - decremented bool - - // task keeps a reference to a task for TASK dependencies. - task *task - // taskID indicates the sequence number of a task within a scheduler. - taskID int -} - -func (c *closeContext) addDependent(ctx *OpContext, kind depKind, dependant *closeContext) *ccDep { - if !DebugDeps { - return nil - } - - if dependant == nil { - dependant = c - } - - if ctx.LogEval > 1 { - ctx.Logf(ctx.vertex, "INC(%s) %v %p parent: %p %d\n", kind, c.Label(), c, c.parent, c.conjunctCount) - } - - dep := &ccDep{kind: kind, dependency: dependant} - c.dependencies = append(c.dependencies, dep) - - return dep -} - -// matchDecrement checks that this decrement matches a previous increment. -func (c *closeContext) matchDecrement(ctx *OpContext, v *Vertex, kind depKind, dependant *closeContext) { - if !DebugDeps { - return - } - - if dependant == nil { - dependant = c - } - - if ctx.LogEval > 1 { - ctx.Logf(ctx.vertex, "DEC(%s) %v %p %d\n", kind, c.Label(), c, c.conjunctCount) - } - - for _, d := range c.dependencies { - if d.kind != kind { - continue - } - if d.dependency != dependant { - continue - } - // Only one typ-dependant pair possible. - if d.decremented { - // There might be a duplicate entry, so continue searching. - continue - } - - d.decremented = true - return - } - - panic(fmt.Sprintf("unmatched decrement: %s", kind)) -} - // mermaidContext is used to create a dependency analysis for a node. type mermaidContext struct { ctx *OpContext @@ -352,6 +207,7 @@ func CreateMermaidGraph(ctx *OpContext, v *Vertex, all bool) (graph string, hasE io.WriteString(m.w, "graph TD\n") io.WriteString(m.w, " classDef err fill:#e01010,stroke:#000000,stroke-width:3,font-size:medium\n") + fmt.Fprintf(m.w, " title[%v]\n", ctx.disjunctInfo()) indent(m.w, 1) fmt.Fprintf(m.w, "style %s stroke-width:5\n\n", m.vertexID(v)) @@ -427,7 +283,7 @@ func (m *mermaidContext) vertex(v *Vertex) *mermaidVertex { var status string switch { - case v.status == finalized: + case v.Status() == finalized: status = "finalized" case v.state == nil: status = "ready" @@ -545,15 +401,7 @@ func (m *mermaidContext) cc(cc *closeContext) { case PARENT: w = node name = m.pstr(d.dependency) - case EVAL: - if cc.Label().IsLet() { - // Do not show eval links for let nodes, as they never depend - // on the parent node. Alternatively, link them to the root - // node instead. - return - } - fallthrough - case ARC, NOTIFY, DISJUNCT, COMP: + case EVAL, ARC, NOTIFY, DISJUNCT, COMP: w = global indentLevel = 1 name = m.pstr(d.dependency) @@ -565,7 +413,7 @@ func (m *mermaidContext) cc(cc *closeContext) { taskID = m.task(d) } name = fmt.Sprintf("%s((%d))", taskID, d.taskID) - case ROOT, INIT: + case ROOT, INIT, SHARED: w = node src := cc.src if v.f != src.Label { @@ -642,14 +490,21 @@ func (m *mermaidContext) pstr(cc *closeContext) string { flags.WriteByte(flag) } } - addFlag(cc.isDef, '#') + addFlag(cc.isDefOrig, '#') addFlag(cc.isEmbed, 'E') addFlag(cc.isClosed, 'c') addFlag(cc.isClosedOnce, 'C') - addFlag(cc.hasEllipsis, 'o') + addFlag(cc.isTotal, 'o') flags.WriteByte(cc.arcType.String()[0]) io.Copy(w, flags) + // Show the origin of the closeContext. + indentOnNewline(w, 3) + fmt.Fprintf(w, "+%d", cc.depth) + if cc.holeID != 0 { + fmt.Fprintf(w, " H%d", cc.holeID) + } + w.WriteString(close) switch { diff --git a/vendor/cuelang.org/go/internal/core/adt/dep.go b/vendor/cuelang.org/go/internal/core/adt/dep.go new file mode 100644 index 0000000000..67261d9294 --- /dev/null +++ b/vendor/cuelang.org/go/internal/core/adt/dep.go @@ -0,0 +1,371 @@ +// Copyright 2025 CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package adt + +import "fmt" + +// depKind is a type of dependency that is tracked with incDependent and +// decDependent. For each there should be matching pairs passed to these +// functions. The debugger, when used, tracks and verifies that these +// dependencies are balanced. +type depKind int + +//go:generate go run golang.org/x/tools/cmd/stringer -type=depKind + +const ( + // PARENT dependencies are used to track the completion of parent + // closedContexts within the closedness tree. + PARENT depKind = iota + 1 + + // ARC dependencies are used to track the completion of corresponding + // closedContexts in parent Vertices. + ARC + + // NOTIFY dependencies keep a note while dependent conjuncts are collected + NOTIFY // root node of source + + // TASK dependencies are used to track the completion of a task. + TASK + + // DISJUNCT is used to mark an incomplete disjunct. + DISJUNCT + + // EVAL tracks that the conjunct associated with a closeContext has been + // inserted using scheduleConjunct. A closeContext may not be deleted + // as long as the conjunct has not been evaluated yet. + // This prevents a node from being released if an ARC decrement happens + // before a node is evaluated. + EVAL + + // COMP tracks pending arcs in comprehensions. + COMP + + // ROOT dependencies are used to track that all nodes of parents are + // added to a tree. + ROOT // Always refers to self. + + // INIT dependencies are used to hold ownership of a closeContext during + // initialization and prevent it from being finalized when scheduling a + // node's conjuncts. + INIT + + // DEFER is used to track recursive processing of a node. + DEFER // Always refers to self. + + // SHARED is used to track shared nodes. The processing of shared nodes may + // change until all other conjuncts have been processed. + SHARED + + // TEST is used for testing notifications. + TEST // Always refers to self. +) + +// ccDep is used to record counters which is used for debugging only. +// It is purpose is to be precise about matching inc/dec as well as to be able +// to traverse dependency. +type ccDep struct { + dependency *closeContext + kind depKind + decremented bool + + // task keeps a reference to a task for TASK dependencies. + task *task + // taskID indicates the sequence number of a task within a scheduler. + taskID int +} + +func (c *closeContext) addDependent(ctx *OpContext, kind depKind, dependant *closeContext) *ccDep { + if dependant == nil { + dependant = c + } + + if ctx.LogEval > 1 { + ctx.Logf(ctx.vertex, "INC(%s) %v %p parent: %p %d\n", kind, c.Label(), c, c.parent, c.conjunctCount) + } + + dep := &ccDep{kind: kind, dependency: dependant} + c.dependencies = append(c.dependencies, dep) + + return dep +} + +// matchDecrement checks that this decrement matches a previous increment. +func (c *closeContext) matchDecrement(ctx *OpContext, v *Vertex, kind depKind, dependant *closeContext) { + if dependant == nil { + dependant = c + } + + if ctx.LogEval > 1 { + ctx.Logf(ctx.vertex, "DEC(%s) %v %p %d\n", kind, c.Label(), c, c.conjunctCount) + } + + for _, d := range c.dependencies { + if d.kind != kind { + continue + } + if d.dependency != dependant { + continue + } + // Only one typ-dependant pair possible. + if d.decremented { + // There might be a duplicate entry, so continue searching. + continue + } + + d.decremented = true + return + } + + if DebugDeps { + panic(fmt.Sprintf("unmatched decrement: %s", kind)) + } +} + +// A ccDepRef x refers to the x.src.[arcs|notify][x.index] +// +// We use this instead of pointers, because the address may change when +// growing a slice. We use this instead mechanism instead of a pointers so +// that we do not need to maintain separate free buffers once we use pools of +// closeContext. +type ccDepRef struct { + src *closeContext + kind depKind + index int +} + +// addArc adds a dependent arc to c. If child is an arc, child.src == key +func (c *closeContext) addArcDependency(ctx *OpContext, matched bool, child *closeContext) { + root := child.src.cc() + + // NOTE: do not increment + // - either root closeContext or otherwise resulting from sub closeContext + // all conjuncts will be added now, notified, or scheduled as task. + for _, a := range c.arcs { + if a.root == root { + panic("addArc: Label already exists") + } + } + child.incDependent(ctx, ARC, c) // matched in decDependent REF(arcs) + + c.arcs = append(c.arcs, ccArc{ + matched: matched, + root: root, + dst: child, + }) + + root.externalDeps = append(root.externalDeps, ccDepRef{ + src: c, + kind: ARC, + index: len(c.arcs) - 1, + }) +} + +func (c *closeContext) addNotifyDependency(ctx *OpContext, dst *closeContext) bool { + for _, a := range c.notify { + if a.dst == dst { + return false + } + } + dst.incDependent(ctx, NOTIFY, c) // matched in decDependent REF(arcs) + + c.notify = append(c.notify, ccNotify{dst: dst}) + + root := dst.src.cc() + root.externalDeps = append(root.externalDeps, ccDepRef{ + src: c, + kind: NOTIFY, + index: len(c.notify) - 1, + }) + return true +} + +// incDisjunct increases disjunction-related counters. We require kind to be +// passed explicitly so that we can easily find the points where certain kinds +// are used. +func (c *closeContext) incDisjunct(ctx *OpContext, kind depKind) { + if kind != DISJUNCT { + panic("unexpected kind") + } + c.incDependent(ctx, DISJUNCT, nil) + + // TODO: the counters are only used in debug mode and we could skip this + // if debug is disabled. + for ; c != nil; c = c.parent { + c.disjunctCount++ + } +} + +// decDisjunct decreases disjunction-related counters. We require kind to be +// passed explicitly so that we can easily find the points where certain kinds +// are used. +func (c *closeContext) decDisjunct(ctx *OpContext, kind depKind) { + if kind != DISJUNCT { + panic("unexpected kind") + } + c.decDependent(ctx, DISJUNCT, nil) + + // TODO: the counters are only used in debug mode and we could skip this + // if debug is disabled. + for ; c != nil; c = c.parent { + c.disjunctCount-- + } +} + +// incDependent needs to be called for any conjunct or child closeContext +// scheduled for c that is queued for later processing and not scheduled +// immediately. +func (c *closeContext) incDependent(ctx *OpContext, kind depKind, dependant *closeContext) (debug *ccDep) { + if c.src == nil { + panic("incDependent: unexpected nil src") + } + if dependant != nil && c.generation != dependant.generation { + // TODO: enable this check. + + // panic(fmt.Sprintf("incDependent: inconsistent generation: %d %d", c.generation, dependant.generation)) + } + debug = c.addDependent(ctx, kind, dependant) + + if c.done { + openDebugGraph(ctx, c, "incDependent: already checked") + + panic(fmt.Sprintf("incDependent: already closed: %p", c)) + } + + c.conjunctCount++ + return debug +} + +// decDependent needs to be called for any conjunct or child closeContext for +// which a corresponding incDependent was called after it has been successfully +// processed. +func (c *closeContext) decDependent(ctx *OpContext, kind depKind, dependant *closeContext) { + v := c.src + + c.matchDecrement(ctx, v, kind, dependant) + c.decDependentNoMatch(ctx, kind, dependant) +} + +// decDependentNoMatch is like decDependent, but does not check for a matching +// increment. This is useful when a decrement is triggered during creating +// a disjunct overlay, as it obviates the need to create the matching debug +// dependency. +func (c *closeContext) decDependentNoMatch(ctx *OpContext, kind depKind, dependant *closeContext) { + if c.conjunctCount == 0 { + panic(fmt.Sprintf("negative reference counter %d %p", c.conjunctCount, c)) + } + + c.conjunctCount-- + if c.conjunctCount > 0 { + return + } + + c.done = true + + for i, a := range c.arcs { + cc := a.dst + if a.decremented { + continue + } + c.arcs[i].decremented = true + cc.decDependent(ctx, ARC, c) + } + + for i, a := range c.notify { + cc := a.dst + if a.decremented { + continue + } + c.notify[i].decremented = true + cc.decDependent(ctx, NOTIFY, c) + } + + if !c.updateClosedInfo(ctx) { + return + } + + p := c.parent + + p.decDependent(ctx, PARENT, c) // REF(decrement: spawn) + + // If we have started decrementing a child closeContext, the parent started + // as well. If it is still marked as needing an EVAL decrement, which can + // happen if processing started before the node was added, it is safe to + // decrement it now. In this case the NOTIFY and ARC dependencies will keep + // the nodes alive until they can be completed. + if dep := p.needsCloseInSchedule; dep != nil { + p.needsCloseInSchedule = nil + p.decDependent(ctx, EVAL, dep) + } +} + +// breakIncomingNotifications walks over incoming arcs and forces any remaining +// work to be done. +func (n *nodeContext) breakIncomingNotifications(mode runMode) { + v := n.node + // TODO: replace with something more principled that does not piggyback on + // debug information. + for _, r := range v.cc().externalDeps { + if r.kind != NOTIFY { + continue + } + src := r.src + a := &src.notify[r.index] + if a.decremented { + continue + } + if n := src.src.getState(n.ctx); n != nil { + n.completeNodeTasks(mode) + } + } +} + +// breakIncomingDeps breaks all incoming dependencies, which includes arcs and +// pending notifications and attempts all remaining work. +// +// We should only break incoming dependencies if we are finalizing nodes, as +// breaking them earlier can cause a "already closed" panic. To make sure of +// this, we force the caller to pass mode. +func (n *nodeContext) breakIncomingDeps(mode runMode) { + if mode != finalize { + return + } + + // TODO: remove this block in favor of finalizing notification nodes, + // or what have you. We have patched this to skip evaluating when using + // disjunctions, but this is overall a brittle approach. + for _, r := range n.node.cc().externalDeps { + src := r.src + switch r.kind { + case ARC: + a := &src.arcs[r.index] + if a.decremented { + continue + } + a.decremented = true + + src.src.unify(n.ctx, needTasksDone, attemptOnly) + a.dst.decDependent(n.ctx, ARC, src) + case NOTIFY: + a := &src.notify[r.index] + if a.decremented { + continue + } + a.decremented = true + + src.src.unify(n.ctx, needTasksDone, attemptOnly) + a.dst.decDependent(n.ctx, NOTIFY, src) + } + } +} diff --git a/vendor/cuelang.org/go/internal/core/adt/depkind_string.go b/vendor/cuelang.org/go/internal/core/adt/depkind_string.go new file mode 100644 index 0000000000..0308eb57c9 --- /dev/null +++ b/vendor/cuelang.org/go/internal/core/adt/depkind_string.go @@ -0,0 +1,35 @@ +// Code generated by "stringer -type=depKind"; DO NOT EDIT. + +package adt + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[PARENT-1] + _ = x[ARC-2] + _ = x[NOTIFY-3] + _ = x[TASK-4] + _ = x[DISJUNCT-5] + _ = x[EVAL-6] + _ = x[COMP-7] + _ = x[ROOT-8] + _ = x[INIT-9] + _ = x[DEFER-10] + _ = x[SHARED-11] + _ = x[TEST-12] +} + +const _depKind_name = "PARENTARCNOTIFYTASKDISJUNCTEVALCOMPROOTINITDEFERSHAREDTEST" + +var _depKind_index = [...]uint8{0, 6, 9, 15, 19, 27, 31, 35, 39, 43, 48, 54, 58} + +func (i depKind) String() string { + i -= 1 + if i < 0 || i >= depKind(len(_depKind_index)-1) { + return "depKind(" + strconv.FormatInt(int64(i+1), 10) + ")" + } + return _depKind_name[_depKind_index[i]:_depKind_index[i+1]] +} diff --git a/vendor/cuelang.org/go/internal/core/adt/disjunct.go b/vendor/cuelang.org/go/internal/core/adt/disjunct.go index 675fab7225..4da35fa6a2 100644 --- a/vendor/cuelang.org/go/internal/core/adt/disjunct.go +++ b/vendor/cuelang.org/go/internal/core/adt/disjunct.go @@ -15,6 +15,8 @@ package adt import ( + "slices" + "cuelang.org/go/cue/errors" "cuelang.org/go/cue/token" ) @@ -85,6 +87,7 @@ import ( type envDisjunct struct { env *Environment cloneID CloseInfo + holeID int // fields for new evaluator @@ -208,7 +211,7 @@ func (n *nodeContext) expandDisjuncts( n.disjuncts = append(n.disjuncts, n) } if n.node.BaseValue == nil { - n.node.BaseValue = n.getValidators(state) + n.setBaseValue(n.getValidators(state)) } n.usedDefault = append(n.usedDefault, defaultInfo{ @@ -467,6 +470,7 @@ func (n *nodeContext) makeError() { b := &Bottom{ Code: code, Err: n.disjunctError(), + Node: n.node, } n.node.SetValue(n.ctx, b) } @@ -502,12 +506,10 @@ func clone(v Vertex) Vertex { case finalized: v.Arcs[i] = arc - case 0: + case unprocessed: a := *arc v.Arcs[i] = &a - - a.Conjuncts = make([]Conjunct, len(arc.Conjuncts)) - copy(a.Conjuncts, arc.Conjuncts) + a.Conjuncts = slices.Clone(arc.Conjuncts) default: a := *arc @@ -520,8 +522,7 @@ func clone(v Vertex) Vertex { } if a := v.Structs; len(a) > 0 { - v.Structs = make([]*StructInfo, len(a)) - copy(v.Structs, a) + v.Structs = slices.Clone(a) } return v diff --git a/vendor/cuelang.org/go/internal/core/adt/disjunct2.go b/vendor/cuelang.org/go/internal/core/adt/disjunct2.go index 503da32a85..955dc83613 100644 --- a/vendor/cuelang.org/go/internal/core/adt/disjunct2.go +++ b/vendor/cuelang.org/go/internal/core/adt/disjunct2.go @@ -129,7 +129,7 @@ package adt // // ## Evaluating equality of partially evaluated nodes // -// Because unevaluated expressions may depend on results that have yet been +// Because unevaluated expressions may depend on results that have yet to be // computed, we cannot reliably compare the results of a Vertex to determine // equality. We need a different strategy. // @@ -209,6 +209,7 @@ type disjunct struct { // is relatively rare, we keep it separate to avoid bloating the closeContext. type disjunctHole struct { cc *closeContext + holeID int underlying *closeContext } @@ -228,23 +229,37 @@ func (n *nodeContext) scheduleDisjunction(d envDisjunct) { // case mergeVertex will override the original value, or multiple disjuncts, // in which case the original is set to the disjunct itself. ccHole.incDisjunct(n.ctx, DISJUNCT) + ccHole.holeID = d.holeID n.disjunctions = append(n.disjunctions, d) n.disjunctCCs = append(n.disjunctCCs, disjunctHole{ cc: ccHole, // this value is cloned in doDisjunct. + holeID: d.holeID, underlying: ccHole, }) } -func initArcs(ctx *OpContext, v *Vertex) { +func initArcs(ctx *OpContext, v *Vertex) bool { + ok := true for _, a := range v.Arcs { - a.getState(ctx) - initArcs(ctx, a) + s := a.getState(ctx) + if s != nil && s.errs != nil { + ok = false + if a.ArcType == ArcMember { + break + } + } else if !initArcs(ctx, a) { + ok = false + } } + return ok } func (n *nodeContext) processDisjunctions() *Bottom { + ID := n.pushDisjunctionTask() + defer ID.pop() + defer func() { // TODO: // Clear the buffers. @@ -257,7 +272,57 @@ func (n *nodeContext) processDisjunctions() *Bottom { a := n.disjunctions n.disjunctions = n.disjunctions[:0] - initArcs(n.ctx, n.node) + holes := make([]disjunctHole, len(n.disjunctCCs)) + copy(holes, n.disjunctCCs) + + // Upon completion, decrement the DISJUNCT counters that were incremented + // in scheduleDisjunction. Note that this disjunction may be a copy of the + // original, in which case we need to decrement the copied disjunctCCs, not + // the original. + // + // This is not strictly necessary, but it helps for balancing counters. + // TODO: Consider disabling this when DebugDeps is not set. + defer func() { + // We add a "top" value to disable closedness checking for this + // disjunction to avoid a spurious "field not allowed" error. + // We return the errors below, which will, in turn, be reported as + // the error. + for i, d := range a { + // TODO(perf: prove that holeIDs are always stored in increasing + // order and allow for an incremental search to reduce cost. + for _, h := range holes { + if h.holeID != a[i].holeID { + continue + } + cc := h.cc + id := a[i].cloneID + id.cc = cc + c := MakeConjunct(d.env, top, id) + n.scheduleConjunct(c, d.cloneID) + cc.decDisjunct(n.ctx, DISJUNCT) + break + } + } + }() + + if !initArcs(n.ctx, n.node) { + return n.getError() + } + + // If the disjunct of an enclosing disjunction operation has an attemptOnly + // runMode, this disjunct should have this also and may not finalize. + // Finalization may cause incoming dependencies to be broken. If an outer + // disjunction still has open holes, this means that more conjuncts may be + // incoming and that finalization would prematurely prevent those from being + // added. In practice, this may result in the infamous "already closed" + // panic. + var outerRunMode runMode + for p := n.node; p != nil; p = p.Parent { + if p.IsDisjunct { + outerRunMode = p.state.runMode + break + } + } // TODO(perf): single pass for quick filter on all disjunctions. // n.node.unify(n.ctx, allKnown, attemptOnly) @@ -271,28 +336,29 @@ func (n *nodeContext) processDisjunctions() *Bottom { // evaluation adds more disjunctions. for i := 0; i < len(a); i++ { d := &a[i] + n.nextDisjunction(i, len(a), d.holeID) + // We need to only finalize the last series of disjunctions. However, + // disjunctions can be nested. mode := attemptOnly - if i == len(a)-1 { + switch { + case outerRunMode != 0: + mode = outerRunMode + if i < len(a)-1 { + mode = attemptOnly + } + case i == len(a)-1: mode = finalize } - results = n.crossProduct(results, cross, d, mode) + + // Mark no final in nodeContext and observe later. + results = n.crossProduct(results, cross, d, mode, d.holeID) // TODO: do we unwind only at the end or also intermittently? switch len(results) { case 0: // TODO: now we have disjunct counters, do we plug holes at all? - // We add a "top" value to disable closedness checking for this - // disjunction to avoid a spurious "field not allowed" error. - // We return the errors below, which will, in turn, be reported as - // the error. - // TODO: probably no longer needed: - for i++; i < len(a); i++ { - c := MakeConjunct(d.env, top, a[i].cloneID) - n.scheduleConjunct(c, d.cloneID) - } - // Empty intermediate result. Further processing will not result in // any new result, so we can terminate here. // TODO(errors): investigate remaining disjunctions for errors. @@ -317,7 +383,7 @@ func (n *nodeContext) processDisjunctions() *Bottom { case 1: d := cross[0].node - n.node.BaseValue = d + n.setBaseValue(d) n.defaultMode = cross[0].defaultMode default: @@ -326,23 +392,42 @@ func (n *nodeContext) processDisjunctions() *Bottom { n.disjuncts = append(n.disjuncts, cross...) } + var completed condition + numDefaults := 0 + if len(n.disjuncts) == 1 { + completed = n.disjuncts[0].completed + } + for _, d := range n.disjuncts { + if d.defaultMode == isDefault { + numDefaults++ + completed = d.completed + } + } + if numDefaults == 1 || len(n.disjuncts) == 1 { + n.signal(completed) + } + return nil } // crossProduct computes the cross product of the disjuncts of a disjunction // with an existing set of results. -func (n *nodeContext) crossProduct(dst, cross []*nodeContext, dn *envDisjunct, mode runMode) []*nodeContext { +func (n *nodeContext) crossProduct(dst, cross []*nodeContext, dn *envDisjunct, mode runMode, hole int) []*nodeContext { defer n.unmarkDepth(n.markDepth()) defer n.unmarkOptional(n.markOptional()) - for _, p := range cross { + for i, p := range cross { + ID := n.nextCrossProduct(i, len(cross), p) + // TODO: use a partial unify instead // p.completeNodeConjuncts() initArcs(n.ctx, p.node) for j, d := range dn.disjuncts { + ID.node.nextDisjunct(j, len(dn.disjuncts), d.expr) + c := MakeConjunct(dn.env, d.expr, dn.cloneID) - r, err := p.doDisjunct(c, d.mode, mode) + r, err := p.doDisjunct(c, d.mode, mode, hole) if err != nil { // TODO: store more error context @@ -371,19 +456,31 @@ func (n *nodeContext) crossProduct(dst, cross []*nodeContext, dn *envDisjunct, m // collectErrors collects errors from a failed disjunctions. func (n *nodeContext) collectErrors(dn *envDisjunct) (errs *Bottom) { + code := EvalError for _, d := range dn.disjuncts { - if d.err != nil { - errs = CombineErrors(dn.src.Source(), errs, d.err) + if b := d.err; b != nil { + n.disjunctErrs = append(n.disjunctErrs, b) + if b.Code > code { + code = b.Code + } } } - return errs + + b := &Bottom{ + Code: code, + Err: n.disjunctError(), + Node: n.node, + } + return b } -func (n *nodeContext) doDisjunct(c Conjunct, m defaultMode, mode runMode) (*nodeContext, *Bottom) { +func (n *nodeContext) doDisjunct(c Conjunct, m defaultMode, mode runMode, hole int) (*nodeContext, *Bottom) { if c.CloseInfo.cc == nil { panic("nil closeContext during init") } - n.ctx.stats.Disjuncts++ + + ID := n.logDoDisjunct() + _ = ID // Do not remove, used for debugging. oc := newOverlayContext(n.ctx) @@ -393,6 +490,14 @@ func (n *nodeContext) doDisjunct(c Conjunct, m defaultMode, mode runMode) (*node // and then swapping it with disjunctCCs in the new nodeContext. holes := make([]disjunctHole, 0, len(n.disjunctCCs)) + // Complete as much of the pending work of this node and its parent before + // copying. Note that once a copy is made, the disjunct is no longer able + // to receive conjuncts from the original. + n.completeNodeTasks(mode) + // TODO: we may need to process incoming notifications for all arcs in + // the copied disjunct, but only those notifications not coming from + // within the arc itself. + // Clone the closeContexts of all open disjunctions and dependencies. for _, d := range n.disjunctCCs { // TODO: remove filled holes. @@ -401,10 +506,13 @@ func (n *nodeContext) doDisjunct(c Conjunct, m defaultMode, mode runMode) (*node // a closeContext corresponding to a disjunction always has a parent. // We therefore do not need to check whether x.parent is nil. o := oc.allocCC(d.cc) - if c.CloseInfo.cc == d.underlying { + if hole == d.holeID { ccHole = o + if d.cc.conjunctCount == 0 { + panic("unexpected zero conjunctCount") + } } - holes = append(holes, disjunctHole{o, d.underlying}) + holes = append(holes, disjunctHole{o, d.holeID, d.underlying}) } if ccHole == nil { @@ -414,14 +522,13 @@ func (n *nodeContext) doDisjunct(c Conjunct, m defaultMode, mode runMode) (*node n.scheduler.blocking = n.scheduler.blocking[:0] d := oc.cloneRoot(n) + d.runMode = mode d.defaultMode = combineDefault(m, n.defaultMode) v := d.node - saved := n.node.BaseValue - n.node.BaseValue = v - defer func() { n.node.BaseValue = saved }() + defer n.setBaseValue(n.swapBaseValue(v)) // Clear relevant scheduler states. // TODO: do something more principled: just ensure that a node that has @@ -440,11 +547,13 @@ func (n *nodeContext) doDisjunct(c Conjunct, m defaultMode, mode runMode) (*node v.unify(n.ctx, allKnown, mode) - if err := d.getError(); err != nil && !isCyclePlaceholder(err) { + if err := d.getErrorAll(); err != nil && !isCyclePlaceholder(err) { d.free() return nil, err } + d = d.node.DerefDisjunct().state + return d, nil } @@ -487,7 +596,7 @@ func (n *nodeContext) finalizeDisjunctions() { } v := n.node - v.BaseValue = d + n.setBaseValue(d) // The conjuncts will have too much information. Better have no // information than incorrect information. @@ -495,6 +604,25 @@ func (n *nodeContext) finalizeDisjunctions() { v.ChildErrors = nil } +func (n *nodeContext) getErrorAll() *Bottom { + err := n.getError() + if err != nil { + return err + } + for _, a := range n.node.Arcs { + if a.ArcType > ArcRequired || a.Label.IsLet() { + return nil + } + n := a.getState(n.ctx) + if n != nil { + if err := n.getErrorAll(); err != nil { + return err + } + } + } + return nil +} + func (n *nodeContext) getError() *Bottom { if b := n.node.Bottom(); b != nil && !isCyclePlaceholder(b) { return b @@ -537,16 +665,26 @@ outer: // it, trading correctness for performance. // If enabled, we would simply "continue" here. - for i, h := range xn.disjunctCCs { // TODO(perf): only iterate over completed - x, y := findIntersections(h.cc, x.disjunctCCs[i].cc) - if !equalPartialNode(xn.ctx, x, y) { - continue outer + for i, h := range xn.disjunctCCs { + // TODO(perf): only iterate over completed + // TODO(evalv3): we now have a double loop to match the + // disjunction holes. It should be possible to keep them + // aligned and avoid the inner loop. + for _, g := range x.disjunctCCs { + if h.underlying == g.underlying { + x, y := findIntersections(h.cc, x.disjunctCCs[i].cc) + if !equalPartialNode(xn.ctx, x, y) { + continue outer + } + } } } - if len(xn.tasks) != len(x.tasks) { - continue + if len(xn.tasks) != xn.taskPos || len(x.tasks) != x.taskPos { + if len(xn.tasks) != len(x.tasks) { + continue + } } - for i, t := range xn.tasks { + for i, t := range xn.tasks[xn.taskPos:] { s := x.tasks[i] if s.x != t.x || s.id.cc != t.id.cc { continue outer @@ -573,24 +711,15 @@ outer: if x.defaultMode == isDefault { xn.defaultMode = isDefault } - x.free() + // TODO: x.free() return a } return append(a, x) } -// isPartialNode reports whether a node must be evaluated as a partial node. -func isPartialNode(d *nodeContext) bool { - if d.node.status == finalized { - return true - } - // TODO: further optimizations - return false -} - // findIntersections reports the closeContext, relative to the two given -// disjunction holds, that should be used in comparing the arc set. +// disjunction holes, that should be used in comparing the arc set. // x and y MUST both be originating from the same disjunct hole. This ensures // that the depth of the parent chain is the same and that they have the // same underlying closeContext. @@ -657,17 +786,11 @@ func equalPartialNode(ctx *OpContext, x, y *closeContext) bool { // TODO(perf): use merge sort outer: for _, a := range x.arcs { - if a.kind != ARC { - continue outer - } for _, b := range y.arcs { - if b.kind != ARC { - continue - } - if a.key.src.Label != b.key.src.Label { + if a.root.src.Label != b.root.src.Label { continue } - if !equalPartialNode(ctx, a.cc, b.cc) { + if !equalPartialNode(ctx, a.dst, b.dst) { return false } continue outer @@ -706,7 +829,7 @@ func isEqualNodeValue(x, y *nodeContext) bool { if x.hasTop != y.hasTop { return false } - if !isEqualBaseValue(x.ctx, x.scalar, y.scalar) { + if !isEqualValue(x.ctx, x.scalar, y.scalar) { return false } @@ -714,26 +837,28 @@ func isEqualNodeValue(x, y *nodeContext) bool { if len(x.checks) != len(y.checks) { return false } - if len(x.tasks) != len(y.tasks) { - return false + if len(x.tasks) != x.taskPos || len(y.tasks) != y.taskPos { + if len(x.tasks) != len(y.tasks) { + return false + } } - if !isEqualBaseValue(x.ctx, x.lowerBound, y.lowerBound) { + if !isEqualValue(x.ctx, x.lowerBound, y.lowerBound) { return false } - if !isEqualBaseValue(x.ctx, x.upperBound, y.upperBound) { + if !isEqualValue(x.ctx, x.upperBound, y.upperBound) { return false } // Assume that checks are added in the same order. for i, c := range x.checks { d := y.checks[i] - if !Equal(x.ctx, c, d, CheckStructural) { + if !Equal(x.ctx, c.x.(Value), d.x.(Value), CheckStructural) { return false } } - for i, t := range x.tasks { + for i, t := range x.tasks[x.taskPos:] { s := y.tasks[i] if s.x != t.x { return false @@ -749,15 +874,20 @@ func isEqualNodeValue(x, y *nodeContext) bool { return true } -func isEqualBaseValue(ctx *OpContext, x, y BaseValue) bool { +type ComparableValue interface { + comparable + Value +} + +func isEqualValue[P ComparableValue](ctx *OpContext, x, y P) bool { + var zero P + if x == y { return true } - xv, _ := x.(Value) - yv, _ := y.(Value) - if xv == nil || yv == nil { + if x == zero || y == zero { return false } - return Equal(ctx, xv, yv, CheckStructural) + return Equal(ctx, x, y, CheckStructural) } diff --git a/vendor/cuelang.org/go/internal/core/adt/doc.go b/vendor/cuelang.org/go/internal/core/adt/doc.go index 84a0a14b9f..36504a1681 100644 --- a/vendor/cuelang.org/go/internal/core/adt/doc.go +++ b/vendor/cuelang.org/go/internal/core/adt/doc.go @@ -20,7 +20,7 @@ // // # Abstract Types // -// The following types describe the a place where a value may be used: +// The following types describe the place where a value may be used: // // Decl a value than can be used as a StructLit element. // Elem a value than can be used as a ListLit element. diff --git a/vendor/cuelang.org/go/internal/core/adt/equality.go b/vendor/cuelang.org/go/internal/core/adt/equality.go index cf2ff2ddeb..e808f17989 100644 --- a/vendor/cuelang.org/go/internal/core/adt/equality.go +++ b/vendor/cuelang.org/go/internal/core/adt/equality.go @@ -24,7 +24,11 @@ const ( // CheckStructural indicates that closedness information should be // considered for equality. Equal may return false even when values are // equal. - CheckStructural Flag = 1 << iota + CheckStructural + + // RegularOnly indicates that only regular fields should be considered, + // thus excluding hidden and definition fields. + RegularOnly ) func Equal(ctx *OpContext, v, w Value, flags Flag) bool { @@ -87,9 +91,11 @@ func equalVertex(ctx *OpContext, x *Vertex, v Value, flags Flag) bool { } } + skipRegular := flags&RegularOnly != 0 + loop1: for _, a := range x.Arcs { - if a.ArcType > maxArcType { + if (skipRegular && !a.Label.IsRegular()) || a.ArcType > maxArcType { continue } for _, b := range y.Arcs { @@ -105,7 +111,7 @@ loop1: loop2: for _, b := range y.Arcs { - if b.ArcType > maxArcType { + if (skipRegular && !b.Label.IsRegular()) || b.ArcType > maxArcType { continue } for _, a := range x.Arcs { diff --git a/vendor/cuelang.org/go/internal/core/adt/errorcode_string.go b/vendor/cuelang.org/go/internal/core/adt/errorcode_string.go new file mode 100644 index 0000000000..bb1e0da5d9 --- /dev/null +++ b/vendor/cuelang.org/go/internal/core/adt/errorcode_string.go @@ -0,0 +1,27 @@ +// Code generated by "stringer -type=ErrorCode -linecomment"; DO NOT EDIT. + +package adt + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[EvalError-0] + _ = x[UserError-1] + _ = x[StructuralCycleError-2] + _ = x[IncompleteError-3] + _ = x[CycleError-4] +} + +const _ErrorCode_name = "evaluserstructural cycleincompletecycle" + +var _ErrorCode_index = [...]uint8{0, 4, 8, 24, 34, 39} + +func (i ErrorCode) String() string { + if i < 0 || i >= ErrorCode(len(_ErrorCode_index)-1) { + return "ErrorCode(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _ErrorCode_name[_ErrorCode_index[i]:_ErrorCode_index[i+1]] +} diff --git a/vendor/cuelang.org/go/internal/core/adt/errors.go b/vendor/cuelang.org/go/internal/core/adt/errors.go index 581779fc42..40f5bdccfc 100644 --- a/vendor/cuelang.org/go/internal/core/adt/errors.go +++ b/vendor/cuelang.org/go/internal/core/adt/errors.go @@ -42,45 +42,31 @@ import ( // control flow. No other aspects of an error may influence control flow. type ErrorCode int8 +//go:generate go run golang.org/x/tools/cmd/stringer -type=ErrorCode -linecomment + const ( // An EvalError is a fatal evaluation error. - EvalError ErrorCode = iota + EvalError ErrorCode = iota // eval // A UserError is a fatal error originating from the user. - UserError + UserError // user // StructuralCycleError means a structural cycle was found. Structural // cycles are permanent errors, but they are not passed up recursively, // as a unification of a value with a structural cycle with one that // doesn't may still give a useful result. - StructuralCycleError + StructuralCycleError // structural cycle // IncompleteError means an evaluation could not complete because of // insufficient information that may still be added later. - IncompleteError + IncompleteError // incomplete // A CycleError indicates a reference error. It is considered to be // an incomplete error, as reference errors may be broken by providing // a concrete value. - CycleError + CycleError // cycle ) -func (c ErrorCode) String() string { - switch c { - case EvalError: - return "eval" - case UserError: - return "user" - case StructuralCycleError: - return "structural cycle" - case IncompleteError: - return "incomplete" - case CycleError: - return "cycle" - } - return "unknown" -} - // Bottom represents an error or bottom symbol. // // Although a Bottom node holds control data, it should not be created until the @@ -100,6 +86,11 @@ type Bottom struct { ForCycle bool // this is a for cycle // Value holds the computed value so far in case Value Value + + // Node marks the node at which an error occurred. This is used to + // determine the package to which an error belongs. + // TODO: use a more precise mechanism for tracking the package. + Node *Vertex } func (x *Bottom) Source() ast.Node { return x.Src } @@ -145,7 +136,8 @@ func isIncomplete(v *Vertex) bool { // // If x is not already an error, the value is recorded in the error for // reference. -func (v *Vertex) AddChildError(recursive *Bottom) { +func (n *nodeContext) AddChildError(recursive *Bottom) { + v := n.node v.ChildErrors = CombineErrors(nil, v.ChildErrors, recursive) if recursive.IsIncomplete() { return @@ -153,13 +145,14 @@ func (v *Vertex) AddChildError(recursive *Bottom) { x := v.BaseValue err, _ := x.(*Bottom) if err == nil { - v.BaseValue = &Bottom{ + n.setBaseValue(&Bottom{ Code: recursive.Code, Value: v, HasRecursive: true, ChildError: true, Err: recursive.Err, - } + Node: n.node, + }) return } @@ -168,7 +161,7 @@ func (v *Vertex) AddChildError(recursive *Bottom) { err.Code = recursive.Code } - v.BaseValue = err + n.setBaseValue(err) } // CombineErrors combines two errors that originate at the same Vertex. @@ -176,17 +169,22 @@ func CombineErrors(src ast.Node, x, y Value) *Bottom { a, _ := Unwrap(x).(*Bottom) b, _ := Unwrap(y).(*Bottom) - if a == b && isCyclePlaceholder(a) { - return a - } switch { - case a != nil && b != nil: - case a != nil: - return a - case b != nil: - return b - default: + case a == nil && b == nil: return nil + case a == nil: + return b + case b == nil: + return a + case a == b && isCyclePlaceholder(a): + return a + case a == b: + // Don't return a (or b) because they may have other non-nil fields. + return &Bottom{ + Src: src, + Err: a.Err, + Code: a.Code, + } } if a.Code != b.Code { @@ -225,18 +223,20 @@ func addPositions(err *ValueError, c Conjunct) { func NewRequiredNotPresentError(ctx *OpContext, v *Vertex) *Bottom { saved := ctx.PushArc(v) err := ctx.Newf("field is required but not present") - for _, c := range v.Conjuncts { + v.VisitLeafConjuncts(func(c Conjunct) bool { if f, ok := c.x.(*Field); ok && f.ArcType == ArcRequired { err.AddPosition(c.x) } if c.CloseInfo.closeInfo != nil { err.AddPosition(c.CloseInfo.location) } - } + return true + }) b := &Bottom{ Code: IncompleteError, Err: err, + Node: v, } ctx.PopArc(saved) return b @@ -245,9 +245,10 @@ func NewRequiredNotPresentError(ctx *OpContext, v *Vertex) *Bottom { func newRequiredFieldInComprehensionError(ctx *OpContext, x *ForClause, v *Vertex) *Bottom { err := ctx.Newf("missing required field in for comprehension: %v", v.Label) err.AddPosition(x.Src) - for _, c := range v.Conjuncts { + v.VisitLeafConjuncts(func(c Conjunct) bool { addPositions(err, c) - } + return true + }) return &Bottom{ Code: IncompleteError, Err: err, @@ -283,6 +284,7 @@ func (v *Vertex) reportFieldError(c *OpContext, pos token.Pos, f Feature, intMsg b := &Bottom{ Code: code, Err: err, + Node: v, } // TODO: yield failure c.AddBottom(b) // TODO: unify error mechanism. @@ -349,17 +351,10 @@ func appendNodePositions(a []token.Pos, n Node) []token.Pos { a = append(a, p) } if v, ok := n.(*Vertex); ok { - for _, c := range v.Conjuncts { - switch x := c.x.(type) { - case *ConjunctGroup: - for _, c := range *x { - a = appendNodePositions(a, c.Elem()) - } - - default: - a = appendNodePositions(a, c.Elem()) - } - } + v.VisitLeafConjuncts(func(c Conjunct) bool { + a = appendNodePositions(a, c.Elem()) + return true + }) } return a } diff --git a/vendor/cuelang.org/go/internal/core/adt/eval.go b/vendor/cuelang.org/go/internal/core/adt/eval.go index f26dd24ebb..a0f21332c5 100644 --- a/vendor/cuelang.org/go/internal/core/adt/eval.go +++ b/vendor/cuelang.org/go/internal/core/adt/eval.go @@ -54,8 +54,6 @@ func (c *OpContext) Stats() *stats.Counts { // return e.NewContext(v) // } -var structSentinel = &StructMarker{} - var incompleteSentinel = &Bottom{ Code: IncompleteError, Err: errors.Newf(token.NoPos, "incomplete"), @@ -83,7 +81,11 @@ func (c *OpContext) evaluate(v *Vertex, r Resolver, state combinedFlags) Value { for ; v.Parent != nil && v.ArcType == ArcPending; v = v.Parent { } err := c.Newf("cycle with field %v", r) - b := &Bottom{Code: CycleError, Err: err} + b := &Bottom{ + Code: CycleError, + Err: err, + Node: v, + } v.setValue(c, v.status, b) return b // TODO: use this instead, as is usual for incomplete errors, @@ -194,17 +196,17 @@ func (c *OpContext) unify(v *Vertex, flags combinedFlags) { return case evaluatingArcs: - Assertf(c, v.status > 0, "unexpected status %d", v.status) + Assertf(c, v.status > unprocessed, "unexpected status %d", v.status) return case 0: if v.Label.IsDef() { - v.Closed = true + v.ClosedRecursive = true } if v.Parent != nil { - if v.Parent.Closed { - v.Closed = true + if v.Parent.ClosedRecursive { + v.ClosedRecursive = true } } @@ -601,7 +603,7 @@ func (n *nodeContext) postDisjunct(state vertexStatus) { // // Before it does this, it also checks whether n is of another incompatible // type, like struct. This prevents validators from being inadvertently set. -// TODO: optimize this function for new implementation. +// TODO(evalv3): optimize this function for new implementation. func (n *nodeContext) validateValue(state vertexStatus) { ctx := n.ctx @@ -612,7 +614,38 @@ func (n *nodeContext) validateValue(state vertexStatus) { if n.aStruct != nil { markStruct = true } else if len(n.node.Structs) > 0 { + // TODO: do something more principled here. + // Here we collect evidence that a value is a struct. If a struct has + // an embedding, it may evaluate to an embedded scalar value, in which + // case it is not a struct. Right now this is tracked at the node level, + // but it really should be at the struct level. For instance: + // + // A: matchN(1, [>10]) + // A: { + // if true {c: 1} + // } + // + // Here A is marked as Top by matchN. The other struct also has an + // embedding (the comprehension), and thus does not force it either. + // So the resulting kind is top, not struct. + // As an approximation, we at least mark the node as a struct if it has + // any regular fields. markStruct = n.kind&StructKind != 0 && !n.hasTop + for _, a := range n.node.Arcs { + // TODO(spec): we generally allow optional fields alongside embedded + // scalars. We probably should not. Either way this is not entirely + // accurate, as a Pending arc may still be optional. We should + // collect the arcType noted in adt.Comprehension in a nodeContext + // as well so that we know what the potential arc of this node may + // be. + // + // TODO(evalv3): even better would be to ensure that all + // comprehensions are done before calling this. + if a.Label.IsRegular() && a.ArcType != ArcOptional { + markStruct = true + break + } + } } v := n.node.DerefValue().Value() if n.node.BaseValue == nil && markStruct { @@ -624,7 +657,8 @@ func (n *nodeContext) validateValue(state vertexStatus) { // serious errors and would like to know about all errors anyway. if n.lowerBound != nil { - if b := ctx.Validate(n.lowerBound, v); b != nil { + c := MakeRootConjunct(nil, n.lowerBound) + if b := ctx.Validate(c, v); b != nil { // TODO(errors): make Validate return boolean and generate // optimized conflict message. Also track and inject IDs // to determine origin location.s @@ -636,7 +670,8 @@ func (n *nodeContext) validateValue(state vertexStatus) { } } if n.upperBound != nil { - if b := ctx.Validate(n.upperBound, v); b != nil { + c := MakeRootConjunct(nil, n.upperBound) + if b := ctx.Validate(c, v); b != nil { // TODO(errors): make Validate return boolean and generate // optimized conflict message. Also track and inject IDs // to determine origin location.s @@ -656,6 +691,8 @@ func (n *nodeContext) validateValue(state vertexStatus) { // incompleteErrors reports all errors from uncompleted conjuncts. // If final is true, errors are permanent and reported to parents. func (n *nodeContext) incompleteErrors(final bool) *Bottom { + unreachableForDev(n.ctx) + // collect incomplete errors. var err *Bottom // n.incomplete for _, d := range n.dynamicFields { @@ -757,7 +794,7 @@ func (n *nodeContext) checkClosed(state vertexStatus) bool { if !v.Label.IsInt() && v.Parent != nil && !ignore && v.ArcType <= ArcRequired { ctx := n.ctx // Visit arcs recursively to validate and compute error. - if _, err := verifyArc2(ctx, v.Label, v, v.Closed); err != nil { + if _, err := verifyArc2(ctx, v.Label, v, v.ClosedRecursive); err != nil { // Record error in child node to allow recording multiple // conflicts at the appropriate place, to allow valid fields to // be represented normally and, most importantly, to avoid @@ -772,10 +809,6 @@ func (n *nodeContext) checkClosed(state vertexStatus) bool { func (n *nodeContext) completeArcs(state vertexStatus) { unreachableForDev(n.ctx) - if DebugSort > 0 { - DebugSortArcs(n.ctx, n.node) - } - if n.node.hasAllConjuncts || n.node.Parent == nil { n.node.setParentDone() } @@ -823,7 +856,7 @@ func (n *nodeContext) completeArcs(state vertexStatus) { } if err := a.Bottom(); err != nil { - n.node.AddChildError(err) + n.AddChildError(err) } } @@ -872,6 +905,7 @@ func (n *nodeContext) completeArcs(state vertexStatus) { n.node.AddErr(ctx, &Bottom{ Src: c.expr.Source(), Code: CycleError, + Node: n.node, Err: ctx.NewPosf(pos(c.expr), "circular dependency in evaluation of conditionals: %v changed after evaluation", ctx.Str(c.expr)), @@ -978,6 +1012,10 @@ type nodeContext struct { // for source-level debuggers. node *Vertex + // parent keeps track of the parent Vertex in which a Vertex is being + // evaluated. This is to keep track of the full path in error messages. + parent *Vertex + // underlying is the original Vertex that this node overlays. It should be // set for all Vertex values that were cloned. underlying *Vertex @@ -1001,6 +1039,13 @@ type nodeContext struct { // TODO: also use this to communicate increasingly more concrete values. notify []receiver + // sharedIDs contains all the CloseInfos that are involved in a shared node. + // There can be more than one if the same Vertex is shared multiple times. + // It is important to keep track of each instance as we need to insert each + // of them separately in case a Vertex is "unshared" to ensure that + // closedness information is correctly computed in such cases. + sharedIDs []CloseInfo + // Conjuncts holds a reference to the Vertex Arcs that still need // processing. It does NOT need to be copied. conjuncts []conjunct @@ -1015,8 +1060,14 @@ type nodeContext struct { vLists []*Vertex exprs []envExpr - checks []Validator // BuiltinValidator, other bound values. - postChecks []envCheck // Check non-monotonic constraints, among other things. + // Checks is a list of conjuncts, as we need to preserve the context in + // which it was evaluated. The conjunct is always a validator (and thus + // a Value). We need to keep track of the CloseInfo, however, to be able + // to catch cycles when evaluating BuiltinValidators. + // TODO: introduce ValueConjunct to get better compile time type checking. + checks []Conjunct + + postChecks []envCheck // Check non-monotonic constraints, among other things. // Disjunction handling disjunctions []envDisjunct @@ -1064,6 +1115,8 @@ type conjunct struct { type nodeContextState struct { // isInitialized indicates whether conjuncts have been inserted in the node. + // Use node.isInitialized() to more generally check whether conjuncts have + // been processed. isInitialized bool // toComplete marks whether completeNodeTasks needs to be called on this @@ -1074,6 +1127,12 @@ type nodeContextState struct { // progress. isCompleting int + // runMode keeps track of what runMode a disjunct should run as. This is + // relevant for nested disjunctions, like the 2|3 in (1 | (2|3)) & (1 | 2), + // where the nested disjunction should _not_ be considered as final, as + // there is still a disjunction at a higher level to be processed. + runMode runMode + // evalDept is a number that is assigned when evaluating arcs and is set to // detect structural cycles. This value may be temporarily altered when a // node descends into evaluating a value that may be an error (pattern @@ -1083,15 +1142,18 @@ type nodeContextState struct { // State info - hasTop bool - hasCycle bool // has conjunct with structural cycle - hasNonCycle bool // has conjunct without structural cycle + hasTop bool + hasAnyCyclicConjunct bool // has conjunct with structural cycle + hasAncestorCycle bool // has conjunct with structural cycle to an ancestor + hasNonCycle bool // has material conjuncts without structural cycle + hasNonCyclic bool // has non-cyclic conjuncts at start of field processing - isShared bool // set if we are currently structure sharing. - noSharing bool // set if structure sharing is not allowed - shared Conjunct // the original conjunct that led to sharing - sharedID CloseInfo // the original CloseInfo that led to sharing - origBaseValue BaseValue // the BaseValue that structure sharing replaces. + isShared bool // set if we are currently structure sharing + noSharing bool // set if structure sharing is not allowed + shared Conjunct // the original conjunct that led to sharing + shareCycleType CyclicType // keeps track of the cycle type of shared nodes + origBaseValue BaseValue // the BaseValue that structure sharing replaces + shareDecremented bool // counters of sharedIDs have been decremented depth int32 defaultMode defaultMode @@ -1127,11 +1189,11 @@ type nodeContextState struct { // conjunctsPartialPos is like conjunctsPos, but for the 'partial' phase // of processing where conjuncts are only processed as concrete scalars. conjunctsPartialPos int - - arcPos int } // A receiver receives notifications. +// cc is used for V3 and is nil in V2. +// v is equal to cc.src._cc in V3. type receiver struct { v *Vertex cc *closeContext @@ -1175,6 +1237,7 @@ func (n *nodeContext) clone() *nodeContext { d.arcMap = append(d.arcMap, n.arcMap...) d.notify = append(d.notify, n.notify...) + d.sharedIDs = append(d.sharedIDs, n.sharedIDs...) n.scheduler.cloneInto(&d.scheduler) @@ -1212,6 +1275,7 @@ func (c *OpContext) newNodeContext(node *Vertex) *nodeContext { conjuncts: n.conjuncts[:0], cyclicConjuncts: n.cyclicConjuncts[:0], notify: n.notify[:0], + sharedIDs: n.sharedIDs[:0], checks: n.checks[:0], postChecks: n.postChecks[:0], dynamicFields: n.dynamicFields[:0], @@ -1436,7 +1500,7 @@ func (n *nodeContext) hasErr() bool { if n.node.ChildErrors != nil { return true } - if n.node.status > evaluating && n.node.IsErr() { + if n.node.Status() > evaluating && n.node.IsErr() { return true } return n.ctx.HasErr() || n.errs != nil @@ -1470,7 +1534,7 @@ func (n *nodeContext) getValidators(state vertexStatus) BaseValue { } for _, c := range n.checks { // Drop !=x if x is out of bounds with another bound. - if b, _ := c.(*BoundValue); b != nil && b.Op == NotEqualOp { + if b, _ := c.x.(*BoundValue); b != nil && b.Op == NotEqualOp { if n.upperBound != nil && SimplifyBounds(ctx, n.kind, n.upperBound, b) != nil { continue @@ -1480,8 +1544,9 @@ func (n *nodeContext) getValidators(state vertexStatus) BaseValue { continue } } - a = append(a, c) - kind &= c.Kind() + v := c.x.(Value) + a = append(a, v) + kind &= v.Kind() } if kind&^n.kind != 0 { @@ -1495,7 +1560,7 @@ func (n *nodeContext) getValidators(state vertexStatus) BaseValue { switch len(a) { case 0: // Src is the combined input. - if state >= conjuncts || n.kind&^CompositKind == 0 { + if state >= conjuncts || n.kind&^CompositeKind == 0 { v = &BasicType{K: n.kind} } @@ -1543,7 +1608,6 @@ type envList struct { id CloseInfo ignore bool // has a self-referencing comprehension and is postponed self bool // was added as a postponed self-referencing comprehension - index int } type envCheck struct { @@ -1565,7 +1629,10 @@ func (n *nodeContext) addErr(err errors.Error) { n.assertInitialized() if err != nil { - n.addBottom(&Bottom{Err: err}) + n.addBottom(&Bottom{ + Err: err, + Node: n.node, + }) } } @@ -1784,10 +1851,11 @@ func (n *nodeContext) addVertexConjuncts(c Conjunct, arc *Vertex, inline bool) { // in case an API does many calls to Unify. x := c.Expr() if !inline || arc.IsClosedStruct() || arc.IsClosedList() { - closeInfo = closeInfo.SpawnRef(arc, IsDef(x), x) + isDef, _ := IsDef(x) + closeInfo = closeInfo.SpawnRef(arc, isDef, x) } - if arc.status == 0 && !inline { + if arc.status == unprocessed && !inline { // This is a rare condition, but can happen in certain // evaluation orders. Unfortunately, adding this breaks // resolution of cyclic mutually referring disjunctions. But it @@ -1883,6 +1951,9 @@ func (n *nodeContext) addValueConjunct(env *Environment, v Value, id CloseInfo) switch b := v.(type) { case *Bottom: + if b == NoShareSentinel { + return + } n.addBottom(b) return case *Builtin: @@ -1915,13 +1986,13 @@ func (n *nodeContext) addValueConjunct(env *Environment, v Value, id CloseInfo) switch x.Op { case LessThanOp, LessEqualOp: if y := n.upperBound; y != nil { - n.upperBound = nil v := SimplifyBounds(ctx, n.kind, x, y) if err := valueError(v); err != nil { err.AddPosition(v) err.AddPosition(n.upperBound) err.AddClosedPositions(id) } + n.upperBound = nil n.addValueConjunct(env, v, id) return } @@ -1929,13 +2000,13 @@ func (n *nodeContext) addValueConjunct(env *Environment, v Value, id CloseInfo) case GreaterThanOp, GreaterEqualOp: if y := n.lowerBound; y != nil { - n.lowerBound = nil v := SimplifyBounds(ctx, n.kind, x, y) if err := valueError(v); err != nil { err.AddPosition(v) err.AddPosition(n.lowerBound) err.AddClosedPositions(id) } + n.lowerBound = nil n.addValueConjunct(env, v, id) return } @@ -1945,8 +2016,9 @@ func (n *nodeContext) addValueConjunct(env *Environment, v Value, id CloseInfo) // This check serves as simplifier, but also to remove duplicates. k := 0 match := false + cx := MakeConjunct(env, x, id) for _, c := range n.checks { - if y, ok := c.(*BoundValue); ok { + if y, ok := c.x.(*BoundValue); ok { switch z := SimplifyBounds(ctx, n.kind, x, y); { case z == y: match = true @@ -1959,21 +2031,28 @@ func (n *nodeContext) addValueConjunct(env *Environment, v Value, id CloseInfo) } n.checks = n.checks[:k] if !match { - n.checks = append(n.checks, x) + n.checks = append(n.checks, cx) } return } case Validator: // This check serves as simplifier, but also to remove duplicates. + cx := MakeConjunct(env, x, id) for i, y := range n.checks { - if b := SimplifyValidator(ctx, x, y); b != nil { + if b, ok := SimplifyValidator(ctx, cx, y); ok { n.checks[i] = b return } } n.updateNodeType(x.Kind(), x, id) - n.checks = append(n.checks, x) + n.checks = append(n.checks, cx) + // TODO(validatorType): see namesake TODO in conjunct.go. + k := x.Kind() + if k == TopKind { + n.hasTop = true + } + n.updateNodeType(k, x, id) case *Vertex: // handled above. @@ -2090,6 +2169,7 @@ func (n *nodeContext) addStruct( // TODO(perf): only do this if addExprConjunct below will result in // a fieldSet. Otherwise the entry will just be removed next. id := closeInfo.SpawnEmbed(x) + id.decl = x c := MakeConjunct(childEnv, x, id) n.addExprConjunct(c, partial) @@ -2149,6 +2229,7 @@ func (n *nodeContext) insertField(f Feature, mode ArcType, x Conjunct) *Vertex { default: n.addBottom(&Bottom{ Code: IncompleteError, + Node: n.node, Err: ctx.NewPosf(pos(x.Field()), "cannot add field %s: was already used", f.SelectorString(ctx)), @@ -2189,7 +2270,7 @@ func (n *nodeContext) expandOne(state vertexStatus) (done bool) { unreachableForDev(n.ctx) // Don't expand incomplete expressions if we detected a cycle. - if n.done() || (n.hasCycle && !n.hasNonCycle) { + if n.done() || (n.hasAnyCyclicConjunct && !n.hasNonCycle) { return false } @@ -2468,8 +2549,8 @@ outer: IsOpen: isOpen, }) } else { - if expr, _ := m.Src.(ast.Expr); expr != nil { - sources = append(sources, expr) + if m.Src != nil { + sources = append(sources, m.Src) } m.Src = ast.NewBinExpr(token.AND, sources...) m.IsOpen = m.IsOpen && isOpen diff --git a/vendor/cuelang.org/go/internal/core/adt/expr.go b/vendor/cuelang.org/go/internal/core/adt/expr.go index 445ca925ec..cf25b71e7e 100644 --- a/vendor/cuelang.org/go/internal/core/adt/expr.go +++ b/vendor/cuelang.org/go/internal/core/adt/expr.go @@ -17,7 +17,6 @@ package adt import ( "bytes" "fmt" - "io" "regexp" "github.com/cockroachdb/apd/v3" @@ -88,7 +87,29 @@ func (x *StructLit) evaluate(c *OpContext, state combinedFlags) Value { // used in a context where more conjuncts are added. It may also lead // to disjuncts being in a partially expanded state, leading to // misaligned nodeContexts. - v.CompleteArcs(c) + + // TODO(evalv3): to be fully compatible correct, we should not always + // finalize the arcs here. This is a temporary fix. For now, we have to do + // this as we need a mechanism to set the arcTypeKnown bit without + // finalizing the arcs, as they may depend on the completion of sub fields. + // See, for instance: + // + // chainSuccess: a: { + // raises?: {} + // if raises == _|_ { + // ret: a: 1 + // } + // ret?: {} + // if ret != _|_ { + // foo: a: 1 + // } + // } + // + // This would also require changing the arcType process in ForClause.yield. + // + // v.completeArcs(c, state) + + v.CompleteArcsOnly(c) return v } @@ -294,8 +315,18 @@ func (x *ListLit) Source() ast.Node { func (x *ListLit) evaluate(c *OpContext, state combinedFlags) Value { e := c.Env(0) + // Pass conditions but at least set fieldSetKnown. v := c.newInlineVertex(e.Vertex, nil, Conjunct{e, x, c.ci}) - v.CompleteArcs(c) + v.CompleteArcsOnly(c) + + // TODO(evalv3): evaluating more aggressively yields some improvements, but + // breaks other tests. Consider using this approach, though. + // mode := state.runMode() + // if mode == finalize { + // v.completeArcs(c, allKnown) + // } else { + // v.completeArcs(c, fieldSetKnown) + // } return v } @@ -389,6 +420,9 @@ func (x *ListMarker) node() {} type StructMarker struct { // NeedClose is used to signal that the evaluator should close this struct. // It is only set by the close builtin. + // TODO(evalv3: remove this field. Once we removed this, and also introduced + // open by default lists, we can get rid of StructMarker and ListMarker + // in its entirety in favor of using type bit masks. NeedClose bool } @@ -466,15 +500,18 @@ func (x *BoundExpr) evaluate(ctx *OpContext, state combinedFlags) Value { } switch k := v.Kind(); k { - case IntKind, FloatKind, NumKind, StringKind, BytesKind: + case IntKind, FloatKind, NumberKind, StringKind, BytesKind: case NullKind: if x.Op != NotEqualOp { err := ctx.NewPosf(pos(x.Expr), "cannot use null for bound %s", x.Op) - return &Bottom{Err: err} + return &Bottom{ + Err: err, + Node: ctx.vertex, + } } default: - mask := IntKind | FloatKind | NumKind | StringKind | BytesKind + mask := IntKind | FloatKind | NumberKind | StringKind | BytesKind if x.Op == NotEqualOp { mask |= NullKind } @@ -485,7 +522,10 @@ func (x *BoundExpr) evaluate(ctx *OpContext, state combinedFlags) Value { } err := ctx.NewPosf(pos(x.Expr), "invalid value %s (type %s) for bound %s", v, k, x.Op) - return &Bottom{Err: err} + return &Bottom{ + Err: err, + Node: ctx.vertex, + } } if v, ok := x.Expr.(Value); ok { @@ -592,8 +632,8 @@ func (x *BoundValue) Source() ast.Node { return x.Src } func (x *BoundValue) Kind() Kind { k := x.Value.Kind() switch k { - case IntKind, FloatKind, NumKind: - return NumKind + case IntKind, FloatKind, NumberKind: + return NumberKind case NullKind: if x.Op == NotEqualOp { @@ -622,7 +662,12 @@ func (x *BoundValue) validate(c *OpContext, y Value) *Bottom { // predeclared identifier such as `int`. err := c.Newf("invalid value %v (out of bound %s)", y, x) err.AddPosition(y) - return &Bottom{Src: c.src, Err: err, Code: EvalError} + return &Bottom{ + Src: c.src, + Err: err, + Code: EvalError, + Node: c.vertex, + } default: panic(fmt.Sprintf("unsupported type %T", v)) @@ -901,15 +946,11 @@ func (x *LetReference) resolve(ctx *OpContext, state combinedFlags) *Vertex { // In other words, a Vertex is not necessarily erroneous when a let // field contained in that Vertex is erroneous. - // TODO(order): Do not finalize? Although it is safe to finalize a let - // by itself, it is not necessarily safe, at this point, to finalize any - // references it makes. Originally, let finalization was requested to - // detect cases where multi-mode should be enabled. With the recent compiler - // changes, though, this should be detected statically. Leave this on for - // now, though, as it is not entirely clear it is fine to remove this. - // We can reevaluate this once we have redone some of the planned order of - // evaluation work. - arc.Finalize(ctx) + // We should only partly finalize the result here as it is not safe to + // finalize any references made by the let. + if !ctx.isDevVersion() { + arc.Finalize(ctx) + } b := arc.Bottom() if !arc.MultiLet && b == nil { return arc @@ -918,7 +959,7 @@ func (x *LetReference) resolve(ctx *OpContext, state combinedFlags) *Vertex { // Not caching let expressions may lead to exponential behavior. // The expr uses the expression of a Let field, which can never be used in // any other context. - c := arc.Conjuncts[0] + c := arc.ConjunctAt(0) expr := c.Expr() // A let field always has a single expression and thus ConjunctGroups @@ -958,7 +999,6 @@ func (x *LetReference) resolve(ctx *OpContext, state combinedFlags) *Vertex { // nc.hasNonCycle = true // Allow a first cycle to be skipped. nc.free() - n.unify(ctx, allKnown, finalize) } else { nc := n.getNodeContext(ctx, 0) nc.hasNonCycle = true // Allow a first cycle to be skipped. @@ -995,16 +1035,7 @@ func (x *SelectorExpr) Source() ast.Node { } func (x *SelectorExpr) resolve(c *OpContext, state combinedFlags) *Vertex { - // TODO: the node should really be evaluated as AllConjunctsDone, but the - // order of evaluation is slightly off, causing too much to be evaluated. - // This may especially result in incorrect results when using embedded - // scalars. - // In the new evaluator, evaluation of the node is done in lookup. - // TODO: - // - attempt: if we ensure that errors are propagated in pending arcs. - // - require: if we want to ensure that all arcs - // are known now. - n := c.node(x, x.X, x.Sel.IsRegular(), attempt(partial, needFieldSetKnown)) + n := c.node(x, x.X, x.Sel.IsRegular(), require(partial, needFieldSetKnown)) if n == emptyNode { return n } @@ -1040,11 +1071,7 @@ func (x *IndexExpr) Source() ast.Node { func (x *IndexExpr) resolve(ctx *OpContext, state combinedFlags) *Vertex { // TODO: support byte index. - // TODO: the node should really be evaluated as AllConjunctsDone, but the - // order of evaluation is slightly off, causing too much to be evaluated. - // This may especially result in incorrect results when using embedded - // scalars. - n := ctx.node(x, x.X, true, attempt(partial, needFieldSetKnown)) + n := ctx.node(x, x.X, true, require(partial, needFieldSetKnown)) i := ctx.value(x.Index, require(partial, scalarKnown)) if n == emptyNode { return n @@ -1127,9 +1154,20 @@ func (x *SliceExpr) evaluate(c *OpContext, state combinedFlags) Value { for i, a := range v.Arcs[lo:hi] { label, err := MakeLabel(a.Source(), int64(i), IntLabel) if err != nil { - c.AddBottom(&Bottom{Src: a.Source(), Err: err}) + c.AddBottom(&Bottom{ + Src: a.Source(), + Err: err, + Node: v, + }) return nil } + if v.IsDynamic { + // If the list is dynamic, there is no need to recompute the + // arcs. + a.Label = label + n.Arcs = append(n.Arcs, a) + continue + } arc := *a arc.Parent = n arc.Label = label @@ -1193,6 +1231,7 @@ func (x *Interpolation) evaluate(c *OpContext, state combinedFlags) Value { if err := c.Err(); err != nil { err = &Bottom{ Code: err.Code, + Node: c.vertex, Err: errors.Wrapf(err.Err, pos(x), "invalid interpolation"), } // c.AddBottom(err) @@ -1242,14 +1281,14 @@ func (x *UnaryExpr) evaluate(c *OpContext, state combinedFlags) Value { f.Src = x.Src return &f } - expectedKind = NumKind + expectedKind = NumberKind case AddOp: if v, ok := v.(*Num); ok { // TODO: wrap in thunk to save position of '+'? return v } - expectedKind = NumKind + expectedKind = NumberKind case NotOp: if v, ok := v.(*Bool); ok { @@ -1298,7 +1337,7 @@ func (x *BinaryExpr) evaluate(c *OpContext, state combinedFlags) Value { if env.Vertex.IsDynamic || c.inValidator > 0 { v.Finalize(c) } else { - v.CompleteArcs(c) + v.CompleteArcsOnly(c) } return v @@ -1388,9 +1427,16 @@ func (c *OpContext) validate(env *Environment, src ast.Node, x Expr, op Op, flag // - walk over all fields and verify that fields are not contradicting // previously marked fields. // - v.Finalize(c) + if c.hasDepthCycle(v) { + // Eval V3 logic + c.verifyNonMonotonicResult(env, x, true) + match = op == EqualOp + break + } if v.status == evaluatingArcs { + unreachableForDev(c) // Eval V2 logic + // We have a cycle, which may be an error. Cycle errors may occur // in chains that are themselves not a cycle. It suffices to check // for non-monotonic results at the end for this particular path. @@ -1402,6 +1448,7 @@ func (c *OpContext) validate(env *Environment, src ast.Node, x Expr, op Op, flag match = op == EqualOp break } + v.Finalize(c) switch { case !v.IsDefined(c): @@ -1420,7 +1467,7 @@ func (c *OpContext) validate(env *Environment, src ast.Node, x Expr, op Op, flag } default: - if v.Kind().IsAnyOf(CompositKind) && v.Concreteness() > Concrete && state < conjuncts { + if v.Kind().IsAnyOf(CompositeKind) && v.Concreteness() > Concrete && state < conjuncts { c.PopState(s) c.AddBottom(cycle) return nil @@ -1489,6 +1536,12 @@ func (x *CallExpr) evaluate(c *OpContext, state combinedFlags) Value { switch f := fun.(type) { case *Builtin: b = f + if f.RawFunc != nil { + if !b.checkArgs(c, pos(x), len(x.Args)) { + return nil + } + return f.RawFunc(c, x.Args) + } case *BuiltinValidator: // We allow a validator that takes no arguments except the validated @@ -1517,10 +1570,24 @@ func (x *CallExpr) evaluate(c *OpContext, state combinedFlags) Value { // XXX: XXX: clear id.closeContext per argument and remove from runTask? runMode := state.runMode() - cond := state.conditions() | allAncestorsProcessed | concreteKnown - state = combineMode(cond, runMode).withVertexStatus(state.vertexStatus()) - - expr := c.value(a, state) + cond := state.conditions() + var expr Value + if b.NonConcrete { + state = combineMode(cond, runMode).withVertexStatus(state.vertexStatus()) + expr = c.evalState(a, state) + } else { + cond |= fieldSetKnown | concreteKnown + // Be sure to process disjunctions at the very least when + // finalizing. Requiring disjunctions earlier may lead to too eager + // evaluation. + // + // TODO: Ideally we would always add this flag regardless of mode. + if runMode == finalize { + cond |= disjunctionTask + } + state = combineMode(cond, runMode).withVertexStatus(state.vertexStatus()) + expr = c.value(a, state) + } switch v := expr.(type) { case nil: @@ -1550,7 +1617,9 @@ func (x *CallExpr) evaluate(c *OpContext, state combinedFlags) Value { if result == nil { return nil } - return c.evalState(result, state.withVertexStatus(partial)) + v, ci := c.evalStateCI(result, state.withVertexStatus(partial)) + c.ci = ci + return v } // A Builtin is a value representing a native function call. @@ -1558,7 +1627,20 @@ type Builtin struct { // TODO: make these values for better type checking. Params []Param Result Kind - Func func(c *OpContext, args []Value) Expr + + // NonConcrete should be set to true if a builtin supports non-concrete + // arguments. By default, all arguments are checked to be concrete. + NonConcrete bool + + Func func(c *OpContext, args []Value) Expr + + // RawFunc gives low-level control to CUE's internals for builtins. + // It should be used when fine control over the evaluation process is + // needed. Note that RawFuncs are responsible for returning a Value. This + // gives them fine control over how exactly such value gets evaluated. + // A RawFunc may pass CycleInfo, errors and other information through + // the Context. + RawFunc func(c *OpContext, args []Expr) Value Package Feature Name string @@ -1583,8 +1665,11 @@ func (p Param) Default() Value { return d.Values[0] } -func (x *Builtin) WriteName(w io.Writer, c *OpContext) { - _, _ = fmt.Fprintf(w, "%s.%s", x.Package.StringValue(c), x.Name) +func (x *Builtin) qualifiedName(c *OpContext) string { + if x.Package != InvalidLabel { + return x.Package.StringValue(c) + "." + x.Name + } + return x.Name } // Kind here represents the case where Builtin is used as a Validator. @@ -1616,23 +1701,33 @@ func bottom(v Value) *Bottom { return b } -func (x *Builtin) call(c *OpContext, p token.Pos, validate bool, args []Value) Expr { - fun := x // right now always x. - if len(args) > len(x.Params) { +func (x *Builtin) checkArgs(c *OpContext, p token.Pos, numArgs int) bool { + if numArgs > len(x.Params) { c.addErrf(0, p, "too many arguments in call to %v (have %d, want %d)", - fun, len(args), len(x.Params)) - return nil + x, numArgs, len(x.Params)) + return false } - for i := len(args); i < len(x.Params); i++ { - v := x.Params[i].Default() + if numArgs < len(x.Params) { + // Assume that all subsequent params have a default as well. + v := x.Params[numArgs].Default() if v == nil { c.addErrf(0, p, "not enough arguments in call to %v (have %d, want %d)", - fun, len(args), len(x.Params)) - return nil + x, numArgs, len(x.Params)) + return false } - args = append(args, v) + } + return true +} + +func (x *Builtin) call(c *OpContext, p token.Pos, validate bool, args []Value) Expr { + fun := x // right now always x. + if !x.checkArgs(c, p, len(args)) { + return nil + } + for i := len(args); i < len(x.Params); i++ { + args = append(args, x.Params[i].Default()) } for i, a := range args { if x.Params[i].Kind() == BottomKind { @@ -1735,13 +1830,21 @@ func validateWithBuiltin(c *OpContext, src token.Pos, b *Builtin, args []Value) } default: - return c.NewErrf("invalid validator %s.%s", b.Package.StringValue(c), b.Name) + return c.NewErrf("invalid validator %s", b.qualifiedName(c)) } + // If the validator returns an error and we already had an error, just + // return the original error. + if b, ok := Unwrap(args[0]).(*Bottom); ok { + return b + } // failed: var buf bytes.Buffer - b.WriteName(&buf, c) - if len(args) > 1 { + buf.WriteString(b.qualifiedName(c)) + + // Note: when the builtin accepts non-concrete arguments, omit them because + // they can easily be very large. + if !b.NonConcrete && len(args) > 1 { buf.WriteString("(") for i, a := range args[1:] { if i > 0 { @@ -1752,19 +1855,17 @@ func validateWithBuiltin(c *OpContext, src token.Pos, b *Builtin, args []Value) buf.WriteString(")") } - // If the validator returns an error and we already had an error, just - // return the original error. - if b, ok := Unwrap(args[0]).(*Bottom); ok { - return b - } - vErr := c.NewPosf(src, "invalid value %s (does not satisfy %s)", args[0], buf.String()) for _, v := range args { vErr.AddPosition(v) } - return &Bottom{Code: severeness, Err: errors.Wrap(vErr, err)} + return &Bottom{ + Code: severeness, + Err: errors.Wrap(vErr, err), + Node: c.vertex, + } } // A Disjunction represents a disjunction, where each disjunct may or may not @@ -1922,15 +2023,23 @@ func (x *ForClause) Source() ast.Node { } func (c *OpContext) forSource(x Expr) *Vertex { - state := require(conjuncts, needFieldSetKnown) + state := attempt(conjuncts, needFieldSetKnown) // TODO: always get the vertex. This allows a whole bunch of trickery // down the line. + c.inDetached++ v := c.unifyNode(x, state) + c.inDetached-- node, ok := v.(*Vertex) if ok && c.isDevVersion() { - node.unify(c, state.conditions(), yield) + // We do not request to "yield" here, but rather rely on the + // call-by-need behavior in combination with the freezing mechanism. + // TODO: this seems a bit fragile. At some point we need to make this + // more robust by moving to a pure call-by-need mechanism, for instance. + // TODO: using attemptOnly here will remove the cyclic reference error + // of comprehension.t1.ok (which also errors in V2), + node.unify(c, state.conditions(), finalize) } v, ok = c.getDefault(v) @@ -1968,7 +2077,7 @@ func (c *OpContext) forSource(x Expr) *Vertex { } default: - if kind := v.Kind(); kind&StructKind != 0 { + if kind := v.Kind(); kind&(StructKind|ListKind) != 0 { c.addErrf(IncompleteError, pos(x), "cannot range over %s (incomplete type %s)", x, kind) return emptyNode @@ -1980,6 +2089,17 @@ func (c *OpContext) forSource(x Expr) *Vertex { return emptyNode } } + if c.isDevVersion() { + kind := v.Kind() + // At this point it is possible that the Vertex represents an incomplete + // struct or list, which is the case if it may be struct or list, but + // is also at least some other type, such as is the case with top. + if kind&(StructKind|ListKind) != 0 && kind != StructKind && kind != ListKind { + c.addErrf(IncompleteError, pos(x), + "cannot range over %s (incomplete type %s)", x, kind) + return emptyNode + } + } return node } @@ -1998,6 +2118,7 @@ func (x *ForClause) yield(s *compState) { Code: CycleError, ForCycle: true, Value: n, + Node: n, Err: errors.Newf(pos(x.Src), "comprehension source references itself"), }) return @@ -2014,7 +2135,10 @@ func (x *ForClause) yield(s *compState) { } if c.isDevVersion() { - c.require(a, arcTypeKnown) + // TODO(evalv3): See comment in StructLit.evaluate. + if state := a.getState(c); state != nil { + state.process(arcTypeKnown, attemptOnly) + } } else { if !a.isDefined() { a.Finalize(c) @@ -2041,6 +2165,7 @@ func (x *ForClause) yield(s *compState) { // processing, eluding the deallocation step. status: finalized, IsDynamic: true, + anonymous: true, ArcType: ArcMember, } @@ -2049,6 +2174,7 @@ func (x *ForClause) yield(s *compState) { Label: x.Value, BaseValue: a, IsDynamic: true, + anonymous: true, ArcType: ArcPending, } n.Arcs = append(n.Arcs, b) @@ -2058,6 +2184,7 @@ func (x *ForClause) yield(s *compState) { v := &Vertex{ Label: x.Key, IsDynamic: true, + anonymous: true, } key := a.Label.ToValue(c) v.AddConjunct(MakeRootConjunct(c.Env(0), key)) @@ -2117,6 +2244,7 @@ func (x *LetClause) yield(s *compState) { { Label: x.Label, IsDynamic: true, + anonymous: true, Conjuncts: []Conjunct{{c.Env(0), x.Expr, c.ci}}, }, }} diff --git a/vendor/cuelang.org/go/internal/core/adt/feature.go b/vendor/cuelang.org/go/internal/core/adt/feature.go index 1bcabdb8e8..5b9528e3a0 100644 --- a/vendor/cuelang.org/go/internal/core/adt/feature.go +++ b/vendor/cuelang.org/go/internal/core/adt/feature.go @@ -237,7 +237,7 @@ func LabelFromValue(c *OpContext, src Expr, v Value) Feature { return InvalidLabel } switch v.Kind() { - case IntKind, NumKind: + case IntKind, NumberKind: x, _ := Unwrap(v).(*Num) if x == nil { c.addErrf(IncompleteError, pos(v), msgGround, v, "int") diff --git a/vendor/cuelang.org/go/internal/core/adt/fields.go b/vendor/cuelang.org/go/internal/core/adt/fields.go index ea40ec1cc8..6fe06e7f4d 100644 --- a/vendor/cuelang.org/go/internal/core/adt/fields.go +++ b/vendor/cuelang.org/go/internal/core/adt/fields.go @@ -15,7 +15,7 @@ package adt import ( - "fmt" + "cuelang.org/go/cue/token" ) // This file holds the logic for the insertion of fields and pattern @@ -157,6 +157,10 @@ type closeContext struct { // Used to recursively insert Vertices. parent *closeContext + // depth is the depth from the top following the parent tree. This may be + // relative to an anonymous struct for inline computed values. + depth int + // overlay is used to temporarily link a closeContext to its "overlay" copy, // as it is used in a corresponding disjunction. overlay *closeContext @@ -164,7 +168,13 @@ type closeContext struct { // in disjunction overlays. This is mostly for debugging. generation int - dependencies []*ccDep // For testing only. See debug.go + // a non-zero value indicates that the closeContext is part of a disjunction + // and that it is associated with the given Hole Index. + holeID int + + // dependencies is used to track dependencies that need to be copied in + // overlays. It is also use for testing. + dependencies []*ccDep // externalDeps lists the closeContexts associated with a root node for // which there are outstanding decrements (can only be NOTIFY or ARC). This @@ -172,7 +182,7 @@ type closeContext struct { // // This is only used for root closedContext and only for debugging. // TODO: move to nodeContext. - externalDeps []ccArcRef + externalDeps []ccDepRef // child links to a sequence which additional patterns need to be verified // against (&&). If there are more than one, these additional nodes are @@ -200,12 +210,13 @@ type closeContext struct { arcType ArcType - // isDef indicates whether the closeContext is created as part of a - // definition. + // isDef is true when isDefOrig is true or when isDef is true for any of its + // child nodes, recursively. isDef bool - // hasEllipsis indicates whether the node contains an ellipsis. - hasEllipsis bool + // isDefOrig indicates whether the closeContext is created as part of a + // definition. This value propagates to itself and parents through isDef. + isDefOrig bool // hasTop indicates a node has at least one top conjunct. hasTop bool @@ -255,6 +266,15 @@ type closeContext struct { // tree as this closeContext. In both cases the are keyed by Vertex. arcs []ccArc + // notify represents closeContexts which to notify of updates. + // + // TODO: Note that this slice is very similar to nodeContext.notify and the + // use of these can likely be merged. It may be better to let the notify + // originate from a more specific closeContext, allowing it to stopped + // sooner and possibly even remove the need for breaking dependency + // cycles. + notify []ccNotify + // parentIndex is the position in the parent's arcs slice that corresponds // to this closeContext. This is currently unused. The intention is to use // this to allow groups with single elements (which will be the majority) @@ -272,6 +292,10 @@ type closeContext struct { // context has been completed, but it can be used for initial checking // once isClosed is true. Expr Value + + // decl is the declaration which contains the conjuct which gave + // rise to this closeContext. + decl Decl } // Label is a convenience function to return the label of the associated Vertex. @@ -280,34 +304,50 @@ func (c *closeContext) Label() Feature { } // See also Vertex.updateArcType in composite.go. -func (c *closeContext) updateArcType(t ArcType) { - if t >= c.arcType { +func (c *closeContext) updateArcType(ctx *OpContext, t ArcType) { + if t == ArcPending { return } - if c.arcType == ArcNotPresent { - return + for ; c != nil; c = c.parent { + switch { + case t >= c.arcType: + return + case c.arcType == ArcNotPresent: + ctx.notAllowedError(c.src) + return + default: + c.arcType = t + } } - c.arcType = t } type ccArc struct { - kind depKind + // decremented indicates whether [decDependant] has been called for this + // dependency. decremented bool - key *closeContext - cc *closeContext + // matched indicates the arc is only added to track the destination of a + // matched pattern and that it is not explicitly defined as a field. + // This is only used for arcs and not for notify. + matched bool + // root is dst.src.cc(). TODO: remove and use dst directly. + root *closeContext + // dst is the closeContext for which the counters are incremented and + // decremented and which is the actual destination of the dependency. + dst *closeContext } -// A ccArcRef x refers to the x.src.arcs[x.index]. -// We use this instead of pointers, because the address may change when -// growing a slice. We use this instead mechanism instead of a pointers so -// that we do not need to maintain separate free buffers once we use pools of -// closeContext. -type ccArcRef struct { - src *closeContext - index int +type ccNotify struct { + // decremented indicates whether [decDependant] has been called for this + // dependency. + decremented bool + // dst is the closeContext for which the counters are incremented and + // decremented and which is the actual destination of the dependency. + dst *closeContext } type conjunctGrouper interface { + // Assign conjunct adds the conjunct and returns an arc to represent it, + // along with the position within the group. assignConjunct(ctx *OpContext, root *closeContext, c Conjunct, mode ArcType, check, checkClosed bool) (arc *closeContext, pos int, added bool) } @@ -330,6 +370,7 @@ func (n *nodeContext) getArc(f Feature, mode ArcType) (arc *Vertex, isNew bool) Label: f, ArcType: mode, nonRooted: v.IsDynamic || v.Label.IsLet() || v.nonRooted, + anonymous: v.anonymous || v.Label.IsLet(), } if n.scheduler.frozen&fieldSetKnown != 0 { b := n.ctx.NewErrf("adding field %v not allowed as field set was already referenced", f) @@ -342,28 +383,38 @@ func (n *nodeContext) getArc(f Feature, mode ArcType) (arc *Vertex, isNew bool) } func (v *Vertex) assignConjunct(ctx *OpContext, root *closeContext, c Conjunct, mode ArcType, check, checkClosed bool) (a *closeContext, pos int, added bool) { + // TODO: consider clearing CloseInfo.cc. // c.CloseInfo.cc = nil arc := root.src arc.updateArcType(mode) // TODO: probably not necessary: consider removing. - pos = len(arc.Conjuncts) + if &arc.Conjuncts != root.group { + panic("misaligned conjuncts") + } - added = !check || !arc.hasConjunct(c) - if added { + pos = -1 + if check { + pos = findConjunct(arc.Conjuncts, c) + } + if pos == -1 { + pos = len(arc.Conjuncts) c.CloseInfo.cc = root arc.addConjunctUnchecked(c) + added = true } return root, pos, added } func (cc *closeContext) getKeyedCC(ctx *OpContext, key *closeContext, c CycleInfo, mode ArcType, checkClosed bool) *closeContext { - for _, a := range cc.arcs { - if a.key == key { - a.cc.updateArcType(mode) - return a.cc + for i := range cc.arcs { + a := &cc.arcs[i] + if a.root == key { + a.matched = a.matched && !checkClosed + a.dst.updateArcType(ctx, mode) + return a.dst } } @@ -383,6 +434,8 @@ func (cc *closeContext) getKeyedCC(ctx *OpContext, key *closeContext, c CycleInf }, mode, false, checkClosed) arc := &closeContext{ + // origin: cc.origin, + depth: cc.depth, generation: cc.generation, parent: parent, parentConjuncts: parent, @@ -393,6 +446,7 @@ func (cc *closeContext) getKeyedCC(ctx *OpContext, key *closeContext, c CycleInf group: group, isDef: cc.isDef, + isDefOrig: cc.isDefOrig, isEmbed: cc.isEmbed, needsCloseInSchedule: cc, } @@ -407,7 +461,8 @@ func (cc *closeContext) getKeyedCC(ctx *OpContext, key *closeContext, c CycleInf if !arc.Label().IsLet() { // prevent a dependency on self. if key.src != cc.src { - cc.addDependency(ctx, ARC, key, arc, key) + matched := !checkClosed + cc.addArcDependency(ctx, matched, arc) } } @@ -419,36 +474,48 @@ func (cc *closeContext) getKeyedCC(ctx *OpContext, key *closeContext, c CycleInf return arc } -func (cc *closeContext) linkNotify(ctx *OpContext, dst *Vertex, key *closeContext, c CycleInfo) bool { - for _, a := range cc.arcs { - if a.key == key { - return false - } - } - - cc.addDependency(ctx, NOTIFY, key, key, dst.cc) - return true -} - func (cc *closeContext) assignConjunct(ctx *OpContext, root *closeContext, c Conjunct, mode ArcType, check, checkClosed bool) (arc *closeContext, pos int, added bool) { arc = cc.getKeyedCC(ctx, root, c.CloseInfo.CycleInfo, mode, checkClosed) - pos = len(*arc.group) - c.CloseInfo.cc = nil - added = !check || !hasConjunct(*arc.group, c) - if added { + + var group ConjunctGroup + if arc.group != nil { + group = *arc.group + } + pos = -1 + if check { + pos = findConjunct(group, c) + } + if pos == -1 { + pos = len(group) + added = true + c.CloseInfo.cc = arc if c.CloseInfo.cc.src != arc.src { panic("Inconsistent src") } - *arc.group = append(*arc.group, c) - } + group = append(group, c) + if arc.group == nil { + arc.group = &group + } else { + *arc.group = group + } + } return arc, pos, added } +// TODO: cache depth. +func VertexDepth(v *Vertex) int { + depth := 0 + for p := v.Parent; p != nil; p = p.Parent { + depth++ + } + return depth +} + // spawnCloseContext wraps the closeContext in c with a new one and returns // this new context along with an updated CloseInfo. The new values reflect // that the set of fields represented by c are now, for instance, enclosed in @@ -461,9 +528,12 @@ func (c CloseInfo) spawnCloseContext(ctx *OpContext, t closeNodeType) (CloseInfo panic("nil closeContext") } + depth := VertexDepth(cc.src) + c.cc = &closeContext{ generation: cc.generation, parent: cc, + depth: depth, src: cc.src, parentConjuncts: cc, } @@ -473,6 +543,7 @@ func (c CloseInfo) spawnCloseContext(ctx *OpContext, t closeNodeType) (CloseInfo switch t { case closeDef: c.cc.isDef = true + c.cc.isDefOrig = true case closeEmbed: c.cc.isEmbed = true } @@ -480,85 +551,10 @@ func (c CloseInfo) spawnCloseContext(ctx *OpContext, t closeNodeType) (CloseInfo return c, c.cc } -// addDependency adds a dependent arc to c. If child is an arc, child.src == key -func (c *closeContext) addDependency(ctx *OpContext, kind depKind, key, child, root *closeContext) { - // NOTE: do not increment - // - either root closeContext or otherwise resulting from sub closeContext - // all conjuncts will be added now, notified, or scheduled as task. - - child.incDependent(ctx, kind, c) // matched in decDependent REF(arcs) - - for _, a := range c.arcs { - if a.key == key { - panic("addArc: Label already exists") - } - } - - // TODO: this tests seems sensible, but panics. Investigate what could - // trigger this. - // if child.src.Parent != c.src { - // panic("addArc: inconsistent parent") - // } - if child.src.cc != root.src.cc { - panic("addArc: inconsistent root") - } - c.arcs = append(c.arcs, ccArc{ - kind: kind, - key: key, - cc: child, - }) - root.externalDeps = append(root.externalDeps, ccArcRef{ - src: c, - index: len(c.arcs) - 1, - }) -} - -// incDependent needs to be called for any conjunct or child closeContext -// scheduled for c that is queued for later processing and not scheduled -// immediately. -func (c *closeContext) incDependent(ctx *OpContext, kind depKind, dependant *closeContext) (debug *ccDep) { - if c.src == nil { - panic("incDependent: unexpected nil src") - } - if dependant != nil && c.generation != dependant.generation { - // TODO: enable this check. - - // panic(fmt.Sprintf("incDependent: inconsistent generation: %d %d", c.generation, dependant.generation)) - } - debug = c.addDependent(ctx, kind, dependant) - - if c.done { - openDebugGraph(ctx, c.src, "incDependent: already checked") - - panic(fmt.Sprintf("incDependent: already closed: %p", c)) - } - - c.conjunctCount++ - return debug -} - -// decDependent needs to be called for any conjunct or child closeContext for -// which a corresponding incDependent was called after it has been successfully -// processed. -func (c *closeContext) decDependent(ctx *OpContext, kind depKind, dependant *closeContext) { - v := c.src - - c.matchDecrement(ctx, v, kind, dependant) - - if c.conjunctCount == 0 { - panic(fmt.Sprintf("negative reference counter %d %p", c.conjunctCount, c)) - } - - c.conjunctCount-- - if c.conjunctCount > 0 { - return - } - - c.done = true - +func (c *closeContext) updateClosedInfo(ctx *OpContext) bool { p := c.parent - if c.isDef && !c.hasEllipsis && (!c.hasTop || c.hasNonTop) { + if c.isDef && !c.isTotal && (!c.hasTop || c.hasNonTop) { c.isClosed = true if p != nil { p.isDef = true @@ -572,18 +568,10 @@ func (c *closeContext) decDependent(ctx *OpContext, kind depKind, dependant *clo } } - for i, a := range c.arcs { - cc := a.cc - if a.decremented { - continue - } - c.arcs[i].decremented = true - cc.decDependent(ctx, a.kind, c) // REF(arcs) - } - c.finalizePattern() if p == nil { + v := c.src // Root pattern, set allowed patterns. if pcs := v.PatternConstraints; pcs != nil { if pcs.Allowed != nil { @@ -592,14 +580,11 @@ func (c *closeContext) decDependent(ctx *OpContext, kind depKind, dependant *clo // panic("unexpected allowed set") } pcs.Allowed = c.Expr - return + return false } - return + return false } - if c.hasEllipsis { - p.hasEllipsis = true - } if c.hasTop { p.hasTop = true } @@ -624,57 +609,25 @@ func (c *closeContext) decDependent(ctx *OpContext, kind depKind, dependant *clo p.linkPatterns(c) } - p.decDependent(ctx, PARENT, c) // REF(decrement: spawn) - - // If we have started decrementing a child closeContext, the parent started - // as well. If it is still marked as needing an EVAL decrement, which can - // happen if processing started before the node was added, it is safe to - // decrement it now. In this case the NOTIFY and ARC dependencies will keep - // the nodes alive until they can be completed. - if dep := p.needsCloseInSchedule; dep != nil { - p.needsCloseInSchedule = nil - p.decDependent(ctx, EVAL, dep) - } -} - -// incDisjunct increases disjunction-related counters. We require kind to be -// passed explicitly so that we can easily find the points where certain kinds -// are used. -func (c *closeContext) incDisjunct(ctx *OpContext, kind depKind) { - if kind != DISJUNCT { - panic("unexpected kind") - } - c.incDependent(ctx, DISJUNCT, nil) - - // TODO: the counters are only used in debug mode and we could skip this - // if debug is disabled. - for ; c != nil; c = c.parent { - c.disjunctCount++ - } -} - -// decDisjunct decreases disjunction-related counters. We require kind to be -// passed explicitly so that we can easily find the points where certain kinds -// are used. -func (c *closeContext) decDisjunct(ctx *OpContext, kind depKind) { - if kind != DISJUNCT { - panic("unexpected kind") - } - c.decDependent(ctx, DISJUNCT, nil) - - // TODO: the counters are only used in debug mode and we could skip this - // if debug is disabled. - for ; c != nil; c = c.parent { - c.disjunctCount++ - } + return true } // linkPatterns merges the patterns of child into c, if needed. func (c *closeContext) linkPatterns(child *closeContext) { - if len(child.Patterns) > 0 { - child.next = c.child - c.child = child - } + // We need to always add the closeContext, as this closeContext may, for + // instance, be an embedding within a definition. In other words, we do + // not know yet if this information will be relevant for closedness. + child.next = c.child + c.child = child +} + +// allowedInClosed reports whether a field with label f is allowed in a closed +// struct, even when it is not explicitly defined. +// +// TODO: see https://github.com/cue-lang/cue/issues/543 +// for whether to include f.IsDef. +func allowedInClosed(f Feature) bool { + return f.IsHidden() || f.IsDef() || f.IsLet() } // checkArc validates that the node corresponding to cc allows a field with @@ -685,12 +638,12 @@ func (n *nodeContext) checkArc(cc *closeContext, v *Vertex) *Vertex { f := v.Label ctx := n.ctx - if f.IsHidden() || f.IsLet() { + if allowedInClosed(f) { return v } if cc.isClosed && !matchPattern(ctx, cc.Expr, f) { - ctx.notAllowedError(n.node, v) + ctx.notAllowedError(v) } if n.scheduler.frozen&fieldSetKnown != 0 { for _, a := range n.node.Arcs { @@ -730,6 +683,11 @@ func (cc *closeContext) insertConjunct(ctx *OpContext, key *closeContext, c Conj return } + switch id.CycleType { + case NoCycle, IsOptional: + n.hasNonCyclic = true + } + if key.src.isInProgress() { c.CloseInfo.cc = nil id.cc = arc @@ -737,13 +695,16 @@ func (cc *closeContext) insertConjunct(ctx *OpContext, key *closeContext, c Conj } for _, rec := range n.notify { - if mode == ArcPending { - panic("unexpected pending arc") - } + // TODO(evalv3): currently we get pending arcs here for some tests. + // That seems fine. But consider this again when most of evalv3 work + // is done. See test "pending.cue" in comprehensions/notify2.txtar + // It seems that only let arcs can be pending, though. + // TODO: we should probably only notify a conjunct once the root of the // conjunct group is completed. This will make it easier to "stitch" the // conjunct trees together, as its correctness will be guaranteed. - cc.insertConjunct(ctx, rec.cc, c, id, mode, check, checkClosed) + c.CloseInfo.cc = rec.cc + rec.v.state.scheduleConjunct(c, id) } return @@ -775,22 +736,23 @@ func (n *nodeContext) insertArcCC(f Feature, mode ArcType, c Conjunct, id CloseI defer n.ctx.PopArc(n.ctx.PushArc(v)) - // TODO: this block is not strictly needed. Removing it slightly changes the - // paths at which errors are reported, arguably, but not clearly, for the - // better. Investigate this once the new evaluator is done. - if v.ArcType == ArcNotPresent { - // It was already determined before that this arc may not be present. - // This case can only manifest itself if we have a cycle. - n.node.reportFieldCycleError(n.ctx, pos(c.x), f) - return v, nil - } + // TODO: reporting the cycle error here results in better error paths. + // However, it causes the reference counting mechanism to be faulty. + // Reevaluate once the new evaluator is done. + // if v.ArcType == ArcNotPresent { + // // It was already determined before that this arc may not be present. + // // This case can only manifest itself if we have a cycle. + // n.node.reportFieldCycleError(n.ctx, pos(c.x), f) + // return v, nil + // } - if v.cc == nil { - v.cc = v.rootCloseContext(n.ctx) - v.cc.generation = n.node.cc.generation + if v.cc() == nil { + v.rootCloseContext(n.ctx) + // TODO(evalv3): reevaluate need for generation + v._cc.generation = n.node._cc.generation } - arc, added := cc.insertConjunct(n.ctx, v.cc, c, id, mode, check, true) + arc, added := cc.insertConjunct(n.ctx, v.cc(), c, id, mode, check, true) if !added { return v, arc } @@ -855,9 +817,16 @@ func (n *nodeContext) addConstraint(arc *Vertex, mode ArcType, c Conjunct, check // closedness check. cc := c.CloseInfo.cc + // TODO: can go, but do in separate CL. arc, _ = n.getArc(f, mode) root := arc.rootCloseContext(n.ctx) + + // Note: we are inserting the conjunct int the closeContext corresponding to + // the constraint. This will add an arc to the respective closeContext. In + // order to keep closedness information consistent, we need to ensure that, + // if the arc was otherwise not added in this context, the arc is marked as + // not really present. cc.insertConjunct(n.ctx, root, c, c.CloseInfo, mode, check, false) } @@ -870,32 +839,25 @@ func (n *nodeContext) insertPattern(pattern Value, c Conjunct) { // Collect patterns in root vertex. This allows comparing disjuncts for // equality as well as inserting new arcs down the line as they are // inserted. - if !n.insertConstraint(pattern, c) { - return - } - - // Match against full set of arcs from root, but insert in current vertex. - // Hypothesis: this may not be necessary. Maybe for closedness. - // TODO: may need to replicate the closedContext for patterns. - // Also: Conjuncts for matching other arcs in this node may be different - // for matching arcs using v.foo?, if we need to ensure that conjuncts - // from arcs and patterns are grouped under the same vertex. - // TODO: verify. See test Pattern 1b - for _, a := range n.node.Arcs { - if matchPattern(n.ctx, pattern, a.Label) { - // TODO: is it necessary to check for uniqueness here? - n.addConstraint(a, a.ArcType, c, true) + if n.insertConstraint(pattern, c) { + // Match against full set of arcs from root, but insert in current vertex. + // Hypothesis: this may not be necessary. Maybe for closedness. + // TODO: may need to replicate the closedContext for patterns. + // Also: Conjuncts for matching other arcs in this node may be different + // for matching arcs using v.foo?, if we need to ensure that conjuncts + // from arcs and patterns are grouped under the same vertex. + // TODO: verify. See test Pattern 1b + for _, a := range n.node.Arcs { + if matchPattern(n.ctx, pattern, a.Label) { + // TODO: is it necessary to check for uniqueness here? + n.addConstraint(a, a.ArcType, c, true) + } } } if cc.isTotal { return } - if isTotal(pattern) { - cc.isTotal = true - cc.Patterns = cc.Patterns[:0] - return - } // insert pattern in current set. // TODO: normalize patterns @@ -926,44 +888,19 @@ func isTotal(p Value) bool { // and patterns defined in closed. It reports an error in the nodeContext if // this is not the case. func injectClosed(ctx *OpContext, closed, dst *closeContext) { - // TODO: check that fields are not void arcs. -outer: for _, a := range dst.arcs { - if a.kind != ARC { - continue - } - ca := a.cc - f := ca.Label() - switch ca.src.ArcType { - case ArcMember, ArcRequired: - case ArcOptional, ArcNotPresent: + ca := a.dst + switch f := ca.Label(); { + case ca.src.ArcType == ArcOptional, // Without this continue, an evaluation error may be propagated to // parent nodes that are otherwise allowed. - continue - case ArcPending: - // TODO: Need to evaluate? + // TODO(evalv3): consider using ca.arcType instead. + allowedInClosed(f), + closed.allows(ctx, f): + case ca.arcType == ArcPending: + ca.arcType = ArcNotPresent default: - panic("unreachable") - } - // TODO: disallow new definitions in closed structs. - if f.IsHidden() || f.IsLet() || f.IsDef() { - continue - } - for _, b := range closed.arcs { - cb := b.cc - // TODO: we could potentially remove the check for ArcPending if we - // explicitly set the arcType to ArcNonPresent when a comprehension - // yields no results. - if cb.arcType == ArcNotPresent || cb.arcType == ArcPending { - continue - } - if f == cb.Label() { - continue outer - } - } - if !matchPattern(ctx, closed.Expr, ca.Label()) { - ctx.notAllowedError(closed.src, ca.src) - continue + ctx.notAllowedError(ca.src) } } @@ -980,6 +917,25 @@ outer: } } +func (c *closeContext) allows(ctx *OpContext, f Feature) bool { + ctx.Assertf(token.NoPos, c.conjunctCount == 0, "unexpected 0 conjunctCount") + + for _, b := range c.arcs { + cb := b.dst + if b.matched || f != cb.Label() { + continue + } + // TODO: we could potentially remove the check for ArcPending if we + // explicitly set the arcType to ArcNonPresent when a comprehension + // yields no results. + if cb.arcType == ArcNotPresent || cb.arcType == ArcPending { + continue + } + return true + } + return matchPattern(ctx, c.Expr, f) +} + func (ctx *OpContext) addPositions(c Conjunct) { if x, ok := c.x.(*ConjunctGroup); ok { for _, c := range *x { @@ -993,7 +949,13 @@ func (ctx *OpContext) addPositions(c Conjunct) { // notAllowedError reports a field not allowed error in n and sets the value // for arc f to that error. -func (ctx *OpContext) notAllowedError(v, arc *Vertex) { +func (ctx *OpContext) notAllowedError(arc *Vertex) { + // TODO(compat): ultimately we should strive to remove this explicit + // reproduction of a bug to ensure compatibility with the old evaluator. + if ctx.inLiteralSelectee > 0 { + return + } + defer ctx.PopArc(ctx.PushArc(arc)) defer ctx.ReleasePositions(ctx.MarkPositions()) @@ -1015,6 +977,12 @@ func (ctx *OpContext) notAllowedError(v, arc *Vertex) { // has been evaluated. return } + ctx.Assertf(ctx.pos(), !allowedInClosed(arc.Label), "unexpected disallowed definition, let, or hidden field") + if ctx.HasErr() { + // The next error will override this error when not run in Strict mode. + return + } + // TODO: setting arc instead of n.node eliminates subfields. This may be // desirable or not, but it differs, at least from <=v0.6 behavior. arc.SetValue(ctx, ctx.NewErrf("field not allowed")) @@ -1072,9 +1040,13 @@ func mergeConjunctions(a, b Value) Value { func (c *closeContext) finalizePattern() { switch { case c.Expr != nil: // Patterns and expression are already set. - if !c.isClosed { - panic("c.Expr set unexpectedly") - } + // NOTE: this panic check is just to verify using Expr unnecessarily. It + // is not the end of the world to use c.Expr, it is just less efficient. + // If this check causes trouble, it can be removed. + // TODO(openlists): reenable once we support open list semantics. + // if !c.isClosed { + // panic("c.Expr set unexpectedly") + // } return case c.isTotal: // All values are allowed always. return diff --git a/vendor/cuelang.org/go/internal/core/adt/kind.go b/vendor/cuelang.org/go/internal/core/adt/kind.go index 17c128049b..b11112b9a2 100644 --- a/vendor/cuelang.org/go/internal/core/adt/kind.go +++ b/vendor/cuelang.org/go/internal/core/adt/kind.go @@ -71,16 +71,14 @@ const ( _numberKind - NumberKind = IntKind | FloatKind - BottomKind Kind = 0 - NumKind = IntKind | FloatKind + NumberKind = IntKind | FloatKind TopKind Kind = (allKinds - 1) // all kinds, but not references ScalarKinds = NullKind | BoolKind | IntKind | FloatKind | StringKind | BytesKind - CompositKind = StructKind | ListKind + CompositeKind = StructKind | ListKind ) func kind(v Value) Kind { diff --git a/vendor/cuelang.org/go/internal/core/adt/log.go b/vendor/cuelang.org/go/internal/core/adt/log.go new file mode 100644 index 0000000000..946e380136 --- /dev/null +++ b/vendor/cuelang.org/go/internal/core/adt/log.go @@ -0,0 +1,219 @@ +// Copyright 2025 CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package adt + +import ( + "fmt" + "log" + "strings" + + "cuelang.org/go/cue/token" +) + +// Assert panics if the condition is false. Assert can be used to check for +// conditions that are considers to break an internal variant or unexpected +// condition, but that nonetheless probably will be handled correctly down the +// line. For instance, a faulty condition could lead to error being caught +// down the road, but resulting in an inaccurate error message. In production +// code it is better to deal with the bad error message than to panic. +// +// It is advisable for each use of Assert to document how the error is expected +// to be handled down the line. +func Assertf(c *OpContext, b bool, format string, args ...interface{}) { + if c.Strict && !b { + panic(fmt.Sprintf("assertion failed: "+format, args...)) + } +} + +// Assertf either panics or reports an error to c if the condition is not met. +func (c *OpContext) Assertf(pos token.Pos, b bool, format string, args ...interface{}) { + if !b { + if c.Strict { + panic(fmt.Sprintf("assertion failed: "+format, args...)) + } + c.addErrf(0, pos, format, args...) + } +} + +func init() { + log.SetFlags(0) +} + +var pMap = map[*Vertex]int{} + +func (c *OpContext) Logf(v *Vertex, format string, args ...interface{}) { + if c.LogEval == 0 { + return + } + w := &strings.Builder{} + + c.logID++ + fmt.Fprintf(w, "%3d ", c.logID) + + if c.nest > 0 { + for i := 0; i < c.nest; i++ { + w.WriteString("... ") + } + } + + if v == nil { + fmt.Fprintf(w, format, args...) + _ = log.Output(2, w.String()) + return + } + + p := pMap[v] + if p == 0 { + p = len(pMap) + 1 + pMap[v] = p + } + disjunctInfo := c.disjunctInfo() + fmt.Fprintf(w, "[n:%d/%v %s%s] ", + p, v.Path(), c.PathToString(v.Path()), disjunctInfo) + + for i, a := range args { + switch x := a.(type) { + case Node: + args[i] = c.Str(x) + case Feature: + args[i] = x.SelectorString(c) + } + } + fmt.Fprintf(w, format, args...) + + _ = log.Output(2, w.String()) +} + +// PathToString creates a pretty-printed path of the given list of features. +func (c *OpContext) PathToString(path []Feature) string { + var b strings.Builder + for i, f := range path { + if i > 0 { + b.WriteByte('.') + } + b.WriteString(f.SelectorString(c)) + } + return b.String() +} + +type disjunctInfo struct { + node *nodeContext + disjunctionID int // unique ID for sequence + disjunctionSeq int // index into node.disjunctions + numDisjunctions int // number of disjunctions + crossProductSeq int // index into node.disjuncts (previous results) + numPrevious int // index into node.disjuncts (previous results) + numDisjuncts int // index into node.disjuncts (previous results) + disjunctID int // unique ID for disjunct + disjunctSeq int // index into node.disjunctions[disjunctionSeq].disjuncts + holeID int // unique ID for hole + lhs Node // current LHS expression + rhs Node // current RHS expression +} + +func (c *OpContext) currentDisjunct() *disjunctInfo { + if len(c.disjunctStack) == 0 { + panic("no disjunct") + } + return &c.disjunctStack[len(c.disjunctStack)-1] +} + +func (n *nodeContext) pushDisjunctionTask() *disjunctInfo { + c := n.ctx + c.currentDisjunctionID++ + id := disjunctInfo{ + node: n, + disjunctionID: c.currentDisjunctionID, + } + c.disjunctStack = append(c.disjunctStack, id) + + n.Logf("========= DISJUNCTION %d =========", c.currentDisjunctionID) + c.nest += 1 + + return c.currentDisjunct() +} + +func (n *nodeContext) nextDisjunction(index, num, hole int) { + d := n.ctx.currentDisjunct() + + d.disjunctionSeq = index + 1 + d.numDisjunctions = num + d.holeID = hole +} + +func (n *nodeContext) nextCrossProduct(index, num int, v *nodeContext) *disjunctInfo { + d := n.ctx.currentDisjunct() + + d.crossProductSeq = index + 1 + d.numPrevious = num + d.lhs = v.node.Value() + + return d +} + +func (n *nodeContext) nextDisjunct(index, num int, expr Node) { + d := n.ctx.currentDisjunct() + + d.disjunctSeq = index + 1 + d.numDisjuncts = num + d.rhs = expr +} + +func (n *nodeContext) logDoDisjunct() *disjunctInfo { + c := n.ctx + c.stats.Disjuncts++ + + d := c.currentDisjunct() + + d.disjunctID = int(c.stats.Disjuncts) + + n.Logf("====== Do DISJUNCT %v & %v ======", d.lhs, d.rhs) + + return d +} + +func (d disjunctInfo) pop() { + c := d.node.ctx + c.nest -= 1 + c.disjunctStack = c.disjunctStack[:len(c.disjunctStack)-1] +} + +// disjunctInfo prints a header for log to indicate the current disjunct. +func (c *OpContext) disjunctInfo() string { + if len(c.disjunctStack) == 0 { + return "" + } + var b strings.Builder + for i, d := range c.disjunctStack { + if i != len(c.disjunctStack)-1 && d.disjunctID == 0 { + continue + } + if i != 0 { + b.WriteString(" =>") + } + // which disjunct + fmt.Fprintf(&b, " D%d:H%d:%d/%d", + d.disjunctionID, d.holeID, d.disjunctionSeq, d.numDisjunctions) + if d.crossProductSeq != 0 { + fmt.Fprintf(&b, " P%d/%d", d.crossProductSeq, d.numPrevious) + } + if d.disjunctID != 0 { + fmt.Fprintf(&b, " d%d:%d/%d", + d.disjunctID, d.disjunctSeq, d.numDisjuncts, + ) + } + } + return b.String() +} diff --git a/vendor/cuelang.org/go/internal/core/adt/optional.go b/vendor/cuelang.org/go/internal/core/adt/optional.go index 3606a6dae7..cb99dd26c4 100644 --- a/vendor/cuelang.org/go/internal/core/adt/optional.go +++ b/vendor/cuelang.org/go/internal/core/adt/optional.go @@ -92,6 +92,8 @@ func (o *StructInfo) MatchAndInsert(c *OpContext, arc *Vertex) { // matchBulk reports whether feature f matches the filter of x. It evaluation of // the filter is erroneous, it returns false and the error will be set in c. func matchBulk(c *OpContext, env *Environment, p *BulkOptionalField, f Feature, label Value) bool { + unreachableForDev(c) + v := env.evalCached(c, p.Filter) v = Unwrap(v) @@ -104,7 +106,8 @@ func matchBulk(c *OpContext, env *Environment, p *BulkOptionalField, f Feature, err.AddPosition(c.Elem()) } c.AddBottom(&Bottom{ - Err: err, + Err: err, + Node: c.vertex, }) } if c.errs == nil { diff --git a/vendor/cuelang.org/go/internal/core/adt/overlay.go b/vendor/cuelang.org/go/internal/core/adt/overlay.go index 93554c8465..cd9216153e 100644 --- a/vendor/cuelang.org/go/internal/core/adt/overlay.go +++ b/vendor/cuelang.org/go/internal/core/adt/overlay.go @@ -74,23 +74,33 @@ type overlayContext struct { vertices []*Vertex } -// cloneRoot clones the a Vertex in which disjunctions are defined to allow +// cloneRoot clones the Vertex in which disjunctions are defined to allow // inserting selected disjuncts into a new Vertex. func (ctx *overlayContext) cloneRoot(root *nodeContext) *nodeContext { // Clone all vertices that need to be cloned to support the overlay. v := ctx.cloneVertex(root.node) v.IsDisjunct = true + // At this point we have copied all the mandatory closeContexts. There + // may be derivative closeContexts copied as well. + // TODO: patch notifications to any node that is within the disjunct to // point to the new vertex instead. // Initialize closeContexts: at this point, all closeContexts that need to // be cloned have been allocated and stored in closeContexts and can now be // initialized. - for _, cc := range ctx.closeContexts { + // Use an explicit index as initCloneCC uses allocCC, which MAY allocate a + // new closeContext. It probably does not, but we use an index in case. + for i := 0; i < len(ctx.closeContexts); i++ { + cc := ctx.closeContexts[i] ctx.initCloneCC(cc) } + for _, cc := range ctx.closeContexts { + ctx.finishDependencies(cc) + } + // TODO: walk overlay vertices and decrement counters of non-disjunction // running tasks? // TODO: find a faster way to do this. Walking over vertices would @@ -150,11 +160,16 @@ func (ctx *overlayContext) cloneVertex(x *Vertex) *Vertex { ctx.vertices = append(ctx.vertices, v) - v.cc = ctx.allocCC(x.cc) + v._cc = ctx.allocCC(x.cc()) + + v._cc.src = v + v._cc.parentConjuncts = v - v.cc.src = v - v.cc.parentConjuncts = v - v.Conjuncts = *v.cc.group + // The group of the root closeContext should point to the Conjuncts field + // of the Vertex. As we already allocated the group, we use that allocation, + // but "move" it to v.Conjuncts. + v.Conjuncts = *v._cc.group + v._cc.group = &v.Conjuncts if a := x.Arcs; len(a) > 0 { // TODO(perf): reuse buffer. @@ -193,9 +208,8 @@ func (ctx *overlayContext) cloneVertex(x *Vertex) *Vertex { } func (ctx *overlayContext) cloneNodeContext(n *nodeContext) *nodeContext { - if !n.isInitialized { + if !n.node.isInitialized() { panic("unexpected uninitialized node") - } d := n.ctx.newNodeContext(n.node) d.underlying = n.underlying @@ -213,6 +227,11 @@ func (ctx *overlayContext) cloneNodeContext(n *nodeContext) *nodeContext { d.arcMap = append(d.arcMap, n.arcMap...) d.checks = append(d.checks, n.checks...) + for _, s := range n.sharedIDs { + s.cc = ctx.allocCC(s.cc) + d.sharedIDs = append(d.sharedIDs, s) + } + // TODO: do we need to add cyclicConjuncts? Typically, cyclicConjuncts // gets cleared at the end of a unify call. There are cases, however, where // this is possible. We should decide whether cyclicConjuncts should be @@ -223,12 +242,9 @@ func (ctx *overlayContext) cloneNodeContext(n *nodeContext) *nodeContext { // d.cyclicConjuncts = append(d.cyclicConjuncts, n.cyclicConjuncts...) if len(n.disjunctions) > 0 { - for _, de := range n.disjunctions { - // Do not clone cc, as it is identified by underlying. We only need - // to clone the cc in disjunctCCs. - // de.cloneID.cc = ctx.allocCC(de.cloneID.cc) - d.disjunctions = append(d.disjunctions, de) - } + // Do not clone cc in disjunctions, as it is identified by underlying. + // We only need to clone the cc in disjunctCCs. + d.disjunctions = append(d.disjunctions, n.disjunctions...) for _, h := range n.disjunctCCs { h.cc = ctx.allocCC(h.cc) d.disjunctCCs = append(d.disjunctCCs, h) @@ -265,6 +281,8 @@ func (ctx *overlayContext) allocCC(cc *closeContext) *closeContext { o := &closeContext{generation: ctx.generation} cc.overlay = o + o.depth = cc.depth + o.holeID = cc.holeID if cc.parent != nil { o.parent = ctx.allocCC(cc.parent) @@ -280,13 +298,16 @@ func (ctx *overlayContext) allocCC(cc *closeContext) *closeContext { } if o.parent != nil { - // validate invariants - ca := *cc.parent.group - if ca[cc.parentIndex].x != cc.group { - panic("group misaligned") + // validate invariants. + // TODO: the group can sometimes be empty. Investigate why and + // whether this is valid. + if ca := *cc.parent.group; len(ca) > 0 { + if ca[cc.parentIndex].x != cc.group { + panic("group misaligned") + } + + (*o.parent.group)[cc.parentIndex].x = o.group } - - (*o.parent.group)[cc.parentIndex].x = o.group } } @@ -295,18 +316,10 @@ func (ctx *overlayContext) allocCC(cc *closeContext) *closeContext { // src is set in the root closeContext when cloning a vertex. ctx.closeContexts = append(ctx.closeContexts, cc) - // needsCloseInSchedule is used as a boolean. The pointer to the original - // closeContext is just used for reporting purposes. - if cc.needsCloseInSchedule != nil { - o.needsCloseInSchedule = ctx.allocCC(cc.needsCloseInSchedule) - } - // We only explicitly tag dependencies of type ARC. Notifications that // point within the disjunct overlay will be tagged elsewhere. for _, a := range cc.arcs { - if a.kind == ARC { - ctx.allocCC(a.cc) - } + ctx.allocCC(a.dst) } return o @@ -320,10 +333,11 @@ func (ctx *overlayContext) initCloneCC(x *closeContext) { o.src = o.parent.src } + o.depth = x.depth o.conjunctCount = x.conjunctCount o.disjunctCount = x.disjunctCount o.isDef = x.isDef - o.hasEllipsis = x.hasEllipsis + o.isDefOrig = x.isDefOrig o.hasTop = x.hasTop o.hasNonTop = x.hasNonTop o.isClosedOnce = x.isClosedOnce @@ -336,50 +350,36 @@ func (ctx *overlayContext) initCloneCC(x *closeContext) { o.Expr = x.Expr o.Patterns = append(o.Patterns, x.Patterns...) + // needsCloseInSchedule is a separate mechanism to signal nodes that have + // completed that corresponds to the EVAL mechanism. Since we have not + // processed the conjuncts yet, these are inherently initiated outside of + // this conjunct. By now, if a closeContext needs to remain open, other + // counters should have been added. As an example, the parent node of this + // disjunct is still processing. The disjunction will be fully added before + // processing, and thus their will be no direct EVAL dependency. However, + // this disjunct may depend on a NOTIFY that is kept open by an ancestor + // EVAL. + if x.needsCloseInSchedule != nil { + o.needsCloseInSchedule = nil + } + // child and next always point to completed closeContexts. Moreover, only // fields that are immutable, such as Expr, are used. It is therefore not // necessary to use overlays. o.child = x.child if x.child != nil && x.child.overlay != nil { - // TODO: there seem to be situations where this is possible after all. - // See if this is really true, and we should remove this panic, or if - // this underlies a bug of sorts. + // TODO(evalv3): there seem to be situations where this is possible + // after all. See if this is really true, and we should remove this + // panic, or if this underlies a bug of sorts. // panic("unexpected overlay in child") } o.next = x.next if x.next != nil && x.next.overlay != nil { - panic("unexpected overlay in next") - } - - for _, d := range x.dependencies { - if d.decremented { - continue - } - - if d.dependency.overlay == nil { - // This dependency is irrelevant for the current overlay. We can - // eliminate it as long as we decrement the accompanying counter. - if o.conjunctCount < 2 { - // This node can only be relevant if it has at least one other - // dependency. Check that we are not decrementing the counter - // to 0. - // TODO: this currently panics for some tests. Disabling does - // not seem to harm, though. Reconsider whether this is an issue. - // panic("unexpected conjunctCount: must be at least 2") - } - o.conjunctCount-- - continue - } - - dep := d.dependency - if dep.overlay != nil { - dep = dep.overlay - } - o.dependencies = append(o.dependencies, &ccDep{ - dependency: dep, - kind: d.kind, - decremented: false, - }) + // TODO(evalv3): there seem to be situations where this is possible + // after all. See if this is really true, and we should remove this + // panic, or if this underlies a bug of sorts. + // See Issue #3434. + // panic("unexpected overlay in next") } switch p := x.parentConjuncts.(type) { @@ -405,22 +405,99 @@ func (ctx *overlayContext) initCloneCC(x *closeContext) { if o.parentConjuncts == nil { panic("expected parentConjuncts") } +} + +func (ctx *overlayContext) finishDependencies(x *closeContext) { + o := x.overlay for _, a := range x.arcs { // If an arc does not have an overlay, we should not decrement the // dependency counter. We simply remove the dependency in that case. - if a.cc.overlay == nil { - continue + if a.dst.overlay == nil || a.root.overlay == nil { + panic("arcs should always point inwards and thus included in the overlay") } - if a.key.overlay != nil { - a.key = a.key.overlay // TODO: is this necessary? + if a.decremented { + continue } - a.cc = a.cc.overlay + a.root = a.root.overlay // TODO: is this necessary? + a.dst = a.dst.overlay o.arcs = append(o.arcs, a) + + root := a.dst.src.cc() + root.externalDeps = append(root.externalDeps, ccDepRef{ + src: o, + kind: ARC, + index: len(o.arcs) - 1, + }) } - // NOTE: copying externalDeps is hard and seems unnecessary, as it needs to - // be resolved in the base anyway. + for _, a := range x.notify { + // If a notification does not have an overlay, we should not decrement + // the dependency counter. We simply remove the dependency in that case. + // TODO: however, the original closeContext that it point to now will + // never be "filled". We should insert top in this gat or render it as + // "defunct", for instance, so that it will not leave an nondecremented + // counter. + if a.dst.overlay == nil { + for c := a.dst; c != nil; c = c.parent { + c.disjunctCount++ + } + continue + } + if a.decremented { + continue + } + a.dst = a.dst.overlay + o.notify = append(o.notify, a) + + root := a.dst.src.cc() + root.externalDeps = append(root.externalDeps, ccDepRef{ + src: o, + kind: NOTIFY, + index: len(o.notify) - 1, + }) + } + + for _, d := range x.dependencies { + if d.decremented { + continue + } + + if d.kind == DEFER { + o.decDependentNoMatch(ctx.ctx, DEFER, nil) + continue + } + + // Since have not started processing the disjunct yet, all EVAL + // dependencies will have been initiated outside of this disjunct. + if d.kind == EVAL { + o.decDependentNoMatch(ctx.ctx, EVAL, nil) + continue + } + + if d.dependency.overlay == nil { + // This dependency is irrelevant for the current overlay. We can + // eliminate it as long as we decrement the accompanying counter. + if o.conjunctCount < 2 { + // This node can only be relevant if it has at least one other + // dependency. Check that we are not decrementing the counter + // to 0. + // TODO: this currently panics for some tests. Disabling does + // not seem to harm, though. Reconsider whether this is an issue. + // panic("unexpected conjunctCount: must be at least 2") + } + o.conjunctCount-- + continue + } + + dep := d.dependency + dep = dep.overlay + o.dependencies = append(o.dependencies, &ccDep{ + dependency: dep, + kind: d.kind, + decremented: false, + }) + } } func (ctx *overlayContext) cloneScheduler(dst, src *nodeContext) { @@ -431,8 +508,6 @@ func (ctx *overlayContext) cloneScheduler(dst, src *nodeContext) { ds.completed = ss.completed ds.needs = ss.needs ds.provided = ss.provided - ds.frozen = ss.frozen - ds.isFrozen = ss.isFrozen ds.counters = ss.counters ss.blocking = ss.blocking[:0] @@ -461,7 +536,7 @@ func (ctx *overlayContext) cloneScheduler(dst, src *nodeContext) { ds.tasks = append(ds.tasks, t) case taskRUNNING: - if t.run != handleResolver { + if t.run != handleResolver && t.run != handleExpr { // TODO: consider whether this is also necessary for other // types of tasks. break diff --git a/vendor/cuelang.org/go/internal/core/adt/runmode_string.go b/vendor/cuelang.org/go/internal/core/adt/runmode_string.go new file mode 100644 index 0000000000..1cb34d6ab1 --- /dev/null +++ b/vendor/cuelang.org/go/internal/core/adt/runmode_string.go @@ -0,0 +1,27 @@ +// Code generated by "stringer -type=runMode"; DO NOT EDIT. + +package adt + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[ignore-1] + _ = x[attemptOnly-2] + _ = x[yield-3] + _ = x[finalize-4] +} + +const _runMode_name = "ignoreattemptOnlyyieldfinalize" + +var _runMode_index = [...]uint8{0, 6, 17, 22, 30} + +func (i runMode) String() string { + i -= 1 + if i >= runMode(len(_runMode_index)-1) { + return "runMode(" + strconv.FormatInt(int64(i+1), 10) + ")" + } + return _runMode_name[_runMode_index[i]:_runMode_index[i+1]] +} diff --git a/vendor/cuelang.org/go/internal/core/adt/sched.go b/vendor/cuelang.org/go/internal/core/adt/sched.go index 8b0f224ba0..c6d0727cfa 100644 --- a/vendor/cuelang.org/go/internal/core/adt/sched.go +++ b/vendor/cuelang.org/go/internal/core/adt/sched.go @@ -123,6 +123,7 @@ const ( taskWAITING // task is blocked on a property of an arc to hold taskSUCCESS taskFAILED + taskCANCELLED ) type schedState uint8 @@ -175,6 +176,8 @@ func (s schedState) String() string { // runMode indicates how to proceed after a condition could not be met. type runMode uint8 +//go:generate go run golang.org/x/tools/cmd/stringer -type=runMode + const ( // ignore indicates that the new evaluator should not do any processing. // This is mostly used in the transition from old to new evaluator and @@ -195,20 +198,6 @@ const ( finalize ) -func (r runMode) String() string { - switch r { - case ignore: - return "ignore" - case attemptOnly: - return "attemptOnly" - case yield: - return "yield" - case finalize: - return "finalize" - } - return "unknown" -} - // condition is a bit mask of states that a task may depend on. // // There are generally two types of states: states that are met if all tasks @@ -280,6 +269,17 @@ type scheduler struct { func (s *scheduler) clear() { // TODO(perf): free tasks into task pool + // Any tasks blocked on this scheduler are unblocked once the scheduler is cleared. + // Otherwise they might signal a cleared scheduler, which can panic. + // + // TODO(mvdan,mpvl): In principle, all blocks should have been removed when a scheduler + // is cleared. Perhaps this can happen when the scheduler is stopped prematurely. + // For now, this solution seems to work OK. + for _, t := range s.blocking { + t.blockedOn = nil + t.blockCondition = neverKnown + } + *s = scheduler{ ctx: s.ctx, tasks: s.tasks[:0], @@ -369,11 +369,11 @@ func (s *scheduler) process(needs condition, mode runMode) bool { if s.ctx.LogEval > 0 && len(s.tasks) > 0 { if v := s.tasks[0].node.node; v != nil { - c.nest++ c.Logf(v, "START Process %v -- mode: %v", v.Label, mode) + c.nest++ defer func() { - c.Logf(v, "END Process") c.nest-- + c.Logf(v, "END Process") }() } } @@ -394,9 +394,6 @@ processNextTask: } switch { - case t.defunct: - continue - case t.state == taskRUNNING: // TODO: we could store the current referring node that caused // the cycle and then proceed up the stack to mark all tasks @@ -596,7 +593,7 @@ type task struct { // scheduler. blockedOn *scheduler blockCondition condition - blockStack []*task // TODO: use; for error reporting. + // blockStack []*task // TODO: use; for error reporting. err *Bottom @@ -660,6 +657,12 @@ func (s *scheduler) insertTask(t *task) { func runTask(t *task, mode runMode) { if t.defunct { + if t.state != taskCANCELLED { + t.state = taskCANCELLED + if t.id.cc != nil { + t.id.cc.decDependent(t.node.ctx, TASK, nil) + } + } return } t.node.Logf("============ RUNTASK %v %v", t.run.name, t.x) @@ -700,7 +703,10 @@ func runTask(t *task, mode runMode) { defer ctx.popTask() if t.env != nil { id := t.id - id.cc = nil // this is done to avoid struct args from passing fields up. + // This is done to avoid struct args from passing fields up. + // Use [task.updateCI] to get the current CloseInfo with this field + // restored. + id.cc = nil s := ctx.PushConjunct(MakeConjunct(t.env, t.x, id)) defer ctx.PopState(s) } @@ -723,8 +729,9 @@ func runTask(t *task, mode runMode) { } else { t.state = taskFAILED } - t.node.addBottom(t.err) // TODO: replace with something more principled. - + // TODO: do not add both context and task errors. Do something more + // principled. + t.node.addBottom(t.err) if t.id.cc != nil { t.id.cc.decDependent(ctx, TASK, nil) } @@ -733,6 +740,13 @@ func runTask(t *task, mode runMode) { } } +// updateCI stitches back the closeContext that more removed from the CloseInfo +// before in the given CloseInfo. +func (t *task) updateCI(ci CloseInfo) CloseInfo { + ci.cc = t.id.cc + return ci +} + // waitFor blocks task t until the needs for scheduler s are met. func (t *task) waitFor(s *scheduler, needs condition) { if s.meets(needs) { diff --git a/vendor/cuelang.org/go/internal/core/adt/share.go b/vendor/cuelang.org/go/internal/core/adt/share.go index 09071a6c55..be5bd45f14 100644 --- a/vendor/cuelang.org/go/internal/core/adt/share.go +++ b/vendor/cuelang.org/go/internal/core/adt/share.go @@ -45,7 +45,76 @@ func (n *nodeContext) unshare() { // Find another mechanism once we get rid of the old evaluator. n.node.BaseValue = n.origBaseValue - n.scheduleVertexConjuncts(n.shared, v, n.sharedID) + for _, id := range n.sharedIDs { + n.scheduleVertexConjuncts(n.shared, v, id) + } + + n.decSharedIDs() +} + +// finalizeSharing should be called when it is known for sure a node can be +// shared. +func (n *nodeContext) finalizeSharing() { + n.decSharedIDs() + if !n.isShared { + return + } + switch v := n.node.BaseValue.(type) { + case *Vertex: + if n.shareCycleType == NoCycle { + v.Finalize(n.ctx) + } else if !v.isFinal() { + // TODO: ideally we just handle cycles in optional chains directly, + // rather than relying on this mechanism. This requires us to add + // a mechanism to detect that. + n.ctx.toFinalize = append(n.ctx.toFinalize, v) + } + // If state.parent is non-nil, we determined earlier that this Vertex + // is not rooted and that it can safely be shared. Because it is + // not-rooted, though, it will not have a path location, resulting in + // bad error messages, and in some cases dropped errors. To avoid this, + // we reset the parent and label of the Vertex so that its path reflects + // its assigned location. + if v.state != nil && v.state.parent != nil { + v.Parent = v.state.parent + + // TODO: see if this can be removed and why some errors are not + // propagated when removed. + n.isShared = false + } + case *Bottom: + // An error trumps sharing. We can leave it as is. + default: + panic("unreachable") + } +} + +func (n *nodeContext) addShared(id CloseInfo) { + if len(n.sharedIDs) == 0 || n.shareCycleType < id.CycleType { + n.shareCycleType = id.CycleType + } + + // At this point, the node may still be unshared at a later point. For this + // purpose we need to keep the retain count above zero until all conjuncts + // have been processed and it is clear that sharing is possible. Delaying + // such a count should not hurt performance, as a shared node is completed + // anyway. + n.sharedIDs = append(n.sharedIDs, id) + if id.cc != nil { + id.cc.incDependent(n.ctx, SHARED, n.node.cc()) + } +} + +func (n *nodeContext) decSharedIDs() { + if n.shareDecremented { + return + } + n.shareDecremented = true + for _, id := range n.sharedIDs { + if cc := id.cc; cc != nil { + cc.decDependent(n.ctx, SHARED, n.node.cc()) + } + } } func (n *nodeContext) share(c Conjunct, arc *Vertex, id CloseInfo) { @@ -57,16 +126,34 @@ func (n *nodeContext) share(c Conjunct, arc *Vertex, id CloseInfo) { n.node.IsShared = true n.isShared = true n.shared = c - n.sharedID = id + n.addShared(id) + + if arc.IsDetached() && arc.MayAttach() { // TODO: Second check necessary? + // This node can safely be shared. Since it is not rooted, though, it + // does not have a path location. Instead of setting the parent path + // directly, though, we record the prospective parent in the state: as + // the evaluator uses the Parent field during evaluation, setting the + // field directly here can result in incorrect evaluation results. + // Setting the parent in the state instead allows us to defer setting + // Parent until it is safe to do so.. + if s := arc.getState(n.ctx); s != nil { + s.parent = n.node + } + } } func (n *nodeContext) shareIfPossible(c Conjunct, arc *Vertex, id CloseInfo) bool { - // TODO: have an experiment here to enable or disable structure sharing. - // return false if !n.ctx.Sharing { return false } + // We do not allowing sharing if the conjunct has a cycle. Sharing is only + // possible if there is a single conjunct. We want to further evaluate this + // conjunct to force recognition of a structural cycle. + if id.CycleType == IsCyclic && (n.node.nonRooted || n.node.IsDynamic) { + return false + } + if n.noSharing || n.isShared || n.ctx.errs != nil { return false } @@ -83,7 +170,7 @@ func (n *nodeContext) shareIfPossible(c Conjunct, arc *Vertex, id CloseInfo) boo // probably a good idea anyway. // // TODO: come up with a mechanism to allow this case. - if n.node.Closed && !arc.Closed { + if n.node.ClosedRecursive && !arc.ClosedRecursive { return false } @@ -92,13 +179,7 @@ func (n *nodeContext) shareIfPossible(c Conjunct, arc *Vertex, id CloseInfo) boo // result will result in an infinite loop. // // TODO: allow this case. - if n.node.Label.IsLet() { - return false - } - - // If an arc is a computed intermediate result and not part of a CUE output, - // it should not be shared. - if n.node.nonRooted || arc.nonRooted { + if arc.Label.IsLet() { return false } diff --git a/vendor/cuelang.org/go/internal/core/adt/simplify.go b/vendor/cuelang.org/go/internal/core/adt/simplify.go index e1b3833349..d36af819e5 100644 --- a/vendor/cuelang.org/go/internal/core/adt/simplify.go +++ b/vendor/cuelang.org/go/internal/core/adt/simplify.go @@ -15,6 +15,9 @@ package adt import ( + "bytes" + "strings" + "github.com/cockroachdb/apd/v3" "cuelang.org/go/internal" @@ -66,9 +69,60 @@ func SimplifyBounds(ctx *OpContext, k Kind, x, y *BoundValue) Value { } return y + case xCat == -yCat && k == StringKind: + if xCat == -1 { + x, y = y, x + xv, yv = yv, xv + } + + a, aOK := xv.(*String) + b, bOK := yv.(*String) + + if !aOK || !bOK { + break + } + + switch diff := strings.Compare(a.Str, b.Str); diff { + case -1: + case 0: + if x.Op == GreaterEqualOp && y.Op == LessEqualOp { + return ctx.NewString(a.Str) + } + fallthrough + + case 1: + return ctx.NewErrf("incompatible string bounds %v and %v", y, x) + } + + case xCat == -yCat && k == BytesKind: + if xCat == -1 { + x, y = y, x + xv, yv = yv, xv + } + + a, aOK := xv.(*Bytes) + b, bOK := yv.(*Bytes) + + if !aOK || !bOK { + break + } + + switch diff := bytes.Compare(a.B, b.B); diff { + case -1: + case 0: + if x.Op == GreaterEqualOp && y.Op == LessEqualOp { + return ctx.newBytes(a.B) + } + fallthrough + + case 1: + return ctx.NewErrf("incompatible bytes bounds %v and %v", y, x) + } + case xCat == -yCat: if xCat == -1 { x, y = y, x + xv, yv = yv, xv } a, aOK := xv.(*Num) b, bOK := yv.(*Num) @@ -133,28 +187,34 @@ func SimplifyBounds(ctx *OpContext, k Kind, x, y *BoundValue) Value { case diff == 1: if k&FloatKind == 0 { if x.Op == GreaterEqualOp && y.Op == LessThanOp { - return ctx.newNum(&lo, k&NumKind, x, y) + return ctx.newNum(&lo, k&NumberKind, x, y) } if x.Op == GreaterThanOp && y.Op == LessEqualOp { - return ctx.newNum(&hi, k&NumKind, x, y) + return ctx.newNum(&hi, k&NumberKind, x, y) + } + if x.Op == GreaterThanOp && y.Op == LessThanOp { + return ctx.NewErrf("incompatible integer bounds %v and %v", x, y) } } case diff == 2: if k&FloatKind == 0 && x.Op == GreaterThanOp && y.Op == LessThanOp { _, _ = internal.BaseContext.Add(&d, d.SetInt64(1), &lo) - return ctx.newNum(&d, k&NumKind, x, y) - + return ctx.newNum(&d, k&NumberKind, x, y) } case diff == 0 && err == nil: if x.Op == GreaterEqualOp && y.Op == LessEqualOp { - return ctx.newNum(&lo, k&NumKind, x, y) + return ctx.newNum(&lo, k&NumberKind, x, y) } fallthrough case d.Negative: - return ctx.NewErrf("incompatible bounds %v and %v", x, y) + if k == IntKind { + return ctx.NewErrf("incompatible integer bounds %v and %v", y, x) + } else { + return ctx.NewErrf("incompatible number bounds %v and %v", y, x) + } } case x.Op == NotEqualOp: @@ -202,24 +262,31 @@ func test(ctx *OpContext, op Op, a, b Value) bool { // Currently this only checks for pure equality. In the future this can be used // to simplify certain builtin validators analogously to how we simplify bounds // now. -func SimplifyValidator(ctx *OpContext, v, w Validator) Validator { - switch x := v.(type) { +func SimplifyValidator(ctx *OpContext, v, w Conjunct) (c Conjunct, ok bool) { + switch x := v.x.(type) { case *BuiltinValidator: - switch y := w.(type) { + switch y := w.x.(type) { case *BuiltinValidator: if x == y { - return x + return v, true } if x.Builtin != y.Builtin || len(x.Args) != len(y.Args) { - return nil + return c, false } for i, a := range x.Args { - if !Equal(ctx, a, y.Args[i], CheckStructural) { - return nil + b := y.Args[i] + if v, ok := a.(*Vertex); ok { + v.Finalize(ctx) + } + if v, ok := b.(*Vertex); ok { + v.Finalize(ctx) + } + if !Equal(ctx, a, b, CheckStructural) { + return c, false } } - return x + return v, true } } - return nil + return c, false } diff --git a/vendor/cuelang.org/go/internal/core/adt/states.go b/vendor/cuelang.org/go/internal/core/adt/states.go index 09419291e2..56ab1af6ac 100644 --- a/vendor/cuelang.org/go/internal/core/adt/states.go +++ b/vendor/cuelang.org/go/internal/core/adt/states.go @@ -138,7 +138,11 @@ const ( // This is a signal condition that is reached when: // - allFieldsKnown is reached (all expressions have ) // - it is unified with an associative list type - listTypeKnown + // + // TODO(assoclist): this is set to 0 below: This mode is only needed for + // associative lists and is not yet used. We should use this again and fix + // any performance issues when we implement associative lists. + // listTypeKnown // fieldConjunctsKnown means that all the conjuncts of all fields are // known. @@ -224,6 +228,9 @@ const ( // concreteKnown means that we know whether a value is concrete or not. // At the moment this is equal to 'scalarKnown'. concreteKnown = scalarKnown + + // TODO(assoclist): see comment above. + listTypeKnown condition = 0 ) // schedConfig configures a taskContext with the states needed for the @@ -243,8 +250,9 @@ func stateCompletions(s *scheduler) condition { s.node.Logf("=== stateCompletions: %v %v", v.Label, s.completed) if x.meets(allAncestorsProcessed) { x |= conditionsUsingCounters &^ s.provided - // If we have a pending arc, a sub arc may still cause the arc to - // become not pending. For instance, if 'a' is pending in the following + // If we have a pending or constraint arc, a sub arc may still cause the + // arc to become a member. For instance, if 'a' is pending in the + // following // if x != _!_ { // a: b: 1 // } @@ -294,6 +302,15 @@ func (v *Vertex) allChildConjunctsKnown() bool { return true } + if v.Status() == finalized { + // This can happen, for instance, if this is called on a parent of a + // rooted node that is marked as a parent for a dynamic node. + // In practice this should be handled by the caller, but we add this + // as an extra safeguard. + // TODO: remove this check at some point. + return true + } + return v.state.meets(fieldConjunctsKnown | allAncestorsProcessed) } diff --git a/vendor/cuelang.org/go/internal/core/adt/tasks.go b/vendor/cuelang.org/go/internal/core/adt/tasks.go index 00412de8d9..671169b8fd 100644 --- a/vendor/cuelang.org/go/internal/core/adt/tasks.go +++ b/vendor/cuelang.org/go/internal/core/adt/tasks.go @@ -85,8 +85,13 @@ func processExpr(ctx *OpContext, t *task, mode runMode) { x := t.x.(Expr) state := combineMode(concreteKnown, mode) - v := ctx.evalState(x, state) - t.node.insertValueConjunct(t.env, v, t.id) + v, ci := ctx.evalStateCI(x, state) + if ci.CycleType == IsCyclic && t.node.node.IsPatternConstraint { + // This is an optional cycle that we will ignore. + return + } + ci = t.updateCI(ci) + t.node.insertValueConjunct(t.env, v, ci) } func processResolver(ctx *OpContext, t *task, mode runMode) { @@ -97,7 +102,8 @@ func processResolver(ctx *OpContext, t *task, mode runMode) { // would be a pretty significant rework, though. arc := r.resolve(ctx, oldOnly(0)) - if arc == nil { + // TODO: ensure that resolve always returns one of these two. + if arc == nil || arc == emptyNode { // TODO: yield instead? return } @@ -107,10 +113,15 @@ func processResolver(ctx *OpContext, t *task, mode runMode) { // TODO: consider moving after markCycle or removing. d := arc.DerefDisjunct() + ci := t.updateCI(ctx.ci) + // A reference that points to itself indicates equality. In that case // we are done computing and we can return the arc as is. - ci, skip := t.node.markCycle(d, t.env, r, t.id) + ci, skip := t.node.detectCycleV3(d, t.env, r, ci) if skip { + // Either we have a structure cycle or we are unifying with another + // conjunct. In either case, we are no longer structure sharing here. + t.node.unshare() return } @@ -118,6 +129,13 @@ func processResolver(ctx *OpContext, t *task, mode runMode) { return } + // TODO: consider moving this to within if arc.nonRooted below. + if b, ok := d.BaseValue.(*Bottom); ok && b.Code == StructuralCycleError { + // TODO: ensure better positioning information. + ctx.AddBottom(b) + return + } + c := MakeConjunct(t.env, t.x, ci) t.node.scheduleVertexConjuncts(c, arc, ci) } @@ -135,6 +153,7 @@ func processDynamic(ctx *OpContext, t *task, mode runMode) { if v.Concreteness() != Concrete { n.addBottom(&Bottom{ Code: IncompleteError, + Node: n.node, Err: ctx.NewPosf(pos(field.Key), "key value of dynamic field must be concrete, found %v", v), }) @@ -148,9 +167,14 @@ func processDynamic(ctx *OpContext, t *task, mode runMode) { return } - c := MakeConjunct(t.env, field, t.id) + // Do not update the CloseInfo, as we are passing the field value + // unevaluated. + ci := t.id + + c := MakeConjunct(t.env, field, ci) + // TODO(evalv3): this does not seem to be necessary and even treacherous. c.CloseInfo.cc = nil - n.insertArc(f, field.ArcType, c, t.id, true) + n.insertArc(f, field.ArcType, c, ci, true) } func processPatternConstraint(ctx *OpContext, t *task, mode runMode) { @@ -165,7 +189,11 @@ func processPatternConstraint(ctx *OpContext, t *task, mode runMode) { return } - n.insertPattern(v, MakeConjunct(t.env, t.x, t.id)) + // Do not update the CloseInfo, as we are passing the constraint value + // unevaluated. + ci := t.id + + n.insertPattern(v, MakeConjunct(t.env, t.x, ci)) } func processComprehension(ctx *OpContext, t *task, mode runMode) { @@ -200,7 +228,7 @@ func processListLit(c *OpContext, t *task, mode runMode) { l := t.x.(*ListLit) - n.updateCyclicStatus(t.id) + n.updateCyclicStatusV3(t.id) var ellipsis Node @@ -215,8 +243,10 @@ func processListLit(c *OpContext, t *task, mode runMode) { label, err := MakeLabel(x.Source(), index, IntLabel) n.addErr(err) index++ - c := MakeConjunct(e, x.Value, t.id) - n.insertArc(label, ArcMember, c, t.id, true) + id := t.id + // id.setOptional(t.node) + c := MakeConjunct(e, x.Value, id) + n.insertArc(label, ArcMember, c, id, true) }) hasComprehension = true if err != nil { @@ -225,6 +255,9 @@ func processListLit(c *OpContext, t *task, mode runMode) { } case *Ellipsis: + // TODO(openlist): this will work once we have the same closedness + // semantics for lists as for structs. + // t.id.cc.isTotal = true if j != len(l.Elems)-1 { n.addErr(c.Newf("ellipsis must be last element in list")) return @@ -235,7 +268,10 @@ func processListLit(c *OpContext, t *task, mode runMode) { elem = &Top{} } - c := MakeConjunct(t.env, elem, t.id) + id := t.id + id.setOptionalV3(t.node) + + c := MakeConjunct(t.env, elem, id) pat := &BoundValue{ Op: GreaterEqualOp, Value: n.ctx.NewInt64(index, x), @@ -332,7 +368,7 @@ func (n *nodeContext) updateListType(list Expr, id CloseInfo, isClosed bool, ell m = &ListMarker{ IsOpen: true, } - n.node.setValue(n.ctx, conjuncts, m) + n.setBaseValue(m) } m.IsOpen = m.IsOpen && !isClosed diff --git a/vendor/cuelang.org/go/internal/core/adt/unify.go b/vendor/cuelang.org/go/internal/core/adt/unify.go index 5954630ff0..c145948bd7 100644 --- a/vendor/cuelang.org/go/internal/core/adt/unify.go +++ b/vendor/cuelang.org/go/internal/core/adt/unify.go @@ -20,6 +20,7 @@ import ( "cuelang.org/go/cue/token" ) +// TODO(mpvl): perhaps conjunctsProcessed is a better name for this. func (v *Vertex) isInitialized() bool { return v.status == finalized || (v.state != nil && v.state.isInitialized) } @@ -76,12 +77,12 @@ func (n *nodeContext) initBare() { n.blockOn(scalarKnown | listTypeKnown | arcTypeKnown) if v.Label.IsDef() { - v.Closed = true + v.ClosedRecursive = true } if v.Parent != nil { - if v.Parent.Closed { - v.Closed = true + if v.Parent.ClosedRecursive { + v.ClosedRecursive = true } } } @@ -118,13 +119,27 @@ func (n *nodeContext) scheduleConjuncts() { root.decDependent(ctx, INIT, nil) } +// TODO(evalv3): consider not returning a result at all. func (v *Vertex) unify(c *OpContext, needs condition, mode runMode) bool { if c.LogEval > 0 { - c.nest++ c.Logf(v, "Unify %v", fmt.Sprintf("%p", v)) + c.nest++ defer func() { - c.Logf(v, "END Unify") c.nest-- + c.Logf(v, "END Unify") + }() + } + + if c.evalDepth == 0 { + defer func() { + // This loop processes nodes that need to be evaluated, but should be + // evaluated outside of the stack to avoid structural cycle detection. + // See comment at toFinalize. + a := c.toFinalize + c.toFinalize = c.toFinalize[:0] + for _, x := range a { + x.Finalize(c) + } }() } @@ -132,14 +147,21 @@ func (v *Vertex) unify(c *OpContext, needs condition, mode runMode) bool { return false } + // Note that the state of a node can be removed before the node is. + // This happens with the close builtin, for instance. + // See TestFromAPI in pkg export. + // TODO(evalv3): find something more principled. + if v.state == nil && v.cc() != nil && v.cc().conjunctCount == 0 { + v.status = finalized + return true + } + n := v.getState(c) if n == nil { return true // already completed } defer n.free() - defer n.unmarkDepth(n.markDepth()) - // Typically a node processes all conjuncts before processing its fields. // So this condition is very likely to trigger. If for some reason the // parent has not been processed yet, we could attempt to process more @@ -151,11 +173,46 @@ func (v *Vertex) unify(c *OpContext, needs condition, mode runMode) bool { // Note that if mode is final, we will guarantee that the conditions for // this if clause are met down the line. So we assume this is already the // case and set the signal accordingly if so. - if v.Label.IsLet() || v.IsDynamic || v.Parent.allChildConjunctsKnown() || mode == finalize { + if !v.Rooted() || v.Parent.allChildConjunctsKnown() || mode == finalize { n.signal(allAncestorsProcessed) } nodeOnlyNeeds := needs &^ (subFieldsProcessed) + + if v.BaseValue == nil { + v.BaseValue = cycle + } + n.updateScalar() + if nodeOnlyNeeds == (scalarKnown|arcTypeKnown) && n.meets(nodeOnlyNeeds) { + return true + } + + // Detect a self-reference: if this node is under evaluation at the same + // evaluation depth, this means that we have a self-reference, possibly + // through an expression. As long as there is no request to process arcs or + // finalize the value, we can and should stop processing here to avoid + // spurious cycles. + if v.status == evaluating && + v.state.evalDepth == c.evalDepth && + needs&fieldSetKnown == 0 && + mode != finalize { + return false + } + + v.status = evaluating + + defer n.unmarkDepth(n.markDepth()) + + if n.node.ArcType == ArcPending { + // forcefully do an early recursive evaluation to decide the state + // of the arc. See https://cuelang.org/issue/3621. + n.process(nodeOnlyNeeds, attemptOnly) + if n.node.ArcType == ArcPending { + for _, a := range n.node.Arcs { + a.unify(c, needs, attemptOnly) + } + } + } n.process(nodeOnlyNeeds, mode) defer c.PopArc(c.PushArc(v)) @@ -163,7 +220,7 @@ func (v *Vertex) unify(c *OpContext, needs condition, mode runMode) bool { w := v.DerefDisjunct() if w != v { // Should resolve with dereference. - v.Closed = w.Closed + v.ClosedRecursive = w.ClosedRecursive v.status = w.status v.ChildErrors = CombineErrors(nil, v.ChildErrors, w.ChildErrors) v.Arcs = nil @@ -208,6 +265,16 @@ func (v *Vertex) unify(c *OpContext, needs condition, mode runMode) bool { } } + if v, ok := n.node.BaseValue.(*Vertex); ok && n.shareCycleType == NoCycle { + if n.ctx.hasDepthCycle(v) { + n.reportCycleError() + return true + } + // We unify here to proactively detect cycles. We do not need to, + // nor should we, if have have already found one. + v.unify(n.ctx, needs, mode) + } + // At this point, no more conjuncts will be added, so we could decrement // the notification counters. @@ -216,12 +283,9 @@ func (v *Vertex) unify(c *OpContext, needs condition, mode runMode) bool { // done case needs&subFieldsProcessed != 0: - if DebugSort > 0 { - DebugSortArcs(n.ctx, n.node) - } - switch { - case assertStructuralCycle(n): + case assertStructuralCycleV3(n): + n.breakIncomingDeps(mode) // TODO: consider bailing on error if n.errs != nil. case n.completeAllArcs(needs, mode): } @@ -251,7 +315,7 @@ func (v *Vertex) unify(c *OpContext, needs condition, mode runMode) bool { } case needs&fieldSetKnown != 0: - n.evalArcTypes() + n.evalArcTypes(mode) } if err := n.getErr(); err != nil { @@ -259,7 +323,7 @@ func (v *Vertex) unify(c *OpContext, needs condition, mode runMode) bool { if b := n.node.Bottom(); b != nil { err = CombineErrors(nil, b, err) } - n.node.BaseValue = err + n.setBaseValue(err) } if mode == attemptOnly { @@ -280,18 +344,22 @@ func (v *Vertex) unify(c *OpContext, needs condition, mode runMode) bool { v.ChildErrors = nil v.Arcs = nil - result := w.unify(c, needs, mode) - // Set control fields that are referenced without dereferencing. - if w.Closed { - v.Closed = true + if w.ClosedRecursive { + v.ClosedRecursive = true } + // NOTE: setting ClosedNonRecursive is not necessary, as it is + // handled by scheduleValue. if w.HasEllipsis { v.HasEllipsis = true } v.status = w.status - return result + // Ensure that shared nodes comply to the same requirements as we + // need for the current node. + w.unify(c, needs, mode) + + return true } // TODO: adding this is wrong, but it should not cause the snippet below @@ -309,25 +377,51 @@ func (v *Vertex) unify(c *OpContext, needs condition, mode runMode) bool { // validationCompleted if n.completed&(subFieldsProcessed) != 0 { - n.node.HasEllipsis = n.node.cc.hasEllipsis - - n.node.updateStatus(finalized) + n.node.HasEllipsis = n.node.cc().isTotal - defer n.unmarkOptional(n.markOptional()) + // The next piece of code used to address the following case + // (order matters) + // + // c1: c: [string]: f2 + // f2: c1 + // Also: cycle/issue990 + // + // However, with recent changes, it no longer matters. Simultaneously, + // this causes a hang in the following case: + // + // _self: x: [...and(x)] + // _self + // x: [1] + // + // For this reason we disable it now. It may be the case that we need + // to enable it for computing disjunctions. + // + n.incDepth() + defer n.decDepth() - // The next piece of code addresses the following case. - // order matters - // c1: c: [string]: f2 - // f2: c1 - // Also: cycle/issue990 if pc := n.node.PatternConstraints; pc != nil { for _, c := range pc.Pairs { - c.Constraint.Finalize(n.ctx) + c.Constraint.unify(n.ctx, allKnown, attemptOnly) } } + n.node.updateStatus(finalized) + + defer n.unmarkOptional(n.markOptional()) + if DebugDeps { - RecordDebugGraph(n.ctx, n.node, "Finalize") + switch n.node.BaseValue.(type) { + case *Disjunction: + // If we have a disjunction, its individual disjuncts will + // already have been checked. The node itself will likely have + // spurious results, as it will contain unclosed holes. + + case *Vertex: + // No need to check dereferenced results. + + default: + RecordDebugGraph(n.ctx, n.node, "Finalize") + } } } @@ -373,13 +467,15 @@ func (n *nodeContext) completeNodeTasks(mode runMode) { }() } - if p := v.Parent; p != nil && p.state != nil { - if !v.IsDynamic && n.completed&allAncestorsProcessed == 0 { - p.state.completeNodeTasks(mode) + if !v.Label.IsLet() { + if p := v.Parent; p != nil && p.state != nil { + if !v.IsDynamic && n.completed&allAncestorsProcessed == 0 { + p.state.completeNodeTasks(mode) + } } } - if v.IsDynamic || v.Parent.allChildConjunctsKnown() { + if v.IsDynamic || v.Label.IsLet() || v.Parent.allChildConjunctsKnown() { n.signal(allAncestorsProcessed) } @@ -391,22 +487,7 @@ func (n *nodeContext) completeNodeTasks(mode runMode) { n.updateScalar() } - // Check: - // - parents (done) - // - incoming notifications - // - pending arcs (or incoming COMPS) - // TODO: replace with something more principled that does not piggyback on - // debug information. - for _, r := range v.cc.externalDeps { - src := r.src - a := &src.arcs[r.index] - if a.decremented || a.kind != NOTIFY { - continue - } - if n := src.src.getState(n.ctx); n != nil { - n.completeNodeTasks(mode) - } - } + n.breakIncomingNotifications(mode) // As long as ancestors are not processed, it is still possible for // conjuncts to be inserted. Until that time, it is not okay to decrement @@ -425,37 +506,18 @@ func (n *nodeContext) completeNodeTasks(mode runMode) { cc.decDependent(n.ctx, ROOT, nil) // REF(decrement:nodeDone) } - - return } func (n *nodeContext) updateScalar() { // Set BaseValue to scalar, but only if it was not set before. Most notably, // errors should not be discarded. if n.scalar != nil && (!n.node.IsErr() || isCyclePlaceholder(n.node.BaseValue)) { - n.node.BaseValue = n.scalar + n.setBaseValue(n.scalar) n.signal(scalarKnown) } } func (n *nodeContext) completeAllArcs(needs condition, mode runMode) bool { - if n.node.status == evaluatingArcs { - // NOTE: this was an "incomplete" error pre v0.6. If this is a problem - // we could make this a CycleError. Technically, this may be correct, - // as it is possible to make the values exactly as the inserted - // values. It seems more user friendly to just disallow this, though. - // TODO: make uniform error messages - // see compbottom2.cue: - n.ctx.addErrf(CycleError, pos(n.node), "mutual dependency") - n.node.IsCyclic = true - // Consider using this, although not all - // mutual dependencies are irrecoverable. - // n.reportCycleError() - } - - // TODO: remove the use of updateStatus as a cycle detection mechanism. - n.node.updateStatus(evaluatingArcs) - if n.underlying != nil { // References within the disjunct may end up referencing the layer that // this node overlays. Also for these nodes we want to be able to detect @@ -475,30 +537,17 @@ func (n *nodeContext) completeAllArcs(needs condition, mode runMode) bool { // Investigate how to work around this. n.completeNodeTasks(finalize) - for _, r := range n.node.cc.externalDeps { - src := r.src - a := &src.arcs[r.index] - if a.decremented { - continue - } - a.decremented = true - - // FIXME: we should be careful to not evaluate parent nodes if we - // are inside a disjunction, or at least ensure that there are no - // disjunction values leaked into non-disjunction nodes through - // evaluating externalDeps. - src.src.unify(n.ctx, needTasksDone, attemptOnly) - a.cc.decDependent(n.ctx, a.kind, src) // REF(arcs) - } + n.breakIncomingDeps(mode) n.incDepth() + defer n.decDepth() // XXX(0.7): only set success if needs complete arcs. success := true - // Visit arcs recursively to validate and compute error. - for n.arcPos < len(n.node.Arcs) { - a := n.node.Arcs[n.arcPos] - n.arcPos++ + // Visit arcs recursively to validate and compute error. Use index instead + // of range in case the Arcs grows during processing. + for arcPos := 0; arcPos < len(n.node.Arcs); arcPos++ { + a := n.node.Arcs[arcPos] if !a.unify(n.ctx, needs, mode) { success = false @@ -515,21 +564,11 @@ func (n *nodeContext) completeAllArcs(needs condition, mode runMode) bool { continue } - // Errors are allowed in let fields. Handle errors and failure to - // complete accordingly. - if !a.Label.IsLet() && a.ArcType <= ArcRequired { - a := a.DerefValue() - if err := a.Bottom(); err != nil { - n.node.AddChildError(err) - } - success = true // other arcs are irrelevant - } - // TODO: harmonize this error with "cannot combine" switch { case a.ArcType > ArcRequired, !a.Label.IsString(): case n.kind&StructKind == 0: - if !n.node.IsErr() { + if !n.node.IsErr() && !a.IsErr() { n.reportFieldMismatch(pos(a.Value()), nil, a.Label, n.node.Value()) } // case !wasVoid: @@ -551,8 +590,6 @@ func (n *nodeContext) completeAllArcs(needs condition, mode runMode) bool { } } - n.decDepth() - k := 0 for _, a := range n.node.Arcs { if a.ArcType != ArcNotPresent { @@ -562,6 +599,49 @@ func (n *nodeContext) completeAllArcs(needs condition, mode runMode) bool { } n.node.Arcs = n.node.Arcs[:k] + for _, a := range n.node.Arcs { + // Errors are allowed in let fields. Handle errors and failure to + // complete accordingly. + if !a.Label.IsLet() && a.ArcType <= ArcRequired { + a := a.DerefValue() + if err := a.Bottom(); err != nil { + n.AddChildError(err) + } + success = true // other arcs are irrelevant + } + } + + // TODO: perhaps this code can go once we have builtins for comparing to + // bottom. + for _, c := range n.postChecks { + ctx := n.ctx + f := ctx.PushState(c.env, c.expr.Source()) + + v := ctx.evalState(c.expr, oldOnly(finalized)) + v, _ = ctx.getDefault(v) + v = Unwrap(v) + + switch _, isError := v.(*Bottom); { + case isError == c.expectError: + default: + n.node.AddErr(ctx, &Bottom{ + Src: c.expr.Source(), + Code: CycleError, + Node: n.node, + Err: ctx.NewPosf(pos(c.expr), + "circular dependency in evaluation of conditionals: %v changed after evaluation", + ctx.Str(c.expr)), + }) + } + + ctx.PopState(f) + } + + // This should be called after all arcs have been processed, because + // whether sharing is possible or not may depend on how arcs with type + // ArcPending will resolve. + n.finalizeSharing() + // Strip struct literals that were not initialized and are not part // of the output. // @@ -590,12 +670,12 @@ func (n *nodeContext) completeAllArcs(needs condition, mode runMode) bool { return success } -func (n *nodeContext) evalArcTypes() { +func (n *nodeContext) evalArcTypes(mode runMode) { for _, a := range n.node.Arcs { if a.ArcType != ArcPending { continue } - a.unify(n.ctx, arcTypeKnown, yield) + a.unify(n.ctx, arcTypeKnown, mode) // Ensure the arc is processed up to the desired level if a.ArcType == ArcPending { // TODO: cancel tasks? @@ -604,6 +684,13 @@ func (n *nodeContext) evalArcTypes() { } } +func root(v *Vertex) *Vertex { + for v.Parent != nil { + v = v.Parent + } + return v +} + func (v *Vertex) lookup(c *OpContext, pos token.Pos, f Feature, flags combinedFlags) *Vertex { task := c.current() needs := flags.conditions() @@ -620,10 +707,19 @@ func (v *Vertex) lookup(c *OpContext, pos token.Pos, f Feature, flags combinedFl // proceed with partial data, in which case a "pending" arc will be // created to be completed later. - // Report error for now. + // Propagate error if the error is from a different package. This + // compensates for the fact that we do not fully evaluate the package. if state.hasErr() { - c.AddBottom(state.getErr()) + err := state.getErr() + if err != nil && err.Node != nil && root(err.Node) != root(v) { + c.AddBottom(err) + } } + + // A lookup counts as new structure. See the commend in Section + // "Lookups in inline cycles" in cycle.go. + state.hasNonCycle = true + // TODO: ideally this should not be run at this point. Consider under // which circumstances this is still necessary, and at least ensure // this will not be run if node v currently has a running task. @@ -681,7 +777,7 @@ func (v *Vertex) lookup(c *OpContext, pos token.Pos, f Feature, flags combinedFl break } } - arcState.completeNodeTasks(attemptOnly) + arcState.completeNodeTasks(yield) // Child nodes, if pending and derived from a comprehension, may // still cause this arc to become not pending. @@ -695,11 +791,18 @@ func (v *Vertex) lookup(c *OpContext, pos token.Pos, f Feature, flags combinedFl switch runMode { case ignore, attemptOnly: + // TODO(cycle): ideally, we should be able to require that the + // arcType be known at this point, but that does not seem to work. + // Revisit once we have the structural cycle detection in place. + // TODO: should we avoid notifying ArcPending vertices here? if task != nil { arcState.addNotify2(task.node.node, task.id) } - return arcReturn + if arc.ArcType == ArcPending { + return arcReturn + } + goto handleArcType case yield: arcState.process(needs, yield) @@ -712,14 +815,25 @@ func (v *Vertex) lookup(c *OpContext, pos token.Pos, f Feature, flags combinedFl } } +handleArcType: switch arc.ArcType { - case ArcMember: + case ArcMember, ArcRequired: return arcReturn - case ArcOptional, ArcRequired: + case ArcOptional: + // Technically, this failure also applies to required fields. We assume + // however, that if a reference field that is made regular will already + // result in an error, so that piling up another error is not strictly + // necessary. Note that the spec allows for eliding an error if it is + // guaranteed another error is generated elsewhere. This does not + // properly cover the case where a reference is made directly within the + // definition, but this is fine for the purpose it serves. + // TODO(refRequired): revisit whether referencing required fields should + // fail. label := f.SelectorString(c.Runtime) b := &Bottom{ Code: IncompleteError, + Node: v, Err: c.NewPosf(pos, "cannot reference optional field: %s", label), } diff --git a/vendor/cuelang.org/go/internal/core/adt/vertexstatus_string.go b/vendor/cuelang.org/go/internal/core/adt/vertexstatus_string.go new file mode 100644 index 0000000000..789f0883bb --- /dev/null +++ b/vendor/cuelang.org/go/internal/core/adt/vertexstatus_string.go @@ -0,0 +1,28 @@ +// Code generated by "stringer -type=vertexStatus"; DO NOT EDIT. + +package adt + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[unprocessed-0] + _ = x[evaluating-1] + _ = x[partial-2] + _ = x[conjuncts-3] + _ = x[evaluatingArcs-4] + _ = x[finalized-5] +} + +const _vertexStatus_name = "unprocessedevaluatingpartialconjunctsevaluatingArcsfinalized" + +var _vertexStatus_index = [...]uint8{0, 11, 21, 28, 37, 51, 60} + +func (i vertexStatus) String() string { + if i < 0 || i >= vertexStatus(len(_vertexStatus_index)-1) { + return "vertexStatus(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _vertexStatus_name[_vertexStatus_index[i]:_vertexStatus_index[i+1]] +} diff --git a/vendor/cuelang.org/go/internal/core/compile/builtin.go b/vendor/cuelang.org/go/internal/core/compile/builtin.go index 4178b57a71..79e5bbca47 100644 --- a/vendor/cuelang.org/go/internal/core/compile/builtin.go +++ b/vendor/cuelang.org/go/internal/core/compile/builtin.go @@ -16,6 +16,7 @@ package compile import ( "cuelang.org/go/cue/errors" + "cuelang.org/go/internal" "cuelang.org/go/internal/core/adt" ) @@ -24,10 +25,10 @@ import ( const supportedByLen = adt.StructKind | adt.BytesKind | adt.StringKind | adt.ListKind var ( - stringParam = adt.Param{Value: &adt.BasicType{K: adt.StringKind}} structParam = adt.Param{Value: &adt.BasicType{K: adt.StructKind}} listParam = adt.Param{Value: &adt.BasicType{K: adt.ListKind}} intParam = adt.Param{Value: &adt.BasicType{K: adt.IntKind}} + topParam = adt.Param{Value: &adt.BasicType{K: adt.TopKind}} ) var lenBuiltin = &adt.Builtin{ @@ -86,13 +87,21 @@ var closeBuiltin = &adt.Builtin{ if !ok { return c.NewErrf("struct argument must be concrete") } - if m, ok := s.BaseValue.(*adt.StructMarker); ok && m.NeedClose { - return s + var v *adt.Vertex + if c.Version == internal.DevVersion { + // TODO(evalv3) this is a rather convoluted and inefficient way to + // accomplish signaling vertex should be closed. In most cases, it + // would suffice to set IsClosed in the CloseInfo. However, that + // does not cover all code paths. Consider simplifying this. + v = c.Wrap(s, c.CloseInfo()) + v.ClosedNonRecursive = true + } else { + if m, ok := s.BaseValue.(*adt.StructMarker); ok && m.NeedClose { + return s + } + v = s.Clone() + v.BaseValue = &adt.StructMarker{NeedClose: true} } - v := s.Clone() - // TODO(perf): do not copy the arc, but rather find a way to mark the - // calling nodeContext. - v.BaseValue = &adt.StructMarker{NeedClose: true} return v }, } @@ -101,8 +110,10 @@ var andBuiltin = &adt.Builtin{ Name: "and", Params: []adt.Param{listParam}, Result: adt.IntKind, - Func: func(c *adt.OpContext, args []adt.Value) adt.Expr { - list := c.RawElems(args[0]) + RawFunc: func(c *adt.OpContext, args []adt.Expr) adt.Value { + // Pass through the cycle information from evaluating the first argument. + v := c.EvaluateKeepState(args[0]) + list := c.RawElems(v) if len(list) == 0 { return &adt.Top{} } @@ -115,9 +126,10 @@ var andBuiltin = &adt.Builtin{ } var orBuiltin = &adt.Builtin{ - Name: "or", - Params: []adt.Param{listParam}, - Result: adt.IntKind, + Name: "or", + Params: []adt.Param{listParam}, + Result: adt.IntKind, + NonConcrete: true, Func: func(c *adt.OpContext, args []adt.Value) adt.Expr { d := []adt.Disjunct{} for _, c := range c.RawElems(args[0]) { @@ -133,7 +145,8 @@ var orBuiltin = &adt.Builtin{ // status if the source is open. return &adt.Bottom{ Code: adt.IncompleteError, - Err: errors.Newf(c.Pos(), "empty list in call to or"), + // TODO: get and set Vertex + Err: errors.Newf(c.Pos(), "empty list in call to or"), } } v := &adt.Vertex{} diff --git a/vendor/cuelang.org/go/internal/core/compile/compile.go b/vendor/cuelang.org/go/internal/core/compile/compile.go index f870b3ec05..ca5825616b 100644 --- a/vendor/cuelang.org/go/internal/core/compile/compile.go +++ b/vendor/cuelang.org/go/internal/core/compile/compile.go @@ -275,7 +275,7 @@ func (c *compiler) compileFiles(a []*ast.File) *adt.Vertex { // Or value? // - anything in an anonymous file // for _, f := range a { - if p := internal.GetPackageInfo(f); p.IsAnonymous() { + if f.PackageName() == "" { continue } for _, d := range f.Decls { @@ -305,7 +305,7 @@ func (c *compiler) compileFiles(a []*ast.File) *adt.Vertex { // Or value? c.pushScope(nil, 0, file) // File scope v := &adt.StructLit{Src: file} c.addDecls(v, file.Decls) - res.Conjuncts = append(res.Conjuncts, adt.MakeRootConjunct(env, v)) + res.InsertConjunct(adt.MakeRootConjunct(env, v)) c.popScope() } @@ -697,6 +697,10 @@ func (c *compiler) decl(d ast.Decl) adt.Decl { return c.comprehension(x, false) case *ast.EmbedDecl: // Deprecated + for _, c := range ast.Comments(x.Expr) { + ast.AddComment(x, c) + } + ast.SetComments(x.Expr, x.Comments()) return c.expr(x.Expr) case ast.Expr: @@ -1066,7 +1070,7 @@ func (c *compiler) parse(l *ast.BasicLit) (n adt.Expr) { case token.STRING: info, nStart, _, err := literal.ParseQuotes(s, s) if err != nil { - return c.errf(l, err.Error()) + return c.errf(l, "%s", err.Error()) } s := s[nStart:] return parseString(c, l, info, s) diff --git a/vendor/cuelang.org/go/internal/core/compile/predeclared.go b/vendor/cuelang.org/go/internal/core/compile/predeclared.go index 6345147ac9..ec2fceb347 100644 --- a/vendor/cuelang.org/go/internal/core/compile/predeclared.go +++ b/vendor/cuelang.org/go/internal/core/compile/predeclared.go @@ -38,12 +38,16 @@ func predeclared(n *ast.Ident) adt.Expr { case "float", "__float": return &adt.BasicType{Src: n, K: adt.FloatKind} case "number", "__number": - return &adt.BasicType{Src: n, K: adt.NumKind} + return &adt.BasicType{Src: n, K: adt.NumberKind} case "len", "__len": return lenBuiltin case "close", "__close": return closeBuiltin + case "matchIf", "__matchIf": + return matchIfBuiltin + case "matchN", "__matchN": + return matchNBuiltin case "and", "__and": return andBuiltin case "or", "__or": @@ -56,6 +60,9 @@ func predeclared(n *ast.Ident) adt.Expr { return quoBuiltin case "rem", "__rem": return remBuiltin + + case "__no_sharing": + return adt.NoShareSentinel } if r, ok := predefinedRanges[n.Name]; ok { @@ -136,8 +143,8 @@ func mkIntRange(a, b string) adt.Expr { } func mkFloatRange(a, b string) adt.Expr { - from := newBound(adt.GreaterEqualOp, adt.NumKind, parseFloat(a)) - to := newBound(adt.LessEqualOp, adt.NumKind, parseFloat(b)) + from := newBound(adt.GreaterEqualOp, adt.NumberKind, parseFloat(a)) + to := newBound(adt.LessEqualOp, adt.NumberKind, parseFloat(b)) src := ast.NewBinExpr(token.AND, from.Src, to.Src) return &adt.Conjunction{Src: src, Values: []adt.Value{from, to}} } diff --git a/vendor/cuelang.org/go/internal/core/compile/validator.go b/vendor/cuelang.org/go/internal/core/compile/validator.go new file mode 100644 index 0000000000..de3633e7d0 --- /dev/null +++ b/vendor/cuelang.org/go/internal/core/compile/validator.go @@ -0,0 +1,177 @@ +// Copyright 2024 CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package compile + +// This file contains validator and other non-monotonic builtins. + +import ( + "cuelang.org/go/internal/core/adt" + "cuelang.org/go/internal/core/validate" +) + +// matchN is a validator that checks that the number of schemas in the given +// list that unify with "self" matches the number passed as the first argument +// of the validator. Note that this number may itself be a number constraint +// and does not have to be a concrete number. +var matchNBuiltin = &adt.Builtin{ + Name: "matchN", + Params: []adt.Param{topParam, intParam, listParam}, // varargs + Result: adt.BoolKind, + NonConcrete: true, + Func: func(c *adt.OpContext, args []adt.Value) adt.Expr { + if !c.IsValidator { + return c.NewErrf("matchN is a validator and should not be used as a function") + } + + self := finalizeSelf(c, args[0]) + if err := bottom(c, self); err != nil { + return &adt.Bool{B: false} + } + + constraints := c.Elems(args[2]) + + var count, possibleCount int64 + for _, check := range constraints { + v := unifyValidator(c, self, check) + if err := validate.Validate(c, v, finalCfg); err == nil { + // TODO: is it always true that the lack of an error signifies + // success? + count++ + } else { + if err.IsIncomplete() { + possibleCount++ + } + } + } + + bound := args[1] + // TODO: consider a mode to require "all" to pass, for instance by + // supporting the value null or "all". + + b := checkNum(c, bound, count, count+possibleCount) + if b != nil { + return b + } + return &adt.Bool{B: true} + }, +} + +// matchIf is a validator that checks that if the first argument unifies with +// self, the second argument also unifies with self, otherwise the third +// argument unifies with self. +// The same finalization heuristics are applied to self as are applied +// in matchN. +var matchIfBuiltin = &adt.Builtin{ + Name: "matchIf", + Params: []adt.Param{topParam, topParam, topParam, topParam}, + Result: adt.BoolKind, + NonConcrete: true, + Func: func(c *adt.OpContext, args []adt.Value) adt.Expr { + if !c.IsValidator { + return c.NewErrf("matchIf is a validator and should not be used as a function") + } + + self := finalizeSelf(c, args[0]) + if err := bottom(c, self); err != nil { + return &adt.Bool{B: false} + } + ifSchema, thenSchema, elseSchema := args[1], args[2], args[3] + v := unifyValidator(c, self, ifSchema) + var chosenSchema adt.Value + if err := validate.Validate(c, v, finalCfg); err == nil { + chosenSchema = thenSchema + } else { + chosenSchema = elseSchema + } + v = unifyValidator(c, self, chosenSchema) + err := validate.Validate(c, v, finalCfg) + if err == nil { + return &adt.Bool{B: true} + } + // TODO should we also include in the error something about the fact that + // the if condition passed or failed? + return err + }, +} + +var finalCfg = &validate.Config{Final: true} + +// finalizeSelf ensures a value is fully evaluated and then strips it of any +// of its validators or default values. +func finalizeSelf(c *adt.OpContext, self adt.Value) adt.Value { + if x, ok := self.(*adt.Vertex); ok { + self = x.ToDataAll(c) + } + return self +} + +func unifyValidator(c *adt.OpContext, self, check adt.Value) *adt.Vertex { + v := &adt.Vertex{} + closeInfo := c.CloseInfo() + v.AddConjunct(adt.MakeConjunct(nil, self, closeInfo)) + v.AddConjunct(adt.MakeConjunct(nil, check, closeInfo)) + v.Finalize(c) + return v +} + +func checkNum(ctx *adt.OpContext, bound adt.Value, count, maxCount int64) *adt.Bottom { + cnt := ctx.NewInt64(count) + n := unifyValidator(ctx, bound, cnt) + b, _ := n.BaseValue.(*adt.Bottom) + if b != nil { + b := ctx.NewErrf("%d matched, expected %v", count, bound) + + // By default we should mark the error as incomplete, but check if we + // know for sure it will fail. + switch bound := bound.(type) { + case *adt.Num: + if i, err := bound.X.Int64(); err == nil && i > count && i <= maxCount { + b.Code = adt.IncompleteError + } + + case *adt.BoundValue: + v := &adt.Vertex{} + v.AddConjunct(ctx.MakeConjunct(bound)) + v.AddConjunct(ctx.MakeConjunct(&adt.BoundValue{ + Op: adt.GreaterEqualOp, + Value: cnt, + })) + v.AddConjunct(ctx.MakeConjunct(&adt.BoundValue{ + Op: adt.LessEqualOp, + Value: ctx.NewInt64(maxCount), + })) + v.Finalize(ctx) + if _, ok := v.BaseValue.(*adt.Bottom); !ok { + b.Code = adt.IncompleteError + } + + default: + b.Code = adt.IncompleteError + } + + return b + } + return nil +} + +func bottom(c *adt.OpContext, v adt.Value) *adt.Bottom { + switch x := v.(type) { + case *adt.Vertex: + return x.Err(c) + case *adt.Bottom: + return x + } + return nil +} diff --git a/vendor/cuelang.org/go/internal/core/convert/go.go b/vendor/cuelang.org/go/internal/core/convert/go.go index 0d567bedd4..da4a754ee4 100644 --- a/vendor/cuelang.org/go/internal/core/convert/go.go +++ b/vendor/cuelang.org/go/internal/core/convert/go.go @@ -19,6 +19,7 @@ import ( "encoding" "encoding/json" "fmt" + "math" "math/big" "reflect" "slices" @@ -36,7 +37,6 @@ import ( "cuelang.org/go/internal" "cuelang.org/go/internal/core/adt" "cuelang.org/go/internal/core/compile" - internaljson "cuelang.org/go/internal/encoding/json" "cuelang.org/go/internal/types" ) @@ -52,13 +52,35 @@ func GoValueToValue(ctx *adt.OpContext, x interface{}, nilIsTop bool) adt.Value } func GoTypeToExpr(ctx *adt.OpContext, x interface{}) (adt.Expr, errors.Error) { - v := convertGoType(ctx, reflect.TypeOf(x)) + v := newGoConverter(ctx).convertGoType(reflect.TypeOf(x)) if err := ctx.Err(); err != nil { return v, err.Err } return v, nil } +type goConverter struct { + ctx *adt.OpContext + tfile *token.File + offset int +} + +func newGoConverter(ctx *adt.OpContext) *goConverter { + return &goConverter{ + ctx: ctx, + // Code in *[token.File] uses size+1 in a few places. So do + // MaxInt-2 to be sure to avoid wrap-around issues. + tfile: token.NewFile(pkgID(), -1, math.MaxInt-2), + offset: 1, + } +} + +func (c *goConverter) setNextPos(n ast.Node) ast.Node { + ast.SetPos(n, c.tfile.Pos(c.offset, 0)) + c.offset++ + return n +} + func toValue(e adt.Expr) adt.Value { if v, ok := e.(adt.Value); ok { return v @@ -71,13 +93,14 @@ func toValue(e adt.Expr) adt.Value { func compileExpr(ctx *adt.OpContext, expr ast.Expr) adt.Value { c, err := compile.Expr(nil, ctx, pkgID(), expr) if err != nil { - return &adt.Bottom{Err: errors.Promote(err, "compile")} + return &adt.Bottom{ + Err: errors.Promote(err, "compile")} } return adt.Resolve(ctx, c) } // parseTag parses a CUE expression from a cue tag. -func parseTag(ctx *adt.OpContext, obj *ast.StructLit, field, tag string) ast.Expr { +func parseTag(ctx *adt.OpContext, field, tag string) ast.Expr { tag, _ = splitTag(tag) if tag == "" { return topSentinel @@ -183,17 +206,8 @@ func isOmitEmpty(f *reflect.StructField) bool { return isOmitEmpty } -// parseJSON parses JSON into a CUE value. b must be valid JSON. -func parseJSON(ctx *adt.OpContext, b []byte) adt.Value { - expr, err := parser.ParseExpr("json", b) - if err != nil { - panic(err) // cannot happen - } - return compileExpr(ctx, expr) -} - func GoValueToExpr(ctx *adt.OpContext, nilIsTop bool, x interface{}) adt.Expr { - e := convertRec(ctx, nilIsTop, x) + e := newGoConverter(ctx).convertRec(nilIsTop, x) if e == nil { return ctx.AddErrf("unsupported Go type (%T)", x) } @@ -209,36 +223,41 @@ func isNil(x reflect.Value) bool { return false } -func convertRec(ctx *adt.OpContext, nilIsTop bool, x interface{}) adt.Value { +func (c *goConverter) convertRec(nilIsTop bool, x interface{}) (result adt.Value) { if t := (&types.Value{}); types.CastValue(t, x) { - // TODO: panic if nto the same runtime. + // TODO: panic if not the same runtime. return t.V } - src := ctx.Source() + src := c.ctx.Source() + switch v := x.(type) { case nil: if nilIsTop { - ident, _ := ctx.Source().(*ast.Ident) + ident, _ := src.(*ast.Ident) return &adt.Top{Src: ident} } - return &adt.Null{Src: ctx.Source()} + return &adt.Null{Src: src} case *ast.File: - x, err := compile.Files(nil, ctx, pkgID(), v) + x, err := compile.Files(nil, c.ctx, pkgID(), v) if err != nil { return &adt.Bottom{Err: errors.Promote(err, "compile")} } - if len(x.Conjuncts) != 1 { + if _, n := x.SingleConjunct(); n != 1 { panic("unexpected length") } return x case ast.Expr: - return compileExpr(ctx, v) + return compileExpr(c.ctx, v) case *big.Int: v2 := new(apd.BigInt).SetMathBigInt(v) - return &adt.Num{Src: src, K: adt.IntKind, X: *apd.NewWithBigInt(v2, 0)} + return &adt.Num{ + Src: src, + K: adt.IntKind, + X: *apd.NewWithBigInt(v2, 0), + } case *big.Rat: // should we represent this as a binary operation? @@ -248,7 +267,7 @@ func convertRec(ctx *adt.OpContext, nilIsTop bool, x interface{}) adt.Value { apd.NewWithBigInt(new(apd.BigInt).SetMathBigInt(v.Denom()), 0), ) if err != nil { - return ctx.AddErrf("could not convert *big.Rat: %v", err) + return c.ctx.AddErrf("could not convert *big.Rat: %v", err) } if !v.IsInt() { n.K = adt.FloatKind @@ -259,7 +278,7 @@ func convertRec(ctx *adt.OpContext, nilIsTop bool, x interface{}) adt.Value { n := &adt.Num{Src: src, K: adt.FloatKind} _, _, err := n.X.SetString(v.String()) if err != nil { - return ctx.AddErr(errors.Promote(err, "invalid float")) + return c.ctx.AddErr(errors.Promote(err, "invalid float")) } return n @@ -277,28 +296,28 @@ func convertRec(ctx *adt.OpContext, nilIsTop bool, x interface{}) adt.Value { kind = adt.IntKind v = &d } - n := &adt.Num{Src: ctx.Source(), K: kind} + n := &adt.Num{Src: src, K: kind} n.X = *v return n case json.Marshaler: b, err := v.MarshalJSON() if err != nil { - return ctx.AddErr(errors.Promote(err, "json.Marshaler")) + return c.ctx.AddErr(errors.Promote(err, "json.Marshaler")) } - - return parseJSON(ctx, b) + expr, err := parser.ParseExpr("json", b) + if err != nil { + panic(err) // cannot happen + } + return compileExpr(c.ctx, expr) case encoding.TextMarshaler: b, err := v.MarshalText() if err != nil { - return ctx.AddErr(errors.Promote(err, "encoding.TextMarshaler")) - } - b, err = internaljson.Marshal(string(b)) - if err != nil { - return ctx.AddErr(errors.Promote(err, "json")) + return c.ctx.AddErr(errors.Promote(err, "encoding.TextMarshaler")) } - return parseJSON(ctx, b) + s, _ := unicode.UTF8.NewEncoder().String(string(b)) + return &adt.String{Src: src, Str: s} case error: var errs errors.Error @@ -306,43 +325,43 @@ func convertRec(ctx *adt.OpContext, nilIsTop bool, x interface{}) adt.Value { case errors.Error: errs = x default: - errs = ctx.Newf("%s", x.Error()) + errs = c.ctx.Newf("%s", x.Error()) } return &adt.Bottom{Err: errs} case bool: - return &adt.Bool{Src: ctx.Source(), B: v} + return &adt.Bool{Src: src, B: v} case string: s, _ := unicode.UTF8.NewEncoder().String(v) - return &adt.String{Src: ctx.Source(), Str: s} + return &adt.String{Src: src, Str: s} case []byte: - return &adt.Bytes{Src: ctx.Source(), B: v} + return &adt.Bytes{Src: src, B: v} case int: - return toInt(ctx, int64(v)) + return c.toInt(int64(v)) case int8: - return toInt(ctx, int64(v)) + return c.toInt(int64(v)) case int16: - return toInt(ctx, int64(v)) + return c.toInt(int64(v)) case int32: - return toInt(ctx, int64(v)) + return c.toInt(int64(v)) case int64: - return toInt(ctx, int64(v)) + return c.toInt(int64(v)) case uint: - return toUint(ctx, uint64(v)) + return c.toUint(uint64(v)) case uint8: - return toUint(ctx, uint64(v)) + return c.toUint(uint64(v)) case uint16: - return toUint(ctx, uint64(v)) + return c.toUint(uint64(v)) case uint32: - return toUint(ctx, uint64(v)) + return c.toUint(uint64(v)) case uint64: - return toUint(ctx, uint64(v)) + return c.toUint(uint64(v)) case uintptr: - return toUint(ctx, uint64(v)) + return c.toUint(uint64(v)) case float64: n := &adt.Num{Src: src, K: adt.FloatKind} _, err := n.X.SetFloat64(v) if err != nil { - return ctx.AddErr(errors.Promote(err, "invalid float")) + return c.ctx.AddErr(errors.Promote(err, "invalid float")) } return n case float32: @@ -350,20 +369,20 @@ func convertRec(ctx *adt.OpContext, nilIsTop bool, x interface{}) adt.Value { // apd.Decimal has a SetFloat64 method, but no SetFloat32. _, _, err := n.X.SetString(strconv.FormatFloat(float64(v), 'E', -1, 32)) if err != nil { - return ctx.AddErr(errors.Promote(err, "invalid float")) + return c.ctx.AddErr(errors.Promote(err, "invalid float")) } return n case reflect.Value: if v.CanInterface() { - return convertRec(ctx, nilIsTop, v.Interface()) + return c.convertRec(nilIsTop, v.Interface()) } default: value := reflect.ValueOf(v) switch value.Kind() { case reflect.Bool: - return &adt.Bool{Src: ctx.Source(), B: value.Bool()} + return &adt.Bool{Src: src, B: value.Bool()} case reflect.String: str := value.String() @@ -372,40 +391,32 @@ func convertRec(ctx *adt.OpContext, nilIsTop bool, x interface{}) adt.Value { // if !utf8.ValidString(str) { // return ctx.AddErrf("cannot convert result to string: invalid UTF-8") // } - return &adt.String{Src: ctx.Source(), Str: str} + return &adt.String{Src: src, Str: str} case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return toInt(ctx, value.Int()) + return c.toInt(value.Int()) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return toUint(ctx, value.Uint()) + return c.toUint(value.Uint()) case reflect.Float32, reflect.Float64: - return convertRec(ctx, nilIsTop, value.Float()) + return c.convertRec(nilIsTop, value.Float()) case reflect.Ptr: if value.IsNil() { if nilIsTop { - ident, _ := ctx.Source().(*ast.Ident) + ident, _ := src.(*ast.Ident) return &adt.Top{Src: ident} } - return &adt.Null{Src: ctx.Source()} + return &adt.Null{Src: src} } - return convertRec(ctx, nilIsTop, value.Elem().Interface()) + return c.convertRec(nilIsTop, value.Elem().Interface()) case reflect.Struct: - obj := &adt.StructLit{Src: src} + sl := &adt.StructLit{Src: c.setNextPos(ast.NewStruct())} v := &adt.Vertex{} - env := ctx.Env(0) - if env == nil { - env = &adt.Environment{} - } - // There is no closedness or cycle info for Go structs, so we - // pass an empty CloseInfo. - v.AddStruct(obj, env, adt.CloseInfo{}) - v.SetValue(ctx, &adt.StructMarker{}) t := value.Type() for i := 0; i < value.NumField(); i++ { @@ -423,7 +434,7 @@ func convertRec(ctx *adt.OpContext, nilIsTop bool, x interface{}) adt.Value { if isOmitEmpty(&sf) && val.IsZero() { continue } - sub := convertRec(ctx, nilIsTop, val.Interface()) + sub := c.convertRec(nilIsTop, val.Interface()) if sub == nil { // mimic behavior of encoding/json: skip fields of unsupported types continue @@ -446,32 +457,32 @@ func convertRec(ctx *adt.OpContext, nilIsTop bool, x interface{}) adt.Value { continue } - f := ctx.StringLabel(name) - obj.Decls = append(obj.Decls, &adt.Field{Label: f, Value: sub}) - arc, ok := sub.(*adt.Vertex) - if ok { - a := *arc - arc = &a - arc.Label = f - } else { - arc = &adt.Vertex{Label: f, BaseValue: sub} - arc.ForceDone() - arc.AddConjunct(adt.MakeRootConjunct(nil, sub)) - } - v.Arcs = append(v.Arcs, arc) + f := c.ctx.StringLabel(name) + c.createField(f, sub, sl) + v.Arcs = append(v.Arcs, c.ensureArcVertex(sub, f)) + } + + env := c.ctx.Env(0) + if env == nil { + env = &adt.Environment{} } + // There is no closedness or cycle info for Go structs, so we + // pass an empty CloseInfo. + v.AddStruct(sl, env, adt.CloseInfo{}) + v.SetValue(c.ctx, &adt.StructMarker{}) + v.ForceDone() return v case reflect.Map: - v := &adt.Vertex{BaseValue: &adt.StructMarker{}} - v.SetValue(ctx, &adt.StructMarker{}) + obj := &adt.StructLit{Src: c.setNextPos(ast.NewStruct())} + v := &adt.Vertex{} t := value.Type() switch key := t.Key(); key.Kind() { default: if !key.Implements(textMarshaler) { - return ctx.AddErrf("unsupported Go type for map key (%v)", key) + return c.ctx.AddErrf("unsupported Go type for map key (%v)", key) } fallthrough case reflect.String, @@ -488,80 +499,129 @@ func convertRec(ctx *adt.OpContext, nilIsTop bool, x interface{}) adt.Value { // continue // } - sub := convertRec(ctx, nilIsTop, val.Interface()) + sub := c.convertRec(nilIsTop, val.Interface()) // mimic behavior of encoding/json: report error of // unsupported type. if sub == nil { - return ctx.AddErrf("unsupported Go type (%T)", val.Interface()) + return c.ctx.AddErrf("unsupported Go type (%T)", val.Interface()) } if isBottom(sub) { return sub } s := fmt.Sprint(k) - f := ctx.StringLabel(s) - arc, ok := sub.(*adt.Vertex) - if ok { - a := *arc - arc = &a - arc.Label = f - } else { - arc = &adt.Vertex{Label: f, BaseValue: sub} - arc.ForceDone() - arc.AddConjunct(adt.MakeRootConjunct(nil, sub)) - } - v.Arcs = append(v.Arcs, arc) + f := c.ctx.StringLabel(s) + v.Arcs = append(v.Arcs, c.ensureArcVertex(sub, f)) } slices.SortFunc(v.Arcs, func(a, b *adt.Vertex) int { - return strings.Compare(a.Label.IdentString(ctx), b.Label.IdentString(ctx)) + return strings.Compare(a.Label.IdentString(c.ctx), b.Label.IdentString(c.ctx)) }) + // Create all the adt/ast fields after sorting the arcs + for _, arc := range v.Arcs { + c.createField(arc.Label, arc, obj) + } } + env := c.ctx.Env(0) + if env == nil { + env = &adt.Environment{} + } + v.AddStruct(obj, env, adt.CloseInfo{}) + v.SetValue(c.ctx, &adt.StructMarker{}) + v.ForceDone() + return v case reflect.Slice, reflect.Array: - var values []adt.Value + list := &adt.ListLit{Src: ast.NewList()} + c.setNextPos(list.Src) + + v := &adt.Vertex{} for i := 0; i < value.Len(); i++ { val := value.Index(i) - x := convertRec(ctx, nilIsTop, val.Interface()) + x := c.convertRec(nilIsTop, val.Interface()) if x == nil { - return ctx.AddErrf("unsupported Go type (%T)", + return c.ctx.AddErrf("unsupported Go type (%T)", val.Interface()) } if isBottom(x) { return x } - values = append(values, x) + list.Elems = append(list.Elems, x) + f := adt.MakeIntLabel(adt.IntLabel, int64(i)) + v.Arcs = append(v.Arcs, c.ensureArcVertex(x, f)) } - return ctx.NewList(values...) + env := c.ctx.Env(0) + if env == nil { + env = &adt.Environment{} + } + v.AddConjunct(adt.MakeRootConjunct(env, list)) + v.SetValue(c.ctx, &adt.ListMarker{}) + v.ForceDone() + + return v } } return nil } -func toInt(ctx *adt.OpContext, x int64) adt.Value { - n := &adt.Num{Src: ctx.Source(), K: adt.IntKind} +func (c *goConverter) ensureArcVertex(x adt.Value, l adt.Feature) *adt.Vertex { + env := c.ctx.Env(0) + if env == nil { + env = &adt.Environment{} + } + arc, ok := x.(*adt.Vertex) + if ok { + a := *arc + arc = &a + arc.Label = l + } else { + arc = &adt.Vertex{Label: l} + arc.AddConjunct(adt.MakeRootConjunct(env, x)) + arc.SetValue(c.ctx, x) + arc.ForceDone() + } + return arc +} + +func (c *goConverter) createField(l adt.Feature, sub adt.Value, sl *adt.StructLit) { + src := sl.Src.(*ast.StructLit) + astField := &ast.Field{ + Label: ast.NewIdent(l.IdentString(c.ctx)), + Constraint: token.ILLEGAL, + } + if expr, ok := sub.Source().(ast.Expr); ok { + astField.Value = expr + } + c.setNextPos(astField.Label) + src.Elts = append(src.Elts, astField) + field := &adt.Field{Label: l, Value: sub, Src: astField} + sl.Decls = append(sl.Decls, field) +} + +func (c *goConverter) toInt(x int64) adt.Value { + n := &adt.Num{Src: c.ctx.Source(), K: adt.IntKind} n.X = *apd.New(x, 0) return n } -func toUint(ctx *adt.OpContext, x uint64) adt.Value { - n := &adt.Num{Src: ctx.Source(), K: adt.IntKind} +func (c *goConverter) toUint(x uint64) adt.Value { + n := &adt.Num{Src: c.ctx.Source(), K: adt.IntKind} n.X.Coeff.SetUint64(x) return n } -func convertGoType(ctx *adt.OpContext, t reflect.Type) adt.Expr { +func (c *goConverter) convertGoType(t reflect.Type) adt.Expr { // TODO: this can be much more efficient. // TODO: synchronize - return goTypeToValue(ctx, true, t) + return c.goTypeToValue(true, t) } var ( - jsonMarshaler = reflect.TypeOf(new(json.Marshaler)).Elem() - textMarshaler = reflect.TypeOf(new(encoding.TextMarshaler)).Elem() + jsonMarshaler = reflect.TypeFor[json.Marshaler]() + textMarshaler = reflect.TypeFor[encoding.TextMarshaler]() topSentinel = ast.NewIdent("_") ) @@ -569,20 +629,20 @@ var ( // // TODO: if this value will always be unified with a concrete type in Go, then // many of the fields may be omitted. -func goTypeToValue(ctx *adt.OpContext, allowNullDefault bool, t reflect.Type) adt.Expr { - if _, t, ok := ctx.LoadType(t); ok { +func (c *goConverter) goTypeToValue(allowNullDefault bool, t reflect.Type) adt.Expr { + if _, t, ok := c.ctx.LoadType(t); ok { return t } - _, v := goTypeToValueRec(ctx, allowNullDefault, t) + _, v := c.goTypeToValueRec(allowNullDefault, t) if v == nil { - return ctx.AddErrf("unsupported Go type (%v)", t) + return c.ctx.AddErrf("unsupported Go type (%v)", t) } return v } -func goTypeToValueRec(ctx *adt.OpContext, allowNullDefault bool, t reflect.Type) (e ast.Expr, expr adt.Expr) { - if src, t, ok := ctx.LoadType(t); ok { +func (c *goConverter) goTypeToValueRec(allowNullDefault bool, t reflect.Type) (e ast.Expr, expr adt.Expr) { + if src, t, ok := c.ctx.LoadType(t); ok { return src, t } @@ -615,7 +675,7 @@ func goTypeToValueRec(ctx *adt.OpContext, allowNullDefault bool, t reflect.Type) for elem.Kind() == reflect.Ptr { elem = elem.Elem() } - e, _ = goTypeToValueRec(ctx, false, elem) + e, _ = c.goTypeToValueRec(false, elem) if allowNullDefault { e = wrapOrNull(e) } @@ -654,7 +714,7 @@ func goTypeToValueRec(ctx *adt.OpContext, allowNullDefault bool, t reflect.Type) // TODO: dirty trick: set this to a temporary Vertex and then update the // arcs and conjuncts of this vertex below. This will allow circular // references. Maybe have a special kind of "hardlink" reference. - ctx.StoreType(t, obj, nil) + c.ctx.StoreType(t, obj, nil) for i := 0; i < t.NumField(); i++ { f := t.Field(i) @@ -662,7 +722,7 @@ func goTypeToValueRec(ctx *adt.OpContext, allowNullDefault bool, t reflect.Type) continue } _, ok := f.Tag.Lookup("cue") - elem, _ := goTypeToValueRec(ctx, !ok, f.Type) + elem, _ := c.goTypeToValueRec(!ok, f.Type) if isBad(elem) { continue // Ignore fields for unsupported types } @@ -675,7 +735,7 @@ func goTypeToValueRec(ctx *adt.OpContext, allowNullDefault bool, t reflect.Type) } if tag, ok := f.Tag.Lookup("cue"); ok { - v := parseTag(ctx, obj, name, tag) + v := parseTag(c.ctx, name, tag) if isBad(v) { return v, nil } @@ -687,6 +747,7 @@ func goTypeToValueRec(ctx *adt.OpContext, allowNullDefault bool, t reflect.Type) // The GO JSON decoder always allows a value to be undefined. d := &ast.Field{Label: ast.NewIdent(name), Value: elem} + c.setNextPos(d) if isOptional(&f) { internal.SetConstraint(d, token.OPTION) } @@ -702,16 +763,20 @@ func goTypeToValueRec(ctx *adt.OpContext, allowNullDefault bool, t reflect.Type) if t.Elem().Kind() == reflect.Uint8 { e = ast.NewIdent("__bytes") } else { - elem, _ := goTypeToValueRec(ctx, allowNullDefault, t.Elem()) + elem, _ := c.goTypeToValueRec(allowNullDefault, t.Elem()) if elem == nil { - b := ctx.AddErrf("unsupported Go type (%v)", t.Elem()) + b := c.ctx.AddErrf("unsupported Go type (%v)", t.Elem()) return &ast.BadExpr{}, b } if t.Kind() == reflect.Array { - e = ast.NewBinExpr(token.MUL, - ast.NewLit(token.INT, strconv.Itoa(t.Len())), - ast.NewList(elem)) + e = ast.NewCall( + ast.NewSel(&ast.Ident{ + Name: "list", + Node: ast.NewImport(nil, "list")}, + "Repeat"), + ast.NewList(elem), + ast.NewLit(token.INT, strconv.Itoa(t.Len()))) } else { e = ast.NewList(&ast.Ellipsis{Type: elem}) } @@ -726,13 +791,13 @@ func goTypeToValueRec(ctx *adt.OpContext, allowNullDefault bool, t reflect.Type) reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: default: - b := ctx.AddErrf("unsupported Go type for map key (%v)", key) + b := c.ctx.AddErrf("unsupported Go type for map key (%v)", key) return &ast.BadExpr{}, b } - v, x := goTypeToValueRec(ctx, allowNullDefault, t.Elem()) + v, x := c.goTypeToValueRec(allowNullDefault, t.Elem()) if v == nil { - b := ctx.AddErrf("unsupported Go type (%v)", t.Elem()) + b := c.ctx.AddErrf("unsupported Go type (%v)", t.Elem()) return &ast.BadExpr{}, b } if isBad(v) { @@ -750,20 +815,21 @@ func goTypeToValueRec(ctx *adt.OpContext, allowNullDefault bool, t reflect.Type) store: // TODO: store error if not nil? if e != nil { + c.setNextPos(e) f := &ast.File{Decls: []ast.Decl{&ast.EmbedDecl{Expr: e}}} astutil.Resolve(f, func(_ token.Pos, msg string, args ...interface{}) { - ctx.AddErrf(msg, args...) + c.ctx.AddErrf(msg, args...) }) var x adt.Expr - c, err := compile.Expr(nil, ctx, pkgID(), e) + x2, err := compile.Expr(nil, c.ctx, pkgID(), e) if err != nil { b := &adt.Bottom{Err: err} - ctx.AddBottom(b) + c.ctx.AddBottom(b) x = b } else { - x = c.Expr() + x = x2.Expr() } - ctx.StoreType(t, e, x) + c.ctx.StoreType(t, e, x) return e, x } return e, nil diff --git a/vendor/cuelang.org/go/internal/core/debug/compact.go b/vendor/cuelang.org/go/internal/core/debug/compact.go index 87c31fca78..5450cf93cf 100644 --- a/vendor/cuelang.org/go/internal/core/debug/compact.go +++ b/vendor/cuelang.org/go/internal/core/debug/compact.go @@ -39,12 +39,15 @@ func (w *compactPrinter) node(n adt.Node) { switch x := n.(type) { case *adt.Vertex: if x.BaseValue == nil || (w.cfg.Raw && !x.IsData()) { - for i, c := range x.Conjuncts { + i := 0 + x.VisitLeafConjuncts(func(c adt.Conjunct) bool { if i > 0 { w.string(" & ") } + i++ w.node(c.Elem()) - } + return true + }) return } @@ -62,7 +65,7 @@ func (w *compactPrinter) node(n adt.Node) { w.string("m") } w.string("=") - if c := a.Conjuncts[0]; a.MultiLet { + if c := a.ConjunctAt(0); a.MultiLet { w.node(c.Expr()) continue } @@ -89,6 +92,7 @@ func (w *compactPrinter) node(n adt.Node) { case *adt.Vertex: if v, ok := w.printShared(x); !ok { w.node(v) + w.popVertex() } case adt.Value: diff --git a/vendor/cuelang.org/go/internal/core/debug/debug.go b/vendor/cuelang.org/go/internal/core/debug/debug.go index ce37ee5869..e6431bd57e 100644 --- a/vendor/cuelang.org/go/internal/core/debug/debug.go +++ b/vendor/cuelang.org/go/internal/core/debug/debug.go @@ -70,6 +70,9 @@ type printer struct { indent string cfg *Config + // keep track of vertices to avoid cycles. + stack []*adt.Vertex + // modes: // - show vertex // - show original conjuncts @@ -128,23 +131,51 @@ func (w *printer) shared(v *adt.Vertex) { // printShared prints a reference to a structure-shared node that is a value // of v, if it is a shared node. It reports the dereferenced node and whether // the node was printed. -func (w *printer) printShared(v *adt.Vertex) (x *adt.Vertex, ok bool) { +func (w *printer) printShared(v0 *adt.Vertex) (x *adt.Vertex, ok bool) { + // Handle cyclic shared nodes differently. If a shared node was part of // a disjunction, it will still be wrapped in a disjunct Vertex. // Similarly, a shared node should never point to a disjunct directly, // but rather to the original arc that subsequently points to a // disjunct. - v = v.DerefDisjunct() - useReference := v.IsShared - isCyclic := v.IsCyclic - s, ok := v.BaseValue.(*adt.Vertex) - v = v.DerefValue() - isCyclic = isCyclic || v.IsCyclic - if useReference && isCyclic && ok && len(v.Arcs) > 0 { - w.shared(s) - return v, true + v0 = v0.DerefDisjunct() + isCyclic := v0.IsCyclic + s, ok := v0.BaseValue.(*adt.Vertex) + v1 := v0.DerefValue() + useReference := v0.IsShared && v1.Rooted() + isCyclic = isCyclic || v1.IsCyclic + _ = isCyclic + // NOTE(debug): use this line instead of the following to expand shared + // cases where it is safe to do so. + // if useReference && isCyclic && ok && len(v.Arcs) > 0 { + if useReference && ok && len(v1.Arcs) > 0 { + w.shared(v1) + return v1, true + } + if !w.pushVertex(v1) { + if s != nil { + w.shared(s) + w.string(" =>") + } + w.shared(v1) + return v1, true + } + return v1, false +} + +func (w *printer) pushVertex(v *adt.Vertex) bool { + for _, x := range w.stack { + if x == v { + w.string("") + return false + } } - return v, false + w.stack = append(w.stack, v) + return true +} + +func (w *printer) popVertex() { + w.stack = w.stack[:len(w.stack)-1] } func (w *printer) shortError(errs errors.Error) { @@ -201,6 +232,7 @@ func (w *printer) node(n adt.Node) { if ok { return } + defer w.popVertex() var kind adt.Kind if x.BaseValue != nil { @@ -281,7 +313,7 @@ func (w *printer) node(n adt.Node) { w.string("multi") } w.string(" = ") - if c := a.Conjuncts[0]; a.MultiLet { + if c := a.ConjunctAt(0); a.MultiLet { w.node(c.Expr()) continue } diff --git a/vendor/cuelang.org/go/internal/core/dep/dep.go b/vendor/cuelang.org/go/internal/core/dep/dep.go index ebdc8ca0b2..97bd94a127 100644 --- a/vendor/cuelang.org/go/internal/core/dep/dep.go +++ b/vendor/cuelang.org/go/internal/core/dep/dep.go @@ -17,6 +17,7 @@ package dep import ( "cuelang.org/go/cue/errors" + "cuelang.org/go/internal" "cuelang.org/go/internal/core/adt" ) @@ -129,13 +130,16 @@ type Dependency struct { func (d *Dependency) Recurse() { savedAll := d.visitor.all savedTop := d.visitor.top + savedMarked := d.visitor.marked d.visitor.all = d.visitor.recurse d.visitor.top = true + d.visitor.marked = nil d.visitor.visitReusingVisitor(d.Node, false) d.visitor.all = savedAll d.visitor.top = savedTop + d.visitor.marked = savedMarked } // Import returns the import reference or nil if the reference was within @@ -146,7 +150,7 @@ func (d *Dependency) Import() *adt.ImportReference { // IsRoot reports whether the dependency is referenced by the root of the // original Vertex passed to any of the Visit* functions, and not one of its -// descendent arcs. This always returns true for Visit(). +// descendent arcs. This always returns true for [Visit]. func (d *Dependency) IsRoot() bool { return d.top } @@ -410,15 +414,37 @@ func (c *visitor) reportDependency(env *adt.Environment, ref adt.Resolver, v *ad reference = c.topRef } - if !v.Rooted() { + inspect := false + + if c.ctxt.Version == internal.DevVersion { + inspect = v.IsDetached() || !v.MayAttach() + } else { + inspect = !v.Rooted() + } + + if inspect { + // TODO: there is currently no way to inspect where a non-rooted node + // originated from. As of EvalV3, we allow non-rooted nodes to be + // structure shared. This makes them effectively rooted, with the + // difference that there is an indirection in BaseValue for the + // structure sharing. Nonetheless, this information is lost in the + // internal API when traversing. + + // As an alternative we now do not skip processing the node if we + // an inlined, non-rooted node is associated with another node than + // the one we are currently processing. + + // If a node is internal, we need to further investigate any references. + // If there are any, reference, even if it is otherwise not reported, + // we report this reference. before := c.numRefs c.markInternalResolvers(env, ref, v) // TODO: this logic could probably be simplified if we let clients // explicitly mark whether to visit rootless nodes. Visiting these // may be necessary when substituting values. switch _, ok := ref.(*adt.FieldReference); { - case !ok: - // Do not report rootless nodes for selectors. + case !ok && c.isLocal(env, ref): + // Do not report rootless nodes for selectors. return case c.numRefs > before: // For FieldReferences that resolve to something we do not need @@ -450,6 +476,9 @@ func (c *visitor) reportDependency(env *adt.Environment, ref adt.Resolver, v *ad } v = w } + if inspect && len(c.pathStack) == 0 && c.topRef != nil { + altRef = c.topRef + } // All resolvers are expressions. if p := importRef(ref.(adt.Expr)); p != nil { @@ -460,6 +489,10 @@ func (c *visitor) reportDependency(env *adt.Environment, ref adt.Resolver, v *ad c.numRefs++ + if c.ctxt.Version == internal.DevVersion { + v.Finalize(c.ctxt) + } + d := Dependency{ Node: v, Reference: altRef, @@ -473,6 +506,26 @@ func (c *visitor) reportDependency(env *adt.Environment, ref adt.Resolver, v *ad } } +// isLocal reports whether a non-rooted struct is an internal node or not. +// If it is not, we need to further investigate any references. +func (c *visitor) isLocal(env *adt.Environment, r adt.Resolver) bool { + for { + switch x := r.(type) { + case *adt.FieldReference: + for i := 0; i < int(x.UpCount); i++ { + env = env.Up + } + return env.Vertex == empty + case *adt.SelectorExpr: + r, _ = x.X.(adt.Resolver) + case *adt.IndexExpr: + r, _ = x.X.(adt.Resolver) + default: + return env.Vertex == empty + } + } +} + // TODO(perf): make this available as a property of vertices to avoid doing // work repeatedly. func hasLetParent(v *adt.Vertex) bool { diff --git a/vendor/cuelang.org/go/internal/core/dep/mixed.go b/vendor/cuelang.org/go/internal/core/dep/mixed.go index 51ab7dbe28..5ae089a928 100644 --- a/vendor/cuelang.org/go/internal/core/dep/mixed.go +++ b/vendor/cuelang.org/go/internal/core/dep/mixed.go @@ -29,6 +29,8 @@ import ( // and comprehension sources. func (v *visitor) dynamic(n *adt.Vertex, top bool) { found := false + // TODO: Consider if we should only visit the conjuncts of the disjunction + // for dynamic mode. n.VisitLeafConjuncts(func(c adt.Conjunct) bool { if v.marked[c.Expr()] { found = true @@ -45,6 +47,7 @@ func (v *visitor) dynamic(n *adt.Vertex, top bool) { return } + n = n.DerefValue() for _, a := range n.Arcs { if !a.IsDefined(v.ctxt) || a.Label.IsLet() { continue diff --git a/vendor/cuelang.org/go/internal/core/eval/eval.go b/vendor/cuelang.org/go/internal/core/eval/eval.go index dc0f9bf400..6c486d125d 100644 --- a/vendor/cuelang.org/go/internal/core/eval/eval.go +++ b/vendor/cuelang.org/go/internal/core/eval/eval.go @@ -30,8 +30,6 @@ func Evaluate(r adt.Runtime, v *adt.Vertex) { func New(r adt.Runtime) *Unifier { ctx := NewContext(r, nil) - // TODO: we could access these directly if we can use runtime.Runtime directly. - ctx.Version, ctx.Config = r.Settings() return &Unifier{r: r, e: ctx} } diff --git a/vendor/cuelang.org/go/internal/core/export/adt.go b/vendor/cuelang.org/go/internal/core/export/adt.go index 2d2a14c493..c7b8b7085c 100644 --- a/vendor/cuelang.org/go/internal/core/export/adt.go +++ b/vendor/cuelang.org/go/internal/core/export/adt.go @@ -16,7 +16,9 @@ package export import ( "bytes" + "cmp" "fmt" + "slices" "strings" "cuelang.org/go/cue/ast" @@ -230,6 +232,9 @@ func (e *exporter) adt(env *adt.Environment, expr adt.Elem) ast.Expr { } case *adt.BinaryExpr: + if x.Op == adt.AndOp || x.Op == adt.OrOp { + return e.sortBinaryTree(env, x) + } return &ast.BinaryExpr{ Op: x.Op.Token(), X: e.innerExpr(env, x.X), @@ -301,6 +306,89 @@ func (e *exporter) adt(env *adt.Environment, expr adt.Elem) ast.Expr { } } +// sortBinaryTree converte x to a binary tree and sorts it's elements +// using sortLeafAdt. +func (e *exporter) sortBinaryTree(env *adt.Environment, x *adt.BinaryExpr) (b ast.Expr) { + var exprs []adt.Node + + var flatten func(expr adt.Expr) + flatten = func(expr adt.Expr) { + if y, ok := expr.(*adt.BinaryExpr); ok && x.Op == y.Op { + flatten(y.X) + flatten(y.Y) + } else { + exprs = append(exprs, expr) + } + } + flatten(x) + + // Sort the expressions + slices.SortStableFunc(exprs, cmpLeafNodes) + + nodes := make([]ast.Expr, 0, len(exprs)) + for _, x := range exprs { + switch y := x.(type) { + case *adt.Top: + case *adt.BasicType: + if y.K != adt.TopKind { + nodes = append(nodes, e.expr(env, y)) + } + default: + nodes = append(nodes, e.innerExpr(env, y.(adt.Expr))) + } + } + + if len(nodes) == 0 { + return e.adt(env, &adt.Top{}) + } + + return ast.NewBinExpr(x.Op.Token(), nodes...) +} + +// cmpConjuncts compares two Conjunct based on their element using cmpLeafNodes. +func cmpConjuncts(a, b adt.Conjunct) int { + return cmpLeafNodes(a.Expr(), b.Expr()) +} + +// cmpLeafNodes compares two adt.Expr values. The values may not be a binary +// expressions. It returns true if a is less than b. +func cmpLeafNodes[T adt.Node](a, b T) int { + if c := cmp.Compare(typeOrder(a), typeOrder(b)); c != 0 { + return c + } + + srcA := a.Source() + srcB := b.Source() + + if srcA == nil || srcB == nil { + // TODO: some tie breaker + return 0 + } + + return srcA.Pos().Compare(srcB.Pos()) +} + +func typeOrder(x adt.Node) int { + switch x.(type) { + case *adt.Top: + return 0 + case *adt.BasicType: + return 1 + case *adt.FieldReference: + return 2 // sometimes basic types are represented as field references. + case *adt.Bool, *adt.Null, *adt.Num, *adt.String, *adt.Bytes: + return 10 + case *adt.BoundValue: + return 20 + case *adt.StructLit, *adt.ListLit: + return 500 + case adt.Expr: + return 25 + default: + return 100 + } +} + var dummyTop = &ast.Ident{Name: "_"} func (e *exporter) resolve(env *adt.Environment, r adt.Resolver) ast.Expr { diff --git a/vendor/cuelang.org/go/internal/core/export/export.go b/vendor/cuelang.org/go/internal/core/export/export.go index 5b294331fe..331b39f38d 100644 --- a/vendor/cuelang.org/go/internal/core/export/export.go +++ b/vendor/cuelang.org/go/internal/core/export/export.go @@ -21,6 +21,7 @@ import ( "cuelang.org/go/cue/ast" "cuelang.org/go/cue/ast/astutil" "cuelang.org/go/cue/errors" + "cuelang.org/go/cue/token" "cuelang.org/go/internal" "cuelang.org/go/internal/core/adt" "cuelang.org/go/internal/core/eval" @@ -183,11 +184,14 @@ func (p *Profile) Expr(r adt.Runtime, pkgID string, n adt.Expr) (ast.Expr, error } func (e *exporter) toFile(v *adt.Vertex, x ast.Expr) *ast.File { - f := &ast.File{} + fout := &ast.File{} if e.cfg.AddPackage { pkgName := "" - pkg := &ast.Package{} + pkg := &ast.Package{ + // prevent the file comment from attaching to pkg when there is no pkg comment + PackagePos: token.NoPos.WithRel(token.NewSection), + } v.VisitLeafConjuncts(func(c adt.Conjunct) bool { f, _ := c.Source().(*ast.File) if f == nil { @@ -199,8 +203,15 @@ func (e *exporter) toFile(v *adt.Vertex, x ast.Expr) *ast.File { } if e.cfg.ShowDocs { - if doc := internal.FileComment(f); doc != nil { - ast.AddComment(pkg, doc) + pkgComments, fileComments := internal.FileComments(f) + + for _, c := range pkgComments { + // add a newline between previous file comment and the pkg comments + c.List[0].Slash = c.List[0].Slash.WithRel(token.NewSection) + ast.AddComment(pkg, c) + } + for _, c := range fileComments { + ast.AddComment(fout, c) } } return true @@ -208,7 +219,13 @@ func (e *exporter) toFile(v *adt.Vertex, x ast.Expr) *ast.File { if pkgName != "" { pkg.Name = ast.NewIdent(pkgName) - f.Decls = append(f.Decls, pkg) + fout.Decls = append(fout.Decls, pkg) + ast.SetComments(pkg, internal.MergeDocs(pkg.Comments())) + } else { + for _, c := range fout.Comments() { + ast.AddComment(pkg, c) + } + ast.SetComments(fout, internal.MergeDocs(pkg.Comments())) } } @@ -217,13 +234,13 @@ func (e *exporter) toFile(v *adt.Vertex, x ast.Expr) *ast.File { panic("null input") case *ast.StructLit: - f.Decls = append(f.Decls, st.Elts...) + fout.Decls = append(fout.Decls, st.Elts...) default: - f.Decls = append(f.Decls, &ast.EmbedDecl{Expr: x}) + fout.Decls = append(fout.Decls, &ast.EmbedDecl{Expr: x}) } - return f + return fout } // Vertex exports evaluated values (data mode). diff --git a/vendor/cuelang.org/go/internal/core/export/expr.go b/vendor/cuelang.org/go/internal/core/export/expr.go index 19bf1c3d1c..cf456f8753 100644 --- a/vendor/cuelang.org/go/internal/core/export/expr.go +++ b/vendor/cuelang.org/go/internal/core/export/expr.go @@ -15,8 +15,9 @@ package export import ( + "cmp" "fmt" - "sort" + "slices" "cuelang.org/go/cue/ast" "cuelang.org/go/cue/token" @@ -73,7 +74,7 @@ func (e *exporter) expr(env *adt.Environment, v adt.Elem) (result ast.Expr) { return nil case *adt.Vertex: - if len(x.Conjuncts) == 0 || x.IsData() { + if x.IsData() { // Treat as literal value. return e.value(x) } // Should this be the arcs label? @@ -169,9 +170,9 @@ func (x *exporter) mergeValues(label adt.Feature, src *adt.Vertex, a []conjunct, } // Unify values only for one level. - if a := e.values.Conjuncts; len(a) > 0 { + if e.values.HasConjuncts() { e.values.Finalize(e.ctx) - e.embed = append(e.embed, e.value(e.values, a...)) + e.embed = append(e.embed, e.value(e.values, e.values.Conjuncts...)) } // Collect and order set of fields. @@ -184,21 +185,20 @@ func (x *exporter) mergeValues(label adt.Feature, src *adt.Vertex, a []conjunct, // Sort fields in case features lists are missing to ensure // predictability. Also sort in reverse order, so that bugs // are more likely exposed. - sort.Slice(fields, func(i, j int) bool { - return fields[i] > fields[j] + slices.SortFunc(fields, func(f1, f2 adt.Feature) int { + return -cmp.Compare(f1, f2) }) - if adt.DebugSort == 0 { - m := sortArcs(extractFeatures(e.structs)) - sort.SliceStable(fields, func(i, j int) bool { - if m[fields[j]] == 0 { - return m[fields[i]] != 0 + m := sortArcs(extractFeatures(e.structs)) + slices.SortStableFunc(fields, func(f1, f2 adt.Feature) int { + if m[f2] == 0 { + if m[f1] == 0 { + return +1 } - return m[fields[i]] > m[fields[j]] - }) - } else { - adt.DebugSortFields(e.ctx, fields) - } + return -1 + } + return -cmp.Compare(m[f1], m[f2]) + }) if len(e.fields) == 0 && !e.hasEllipsis { switch len(e.embed) + len(e.conjuncts) { @@ -297,7 +297,12 @@ func (x *exporter) mergeValues(label adt.Feature, src *adt.Vertex, a []conjunct, func (e *conjuncts) wrapCloseIfNecessary(s *ast.StructLit, v *adt.Vertex) ast.Expr { if !e.hasEllipsis && v != nil { + if v.ClosedNonRecursive { + // Eval V3 logic + return ast.NewCall(ast.NewIdent("close"), s) + } if st, ok := v.BaseValue.(*adt.StructMarker); ok && st.NeedClose { + // Eval V2 logic return ast.NewCall(ast.NewIdent("close"), s) } } diff --git a/vendor/cuelang.org/go/internal/core/export/extract.go b/vendor/cuelang.org/go/internal/core/export/extract.go index 7c399c7d25..e666a9b497 100644 --- a/vendor/cuelang.org/go/internal/core/export/extract.go +++ b/vendor/cuelang.org/go/internal/core/export/extract.go @@ -56,9 +56,8 @@ func extractDocs(v *adt.Vertex) (docs []*ast.CommentGroup) { } case *ast.File: - if c := internal.FileComment(f); c != nil { - docs = append(docs, c) - } + fdocs, _ := internal.FileComments(f) + docs = append(docs, fdocs...) } return true @@ -179,8 +178,7 @@ func extractDeclAttrs(attrs []*ast.Attribute, n ast.Node) []*ast.Attribute { switch x := n.(type) { case nil: case *ast.File: - info := internal.GetPackageInfo(x) - attrs = appendDeclAttrs(attrs, x.Decls[info.Index:]) + attrs = appendDeclAttrs(attrs, x.Decls[len(x.Preamble()):]) case *ast.StructLit: attrs = appendDeclAttrs(attrs, x.Elts) } diff --git a/vendor/cuelang.org/go/internal/core/export/toposort.go b/vendor/cuelang.org/go/internal/core/export/toposort.go index bda694a99c..29c548f647 100644 --- a/vendor/cuelang.org/go/internal/core/export/toposort.go +++ b/vendor/cuelang.org/go/internal/core/export/toposort.go @@ -15,9 +15,11 @@ package export import ( - "sort" + "cmp" + "slices" "cuelang.org/go/internal/core/adt" + "cuelang.org/go/internal/core/toposort" ) // TODO: topological sort should go arguably in a more fundamental place as it @@ -27,6 +29,14 @@ import ( // features than for which there are arcs and also includes features for // optional fields. It assumes the Structs fields are initialized and evaluated. func VertexFeatures(c *adt.OpContext, v *adt.Vertex) []adt.Feature { + if c.TopoSort { + return toposort.VertexFeatures(c, v) + } else { + return vertexFeatures(v) + } +} + +func vertexFeatures(v *adt.Vertex) []adt.Feature { sets := extractFeatures(v.Structs) m := sortArcs(sets) // TODO: use for convenience. @@ -44,11 +54,7 @@ func VertexFeatures(c *adt.OpContext, v *adt.Vertex) []adt.Feature { sets = append(sets, a) } - a = sortedArcs(sets) - if adt.DebugSort > 0 { - adt.DebugSortFields(c, a) - } - return a + return sortedArcs(sets) } func extractFeatures(in []*adt.StructInfo) (a [][]adt.Feature) { @@ -71,7 +77,40 @@ func extractFeatures(in []*adt.StructInfo) (a [][]adt.Feature) { return a } -// sortedArcs is like sortArcs, but returns a the features of optional and +// VertexFeaturesUnsorted returns the feature list of v. There will be +// no duplicate features in the returned list, but there is also no +// attempt made to sort the list. +func VertexFeaturesUnsorted(v *adt.Vertex) (features []adt.Feature) { + seen := make(map[adt.Feature]struct{}) + + for _, s := range v.Structs { + for _, decl := range s.Decls { + field, ok := decl.(*adt.Field) + if !ok { + continue + } + label := field.Label + if _, found := seen[label]; found { + continue + } + seen[label] = struct{}{} + features = append(features, label) + } + } + + for _, arc := range v.Arcs { + label := arc.Label + if _, found := seen[label]; found { + continue + } + seen[label] = struct{}{} + features = append(features, label) + } + + return features +} + +// sortedArcs is like sortArcs, but returns the features of optional and // required fields in an sorted slice. Ultimately, the implementation should // use merge sort everywhere, and this will be the preferred method. Also, // when querying optional fields as well, this helps identifying the optional @@ -88,7 +127,7 @@ func sortedArcsFromMap(m map[adt.Feature]int) []adt.Feature { a = append(a, k) } - sort.Slice(a, func(i, j int) bool { return m[a[i]] > m[a[j]] }) + slices.SortFunc(a, func(a1, a2 adt.Feature) int { return -cmp.Compare(m[a1], m[a2]) }) return a } diff --git a/vendor/cuelang.org/go/internal/core/export/value.go b/vendor/cuelang.org/go/internal/core/export/value.go index 8d2507c1d8..f476a51bcd 100644 --- a/vendor/cuelang.org/go/internal/core/export/value.go +++ b/vendor/cuelang.org/go/internal/core/export/value.go @@ -16,6 +16,7 @@ package export import ( "fmt" + "slices" "strings" "cuelang.org/go/cue/ast" @@ -55,9 +56,10 @@ func (e *exporter) vertex(n *adt.Vertex) (result ast.Expr) { e.popFrame(saved) }() - for _, c := range n.Conjuncts { + n.VisitLeafConjuncts(func(c adt.Conjunct) bool { e.markLets(c.Expr().Source(), s) - } + return true + }) switch x := n.BaseValue.(type) { case nil: @@ -85,7 +87,7 @@ func (e *exporter) vertex(n *adt.Vertex) (result ast.Expr) { result = e.structComposite(n, attrs) } - case !x.IsIncomplete() || len(n.Conjuncts) == 0 || e.cfg.Final: + case !x.IsIncomplete() || !n.HasConjuncts() || e.cfg.Final: result = e.bottom(x) } @@ -101,14 +103,23 @@ func (e *exporter) vertex(n *adt.Vertex) (result ast.Expr) { } if result == nil { // fall back to expression mode - a := []ast.Expr{} + a := []adt.Conjunct{} n.VisitLeafConjuncts(func(c adt.Conjunct) bool { - if x := e.expr(c.Env, c.Elem()); x != dummyTop { - a = append(a, x) - } + a = append(a, c) return true }) - result = ast.NewBinExpr(token.AND, a...) + // Use stable sort to ensure that tie breaks (for instance if elements + // are not associated with a position) are deterministic. + slices.SortStableFunc(a, cmpConjuncts) + + exprs := make([]ast.Expr, 0, len(a)) + for _, c := range a { + if x := e.expr(c.Env, c.Elem()); x != dummyTop { + exprs = append(exprs, x) + } + } + + result = ast.NewBinExpr(token.AND, exprs...) } if len(s.Elts) > 0 { @@ -194,12 +205,15 @@ func (e *exporter) value(n adt.Value, a ...adt.Conjunct) (result ast.Expr) { a = x.Values } + slices.SortStableFunc(a, cmpLeafNodes) + for _, x := range a { result = wrapBin(result, e.bareValue(x), adt.AndOp) } case *adt.Disjunction: a := []ast.Expr{} + for i, v := range x.Values { var expr ast.Expr if e.cfg.Simplify { @@ -245,13 +259,15 @@ func (e *exporter) bool(n *adt.Bool) (b *ast.BasicLit) { return ast.NewBool(n.B) } -func extractBasic(a []adt.Conjunct) *ast.BasicLit { - for _, v := range a { - if b, ok := v.Source().(*ast.BasicLit); ok { - return &ast.BasicLit{Kind: b.Kind, Value: b.Value} +func extractBasic(a []adt.Conjunct) (lit *ast.BasicLit) { + adt.VisitConjuncts(a, func(c adt.Conjunct) bool { + if b, ok := c.Source().(*ast.BasicLit); ok { + lit = &ast.BasicLit{Kind: b.Kind, Value: b.Value} + return false } - } - return nil + return true + }) + return lit } func (e *exporter) num(n *adt.Num, orig []adt.Conjunct) *ast.BasicLit { diff --git a/vendor/cuelang.org/go/internal/core/runtime/build.go b/vendor/cuelang.org/go/internal/core/runtime/build.go index 2f21effbb9..9e90ed8ef1 100644 --- a/vendor/cuelang.org/go/internal/core/runtime/build.go +++ b/vendor/cuelang.org/go/internal/core/runtime/build.go @@ -79,7 +79,7 @@ func (x *Runtime) Build(cfg *Config, b *build.Instance) (v *adt.Vertex, errs err v, err = compile.Files(cc, x, b.ID(), b.Files...) errs = errors.Append(errs, err) - errs = errors.Append(errs, x.injectImplementations(b, v)) + errs = errors.Append(errs, x.InjectImplementations(b, v)) if errs != nil { v = adt.ToVertex(&adt.Bottom{Err: errs}) diff --git a/vendor/cuelang.org/go/internal/core/runtime/extern.go b/vendor/cuelang.org/go/internal/core/runtime/extern.go index 423df562ad..edb231cef3 100644 --- a/vendor/cuelang.org/go/internal/core/runtime/extern.go +++ b/vendor/cuelang.org/go/internal/core/runtime/extern.go @@ -58,12 +58,12 @@ type Compiler interface { Compile(name string, scope adt.Value, a *internal.Attr) (adt.Expr, errors.Error) } -// injectImplementations modifies v to include implementations of functions +// InjectImplementations modifies v to include implementations of functions // for fields associated with the @extern attributes. -func (r *Runtime) injectImplementations(b *build.Instance, v *adt.Vertex) (errs errors.Error) { - if r.interpreters == nil { - return nil - } +// +// TODO(mvdan): unexport again once cue.Instance.Build is no longer used by `cue cmd` +// and can be removed entirely. +func (r *Runtime) InjectImplementations(b *build.Instance, v *adt.Vertex) (errs errors.Error) { d := &externDecorator{ runtime: r, @@ -245,14 +245,15 @@ func (d *externDecorator) markExternFieldAttr(kind string, decls []ast.Decl) (er case *ast.Attribute: key, body := x.Split() - if key != "extern" { + // Support old-style and new-style extern attributes. + if key != "extern" && key != kind { break } lastField := len(fieldStack) - 1 if lastField < 0 { errs = errors.Append(errs, errors.Newf(x.Pos(), - "extern attribute not associated with field")) + "@%s attribute not associated with field", kind)) return true } @@ -260,15 +261,14 @@ func (d *externDecorator) markExternFieldAttr(kind string, decls []ast.Decl) (er if _, ok := d.fields[f]; ok { errs = errors.Append(errs, errors.Newf(x.Pos(), - "duplicate extern attributes")) + "duplicate @%s attributes", kind)) return true } - name, isIdent, err := ast.LabelName(f.Label) - if err != nil || !isIdent { + name, _, err := ast.LabelName(f.Label) + if err != nil { b, _ := format.Node(f.Label) - errs = errors.Append(errs, errors.Newf(x.Pos(), - "can only define functions for fields with identifier names, found %v", string(b))) + errs = errors.Append(errs, errors.Newf(x.Pos(), "external attribute has non-concrete label %s", b)) return true } @@ -331,7 +331,7 @@ func (d *externDecorator) processADTNode(n adt.Node, scope *adt.Vertex) bool { b, err := c.Compile(name, scope, &attr) if err != nil { - err = errors.Newf(info.attr.Pos(), "can't load from external module: %v", err) + err = errors.Wrap(errors.Newf(info.attr.Pos(), "@%s", info.extern), err) d.errs = errors.Append(d.errs, err) return true } diff --git a/vendor/cuelang.org/go/internal/core/runtime/imports.go b/vendor/cuelang.org/go/internal/core/runtime/imports.go index 4ac292c172..3059b86447 100644 --- a/vendor/cuelang.org/go/internal/core/runtime/imports.go +++ b/vendor/cuelang.org/go/internal/core/runtime/imports.go @@ -20,7 +20,9 @@ import ( "cuelang.org/go/cue/build" "cuelang.org/go/cue/errors" + "cuelang.org/go/internal" "cuelang.org/go/internal/core/adt" + "cuelang.org/go/internal/cueexperiment" ) type PackageFunc func(ctx adt.Runtime) (*adt.Vertex, errors.Error) @@ -42,7 +44,29 @@ func (x *index) RegisterBuiltin(importPath string, f PackageFunc) { x.builtinShort[base] = importPath } -var SharedRuntime = &Runtime{index: sharedIndex} +// We use a sync.OnceValue below so that cueexperiment.Init is only called +// the first time that the API is used, letting the user set $CUE_EXPERIMENT globally +// as part of their package init if they want to. +var SharedRuntime = sync.OnceValue(func() *Runtime { + r := &Runtime{index: sharedIndex} + // The version logic below is copied from [Runtime.Init]; + // consider refactoring to share the code if it gets any more complicated. + // + // TODO(mvdan,mpvl): Note that SharedRuntime follows the globally set evaluator version, + // which may be different than what was supplied via Go code for each context like + // via cuecontext.EvaluatorVersion(cuecontext.EvalV3). + // This does not cause issues between evalv2 and evalv3 as they use the same ADT, + // but future evaluator versions may not be compatible at that level. + // We should consider using one SharedRuntime per evaluator version, + // or getting rid of SharedRuntime altogether. + cueexperiment.Init() + if cueexperiment.Flags.EvalV3 { + r.version = internal.DevVersion + } else { + r.version = internal.DefaultVersion + } + return r +}) // BuiltinPackagePath converts a short-form builtin package identifier to its // full path or "" if this doesn't exist. diff --git a/vendor/cuelang.org/go/internal/core/runtime/resolve.go b/vendor/cuelang.org/go/internal/core/runtime/resolve.go index 59ab5f224d..843245864b 100644 --- a/vendor/cuelang.org/go/internal/core/runtime/resolve.go +++ b/vendor/cuelang.org/go/internal/core/runtime/resolve.go @@ -21,7 +21,6 @@ import ( "cuelang.org/go/cue/ast" "cuelang.org/go/cue/build" "cuelang.org/go/cue/errors" - "cuelang.org/go/internal" ) // TODO(resolve): this is also done in compile, do we need both? @@ -32,7 +31,7 @@ func (r *Runtime) ResolveFiles(p *build.Instance) (errs errors.Error) { // may be linked to any top-level entry of any of the files. allFields := map[string]ast.Node{} for _, f := range p.Files { - if p := internal.GetPackageInfo(f); p.IsAnonymous() { + if f.PackageName() == "" { continue } for _, d := range f.Decls { @@ -44,7 +43,7 @@ func (r *Runtime) ResolveFiles(p *build.Instance) (errs errors.Error) { } } for _, f := range p.Files { - if p := internal.GetPackageInfo(f); p.IsAnonymous() { + if f.PackageName() == "" { continue } err := resolveFile(idx, f, p, allFields) diff --git a/vendor/cuelang.org/go/internal/core/runtime/runtime.go b/vendor/cuelang.org/go/internal/core/runtime/runtime.go index 5b54015f02..cc1f71c931 100644 --- a/vendor/cuelang.org/go/internal/core/runtime/runtime.go +++ b/vendor/cuelang.org/go/internal/core/runtime/runtime.go @@ -17,7 +17,9 @@ package runtime import ( "cuelang.org/go/cue/build" "cuelang.org/go/internal" + "cuelang.org/go/internal/core/adt" "cuelang.org/go/internal/cuedebug" + "cuelang.org/go/internal/cueexperiment" ) // A Runtime maintains data structures for indexing and reuse for evaluation. @@ -30,7 +32,8 @@ type Runtime struct { // the kind in a file-level @extern(kind) attribute. interpreters map[string]Interpreter - version internal.EvaluatorVersion + version internal.EvaluatorVersion + topoSort bool flags cuedebug.Config } @@ -39,6 +42,12 @@ func (r *Runtime) Settings() (internal.EvaluatorVersion, cuedebug.Config) { return r.version, r.flags } +func (r *Runtime) ConfigureOpCtx(ctx *adt.OpContext) { + ctx.Version = r.version + ctx.TopoSort = r.topoSort + ctx.Config = r.flags +} + func (r *Runtime) SetBuildData(b *build.Instance, x interface{}) { r.loaded[b] = x } @@ -48,7 +57,8 @@ func (r *Runtime) BuildData(b *build.Instance) (x interface{}, ok bool) { return x, ok } -// New is a wrapper for NewVersioned(internal.DefaultVersion). +// New creates a new Runtime obeying the CUE_EXPERIMENT and CUE_DEBUG flags set +// via environment variables. func New() *Runtime { r := &Runtime{} r.Init() @@ -59,8 +69,11 @@ func New() *Runtime { // debug flags. The builtins registered with RegisterBuiltin are available for // evaluation. func NewWithSettings(v internal.EvaluatorVersion, flags cuedebug.Config) *Runtime { - r := &Runtime{version: v, flags: flags} - r.Init() + r := New() + // Override the evaluator version and debug flags derived from env vars + // with the explicit arguments given to us here. + r.version = v + r.SetDebugOptions(&flags) return r } @@ -70,10 +83,17 @@ func (r *Runtime) SetVersion(v internal.EvaluatorVersion) { r.version = v } +// SetTopologicalSort sets whether or not to use topological sorting +// for the Runtime. +func (r *Runtime) SetTopologicalSort(b bool) { + r.topoSort = b +} + // SetDebugOptions sets the debug flags to use for the Runtime. This should only // be set before first use. func (r *Runtime) SetDebugOptions(flags *cuedebug.Config) { r.flags = *flags + r.topoSort = r.topoSort || r.flags.SortFields } // IsInitialized reports whether the runtime has been initialized. @@ -93,4 +113,18 @@ func (r *Runtime) Init() { r.index.builtinShort = sharedIndex.builtinShort r.loaded = map[*build.Instance]interface{}{} + + cueexperiment.Init() + if cueexperiment.Flags.EvalV3 { + r.version = internal.DevVersion + } else { + r.version = internal.DefaultVersion + } + r.topoSort = cueexperiment.Flags.TopoSort + + // By default we follow the environment's CUE_DEBUG settings, + // which can be overriden via [Runtime.SetDebugOptions], + // such as with the API option [cuelang.org/go/cue/cuecontext.CUE_DEBUG]. + cuedebug.Init() + r.SetDebugOptions(&cuedebug.Flags) } diff --git a/vendor/cuelang.org/go/internal/core/subsume/subsume.go b/vendor/cuelang.org/go/internal/core/subsume/subsume.go index 82f522457b..e2a6a7901c 100644 --- a/vendor/cuelang.org/go/internal/core/subsume/subsume.go +++ b/vendor/cuelang.org/go/internal/core/subsume/subsume.go @@ -84,12 +84,6 @@ func (p *Profile) Value(ctx *adt.OpContext, a, b adt.Value) errors.Error { return nil // ignore errors here even if there are some. } -// Check reports whether b is an instance of a. -func (p *Profile) Check(ctx *adt.OpContext, a, b adt.Value) bool { - s := subsumer{ctx: ctx, Profile: *p} - return s.values(a, b) -} - func isBottom(x adt.Node) bool { b, _ := x.(*adt.Bottom) return b != nil @@ -138,7 +132,7 @@ func (s *subsumer) getError() (err errors.Error) { } err = s.errs if s.inexact { - err = internal.DecorateError(internal.ErrInexact, err) + err = errors.Wrap(err, internal.ErrInexact) } return err } diff --git a/vendor/cuelang.org/go/internal/core/subsume/value.go b/vendor/cuelang.org/go/internal/core/subsume/value.go index cdb5fdfcd8..8edbd6ad8b 100644 --- a/vendor/cuelang.org/go/internal/core/subsume/value.go +++ b/vendor/cuelang.org/go/internal/core/subsume/value.go @@ -103,7 +103,9 @@ func (s *subsumer) values(a, b adt.Value) (result bool) { case *adt.BuiltinValidator: state := s.ctx.PushState(s.ctx.Env(0), b.Source()) - b1 := s.ctx.Validate(x, b) + // TODO: is this always correct? + cx := adt.MakeRootConjunct(s.ctx.Env(0), x) + b1 := s.ctx.Validate(cx, b) if b1 != nil { s.errs = errors.Append(s.errs, b1.Err) } diff --git a/vendor/cuelang.org/go/internal/core/subsume/vertex.go b/vendor/cuelang.org/go/internal/core/subsume/vertex.go index f4465fd4d7..adb164296a 100644 --- a/vendor/cuelang.org/go/internal/core/subsume/vertex.go +++ b/vendor/cuelang.org/go/internal/core/subsume/vertex.go @@ -106,7 +106,7 @@ func (s *subsumer) vertices(x, y *adt.Vertex) bool { } // All arcs in x must exist in y and its values must subsume. - xFeatures := export.VertexFeatures(s.ctx, x) + xFeatures := export.VertexFeaturesUnsorted(x) for _, f := range xFeatures { if s.Final && !f.IsRegular() { continue @@ -183,7 +183,7 @@ func (s *subsumer) vertices(x, y *adt.Vertex) bool { return false } - yFeatures := export.VertexFeatures(s.ctx, y) + yFeatures := export.VertexFeaturesUnsorted(y) outer: for _, f := range yFeatures { if s.Final && !f.IsRegular() { @@ -221,7 +221,7 @@ outer: a := &adt.Vertex{Label: f} x.MatchAndInsert(ctx, a) - if len(a.Conjuncts) == 0 { + if !a.HasConjuncts() { // It is accepted and has no further constraints, so all good. continue } @@ -413,7 +413,7 @@ outer: a := &adt.Vertex{Label: f} x.MatchAndInsert(ctx, a) - if len(a.Conjuncts) == 0 { + if !a.HasConjuncts() { // It is accepted and has no further constraints, so all good. continue } diff --git a/vendor/cuelang.org/go/internal/core/toposort/cycles.go b/vendor/cuelang.org/go/internal/core/toposort/cycles.go new file mode 100644 index 0000000000..cd9b939bdd --- /dev/null +++ b/vendor/cuelang.org/go/internal/core/toposort/cycles.go @@ -0,0 +1,153 @@ +// Copyright 2024 CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package toposort + +import "slices" + +type ecNodeState struct { + visitedIncoming []*ecNodeState + blocked bool +} + +func (ecNode *ecNodeState) excluded() bool { + return ecNode == nil +} + +type ecFinderState struct { + cycles []*Cycle + stack []*Node +} + +type Cycle struct { + Nodes Nodes +} + +func (cycle *Cycle) RotateToStartAt(start *Node) { + nodes := cycle.Nodes + if start == nodes[0] { + return + } + for i, node := range nodes { + if start == node { + prefix := slices.Clone(nodes[:i]) + copy(nodes, nodes[i:]) + copy(nodes[len(nodes)-i:], prefix) + break + } + } +} + +// Calculate the Elementary Cycles (EC) within the current Strongly +// Connected Component (SCC). +// +// If the component contains no cycles (by definition, this means the +// component contains only a single node), then the slice returned +// will be empty. +// +// In general: +// +// 1. If a component contains two or more nodes then it contains at +// least one cycle. +// 2. A single node can be involved in many cycles. +// 3. This method finds all cycles within a component, but does not +// include cycles that are merely rotations of each +// other. I.e. every cycle is unique, ignoring rotations. +// 4. The cycles returned are unsorted: each cycle is itself in no +// particular rotation, and the complete slice of cycles is +// similarly unsorted. +// +// The complexity of this algorithm is O((n+e)*c) where +// - n: number of nodes in the SCC +// - e: number of edges between the nodes in the SCC +// - c: number of cycles discovered +// +// Donald B Johnson: Finding All the Elementary Circuits of a Directed +// Graph. SIAM Journal on Computing. Volumne 4, Nr. 1 (1975), +// pp. 77-84. +func (scc *StronglyConnectedComponent) ElementaryCycles() []*Cycle { + nodes := scc.Nodes + nodeStates := make([]ecNodeState, len(nodes)) + for i, node := range nodes { + node.ecNodeState = &nodeStates[i] + } + + ec := &ecFinderState{} + for i, node := range nodes { + ec.findCycles(node, node) + ec.unblockAll(nodes[i+1:]) + node.ecNodeState = nil + } + + return ec.cycles +} + +func (ec *ecFinderState) findCycles(origin, cur *Node) bool { + stackLen := len(ec.stack) + ec.stack = append(ec.stack, cur) + + curEc := cur.ecNodeState + curEc.blocked = true + + cycleFound := false + for _, next := range cur.Outgoing { + if next.ecNodeState.excluded() { + continue + } + if next == origin { // found cycle + ec.cycles = append(ec.cycles, &Cycle{Nodes: slices.Clone(ec.stack)}) + cycleFound = true + } else if !next.ecNodeState.blocked { + if ec.findCycles(origin, next) { + cycleFound = true + } + } + } + + if cycleFound { + ec.unblock(curEc) + } else { + for _, next := range cur.Outgoing { + if next.ecNodeState.excluded() { + continue + } + nextEc := next.ecNodeState + nextEc.visitedIncoming = append(nextEc.visitedIncoming, curEc) + } + } + + if len(ec.stack) != stackLen+1 { + panic("stack is unexpected height!") + } + ec.stack = ec.stack[:stackLen] + return cycleFound +} + +func (ec *ecFinderState) unblockAll(nodes Nodes) { + for _, node := range nodes { + nodeEc := node.ecNodeState + nodeEc.blocked = false + nodeEc.visitedIncoming = nodeEc.visitedIncoming[:0] + } +} + +func (ec *ecFinderState) unblock(nodeEc *ecNodeState) { + nodeEc.blocked = false + for _, previousEc := range nodeEc.visitedIncoming { + if previousEc.blocked { + ec.unblock(previousEc) + } + } + nodeEc.visitedIncoming = nodeEc.visitedIncoming[:0] +} diff --git a/vendor/cuelang.org/go/internal/core/toposort/graph.go b/vendor/cuelang.org/go/internal/core/toposort/graph.go new file mode 100644 index 0000000000..9d43b76962 --- /dev/null +++ b/vendor/cuelang.org/go/internal/core/toposort/graph.go @@ -0,0 +1,392 @@ +// Copyright 2024 CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package toposort + +import ( + "cmp" + "math" + "slices" + + "cuelang.org/go/internal/core/adt" +) + +const ( + NodeUnsorted = -1 + NodeInCurrentScc = -2 +) + +type Graph struct { + nodes Nodes +} + +type Node struct { + Feature adt.Feature + Outgoing Nodes + Incoming Nodes + structMeta *structMeta + // temporary state for calculating the Strongly Connected + // Components of a graph. + sccNodeState *sccNodeState + // temporary state for calculating the Elementary Cycles of a + // graph. + ecNodeState *ecNodeState + position int +} + +func (n *Node) IsSorted() bool { + return n.position >= 0 +} + +// SafeName returns a string useful for debugging, regardless of the +// type of the feature. So for IntLabels, you'll get back `1`, `10` +// etc; for identifiers, you may get back a string with quotes in it, +// eg `"runs-on"`. So this is not useful for comparisons, but it is +// useful (and safe) for debugging. +func (n *Node) SafeName(index adt.StringIndexer) string { + return n.Feature.SelectorString(index) +} + +type Nodes []*Node + +func (nodes Nodes) Features() []adt.Feature { + features := make([]adt.Feature, len(nodes)) + for i, node := range nodes { + features[i] = node.Feature + } + return features +} + +type edge struct { + from adt.Feature + to adt.Feature +} + +type GraphBuilder struct { + allowEdges bool + edgesSet map[edge]struct{} + nodesByFeature map[adt.Feature]*Node +} + +// NewGraphBuilder is the constructor for GraphBuilder. +// +// If you disallow edges, then nodes can still be added to the graph, +// and the [GraphBuilder.AddEdge] method will not error, but edges +// will never be added between nodes. This has the effect that +// topological ordering is not possible. +func NewGraphBuilder(allowEdges bool) *GraphBuilder { + return &GraphBuilder{ + allowEdges: allowEdges, + edgesSet: make(map[edge]struct{}), + nodesByFeature: make(map[adt.Feature]*Node), + } +} + +// Adds an edge between the two features. Nodes for the features will +// be created if they don't already exist. This method is idempotent: +// multiple calls with the same arguments will not create multiple +// edges, nor error. +func (builder *GraphBuilder) AddEdge(from, to adt.Feature) { + if !builder.allowEdges { + builder.EnsureNode(from) + builder.EnsureNode(to) + return + } + + edge := edge{from: from, to: to} + if _, found := builder.edgesSet[edge]; found { + return + } + + builder.edgesSet[edge] = struct{}{} + fromNode := builder.EnsureNode(from) + toNode := builder.EnsureNode(to) + fromNode.Outgoing = append(fromNode.Outgoing, toNode) + toNode.Incoming = append(toNode.Incoming, fromNode) +} + +// Ensure that a node for this feature exists. This is necessary for +// features that are not necessarily connected to any other feature. +func (builder *GraphBuilder) EnsureNode(feature adt.Feature) *Node { + node, found := builder.nodesByFeature[feature] + if !found { + node = &Node{Feature: feature, position: NodeUnsorted} + builder.nodesByFeature[feature] = node + } + return node +} + +func (builder *GraphBuilder) Build() *Graph { + nodesByFeature := builder.nodesByFeature + nodes := make(Nodes, 0, len(nodesByFeature)) + for _, node := range nodesByFeature { + nodes = append(nodes, node) + } + return &Graph{nodes: nodes} +} + +type indexComparison struct{ adt.StringIndexer } + +func (index *indexComparison) compareNodeByName(a, b *Node) int { + aFeature, bFeature := a.Feature, b.Feature + aIsInt, bIsInt := aFeature.Typ() == adt.IntLabel, bFeature.Typ() == adt.IntLabel + + switch { + case aIsInt && bIsInt: + return cmp.Compare(aFeature.Index(), bFeature.Index()) + case aIsInt: + return -1 + case bIsInt: + return 1 + default: + return cmp.Compare(aFeature.RawString(index), bFeature.RawString(index)) + } +} + +func (index *indexComparison) compareCyclesByNames(a, b *Cycle) int { + return slices.CompareFunc(a.Nodes, b.Nodes, index.compareNodeByName) +} + +func (index *indexComparison) compareComponentsByNodes(a, b *StronglyConnectedComponent) int { + return slices.CompareFunc(a.Nodes, b.Nodes, index.compareNodeByName) +} + +func chooseCycleEntryNode(cycle *Cycle) (entryNode *Node, enabledSince, brokenEdgeCount int) { + enabledSince = math.MaxInt + + for _, cycleNode := range cycle.Nodes { + if cycleNode.IsSorted() { + // this node is already in the sorted result + continue + } + NextNodeIncoming: + for _, incoming := range cycleNode.Incoming { + position := incoming.position + + if position < 0 { + // this predecessor node has not yet been added to the sorted + // result. + for _, cycleNode1 := range cycle.Nodes { + // ignore this predecessor node if it is part of this cycle. + if cycleNode1 == incoming { + continue NextNodeIncoming + } + } + brokenEdgeCount++ + continue NextNodeIncoming + } + + // this predecessor node must already be in the sorted output. + if position < enabledSince { + enabledSince = position + entryNode = cycleNode + } + } + } + return entryNode, enabledSince, brokenEdgeCount +} + +func chooseCycle(indexCmp *indexComparison, unusedCycles []*Cycle) *Cycle { + chosenCycleIdx := -1 + chosenCycleBrokenEdgeCount := math.MaxInt + chosenCycleEnabledSince := math.MaxInt + var chosenCycleEntryNode *Node + + for i, cycle := range unusedCycles { + if cycle == nil { + continue + } + debug("cycle %d: %v\n", i, cycle) + entryNode, enabledSince, brokenEdgeCount := chooseCycleEntryNode(cycle) + + if entryNode == nil { + entryNode = slices.MinFunc( + cycle.Nodes, indexCmp.compareNodeByName) + } + + debug("cycle %v; edgeCount %v; enabledSince %v; entryNode %v\n", + cycle, brokenEdgeCount, enabledSince, + entryNode.SafeName(indexCmp)) + + cycleIsBetter := chosenCycleIdx == -1 + // this is written out long-form for ease of readability + switch { + case cycleIsBetter: + // noop + case brokenEdgeCount < chosenCycleBrokenEdgeCount: + cycleIsBetter = true + case brokenEdgeCount > chosenCycleBrokenEdgeCount: + // noop - only continue if == + + case enabledSince < chosenCycleEnabledSince: + cycleIsBetter = true + case enabledSince > chosenCycleEnabledSince: + // noop - only continue if == + + case indexCmp.compareNodeByName(entryNode, chosenCycleEntryNode) < 0: + cycleIsBetter = true + case entryNode == chosenCycleEntryNode: + cycleIsBetter = + indexCmp.compareCyclesByNames(cycle, unusedCycles[chosenCycleIdx]) < 0 + } + + if cycleIsBetter { + chosenCycleIdx = i + chosenCycleBrokenEdgeCount = brokenEdgeCount + chosenCycleEnabledSince = enabledSince + chosenCycleEntryNode = entryNode + } + } + + if chosenCycleEntryNode == nil { + return nil + } + + debug("Chose cycle: %v; entering at node: %s\n", + unusedCycles[chosenCycleIdx], chosenCycleEntryNode.SafeName(indexCmp)) + cycle := unusedCycles[chosenCycleIdx] + unusedCycles[chosenCycleIdx] = nil + cycle.RotateToStartAt(chosenCycleEntryNode) + return cycle +} + +// Sort the features of the graph into a single slice. +// +// As far as possible, a topological sort is used. +// +// Whenever there is choice as to which feature should occur next, a +// lexicographical comparison is done, and minimum feature chosen. +// +// Whenever progress cannot be made due to needing to enter into +// cycles, the cycle to enter into, and the node of that cycle with +// which to start, is selected based on: +// +// 1. minimising the number of incoming edges that are violated +// 2. chosing a node which was reachable as early as possible +// 3. chosing a node with a smaller feature name (lexicographical) +func (graph *Graph) Sort(index adt.StringIndexer) []adt.Feature { + indexCmp := &indexComparison{index} + + nodesSorted := make(Nodes, 0, len(graph.nodes)) + + scc := graph.StronglyConnectedComponents() + var sccReady []*StronglyConnectedComponent + for _, component := range scc { + component.visited = false + slices.SortFunc(component.Nodes, indexCmp.compareNodeByName) + if len(component.Incoming) == 0 { + sccReady = append(sccReady, component) + } + } + slices.SortFunc(sccReady, indexCmp.compareComponentsByNodes) + + sccVisitedCount := 0 + for sccVisitedCount != len(scc) { + sccCurrent := sccReady[0] + sccReady = sccReady[1:] + if sccCurrent.visited { + continue + } + sccCurrent.visited = true + sccVisitedCount++ + debug("scc current: %p %v\n", sccCurrent, sccCurrent) + var cyclesCurrent []*Cycle + + var nodesReady Nodes + NextNode: + for _, node := range sccCurrent.Nodes { + node.position = NodeInCurrentScc + for _, required := range node.Incoming { + if !required.IsSorted() { + continue NextNode + } + } + nodesReady = append(nodesReady, node) + } + slices.SortFunc(nodesReady, indexCmp.compareNodeByName) + + requiredLen := len(nodesSorted) + len(sccCurrent.Nodes) + for requiredLen != len(nodesSorted) { + if len(nodesReady) == 0 { + debug("Stuck after: %v\n", nodesSorted) + if cyclesCurrent == nil { + cyclesCurrent = sccCurrent.ElementaryCycles() + debug("cycles current: %v\n", cyclesCurrent) + } + cycle := chooseCycle(indexCmp, cyclesCurrent) + if cycle == nil { + panic("No cycle found.") + } + nodesSorted, nodesReady = appendNodes( + indexCmp, nodesSorted, cycle.Nodes, nodesReady) + + } else { + nodesSorted, nodesReady = appendNodes( + indexCmp, nodesSorted, nodesReady[:1], nodesReady[1:]) + } + } + + sccReadyNeedsSorting := false + SccNextOutgoing: + for _, next := range sccCurrent.Outgoing { + for _, required := range next.Incoming { + if !required.visited { + continue SccNextOutgoing + } + } + sccReady = append(sccReady, next) + sccReadyNeedsSorting = true + } + if sccReadyNeedsSorting { + slices.SortFunc(sccReady, indexCmp.compareComponentsByNodes) + } + } + + return nodesSorted.Features() +} + +func appendNodes(indexCmp *indexComparison, nodesSorted, nodesReady, nodesEnabled Nodes) (nodesSortedOut, nodesEnabledOut Nodes) { + nodesReadyNeedsSorting := false + for _, node := range nodesReady { + if node.IsSorted() { + continue + } + node.position = len(nodesSorted) + nodesSorted = append(nodesSorted, node) + + NextOutgoing: + for _, next := range node.Outgoing { + if next.position != NodeInCurrentScc { + continue + } + for _, required := range next.Incoming { + if !required.IsSorted() { + continue NextOutgoing + } + } + debug("After %v, found new ready: %s\n", + nodesSorted, next.SafeName(indexCmp)) + nodesEnabled = append(nodesEnabled, next) + nodesReadyNeedsSorting = true + } + } + if nodesReadyNeedsSorting { + slices.SortFunc(nodesEnabled, indexCmp.compareNodeByName) + } + return nodesSorted, nodesEnabled +} + +func debug(formatting string, args ...any) { + // fmt.Printf(formatting, args...) +} diff --git a/vendor/cuelang.org/go/internal/core/toposort/scc.go b/vendor/cuelang.org/go/internal/core/toposort/scc.go new file mode 100644 index 0000000000..9f8f3ef707 --- /dev/null +++ b/vendor/cuelang.org/go/internal/core/toposort/scc.go @@ -0,0 +1,147 @@ +// Copyright 2024 CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package toposort + +import ( + "slices" +) + +type sccNodeState struct { + component *StronglyConnectedComponent + lowLink uint + index uint + visited bool + onStack bool +} + +type StronglyConnectedComponent struct { + Nodes Nodes + Outgoing []*StronglyConnectedComponent + Incoming []*StronglyConnectedComponent + visited bool +} + +// Calculate the Strongly Connected Components of the graph. +// https://en.wikipedia.org/wiki/Strongly_connected_component +// +// The components returned are topologically sorted (forwards), and +// form a DAG (this is the "condensation graph"). +func (graph *Graph) StronglyConnectedComponents() []*StronglyConnectedComponent { + nodeStates := make([]sccNodeState, len(graph.nodes)) + for i, node := range graph.nodes { + node.sccNodeState = &nodeStates[i] + } + + scc := &sccFinderState{} + for _, node := range graph.nodes { + if !node.sccNodeState.visited { + scc.findSCC(node) + } + } + + for _, node := range graph.nodes { + node.sccNodeState = nil + } + + components := scc.components + for _, component := range components { + for _, next := range component.Outgoing { + next.Incoming = append(next.Incoming, component) + } + } + slices.Reverse(components) + return components +} + +type sccFinderState struct { + components []*StronglyConnectedComponent + stack Nodes + counter uint +} + +// This is Tarjan's algorithm from 1972. +// +// Robert Tarjan: Depth-first search and linear graph algorithms. +// SIAM Journal on Computing. Volume 1, Nr. 2 (1972), pp. 146-160. +// +// https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm +func (scc *sccFinderState) findSCC(cur *Node) { + num := scc.counter + scc.counter++ + + curScc := cur.sccNodeState + curScc.lowLink = num + curScc.index = num + curScc.visited = true + curScc.onStack = true + + scc.stack = append(scc.stack, cur) + + for _, next := range cur.Outgoing { + nextScc := next.sccNodeState + if !nextScc.visited { + scc.findSCC(next) + curScc.lowLink = min(curScc.lowLink, nextScc.lowLink) + + } else if nextScc.onStack { + // If the next node is already on the stack, the edge joining + // the current node and the next node completes a cycle. + curScc.lowLink = min(curScc.lowLink, nextScc.index) + } + } + + // If the lowlink value of the node is equal to its DFS value, this + // is the head node of a strongly connected component that's shaped + // by the node and all nodes on the stack. + if curScc.lowLink == curScc.index { + component := &StronglyConnectedComponent{visited: true} + + var componentNodes Nodes + + for i := len(scc.stack) - 1; i >= 0; i-- { + nodeN := scc.stack[i] + nodeNScc := nodeN.sccNodeState + nodeNScc.onStack = false + nodeNScc.component = component + componentNodes = append(componentNodes, nodeN) + if nodeNScc == curScc { + scc.stack = scc.stack[:i] + break + } + } + + var outgoingComponents []*StronglyConnectedComponent + for _, node := range componentNodes { + for _, nextNode := range node.Outgoing { + // This algorithm is depth-first, which means we can rely + // on the next component always existing before our own + // component. + nextComponent := nextNode.sccNodeState.component + if !nextComponent.visited { + nextComponent.visited = true + outgoingComponents = append(outgoingComponents, nextComponent) + } + } + } + + component.Nodes = componentNodes + component.Outgoing = outgoingComponents + component.visited = false + for _, component := range outgoingComponents { + component.visited = false + } + scc.components = append(scc.components, component) + } +} diff --git a/vendor/cuelang.org/go/internal/core/toposort/vertex.go b/vendor/cuelang.org/go/internal/core/toposort/vertex.go new file mode 100644 index 0000000000..014eec8c73 --- /dev/null +++ b/vendor/cuelang.org/go/internal/core/toposort/vertex.go @@ -0,0 +1,530 @@ +// Copyright 2024 CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package toposort + +// Ultimately we need to build a graph of field names. Those field +// names can come from different constructions, such as: +// +// 1. Within a struct +// +// x: {z: _, y: _} +// +// When considering x, there should be a edge from z to y (written +// from now on as (z -> y)). +// +// 2. Explicit unification +// +// x: {z: _, y: _} & {x: _, w: _} +// +// When considering x, we want no edges between the arguments of the +// explicit unification operator '&'. There should only be edges (z +// -> y) and (x -> w). Through explicit unifications, cycles of field +// names can be introduced, e.g.: +// +// x: {z: _, y: _} & {y: _, w: _, z: _} +// +// 3. Embeddings +// +// b: {x: _, w: _} +// a: {z: _, y: _} +// c: { a, b } +// +// Here, a and b are embedded within c, and the order is important, so +// at a minimum we want edges (z -> y), (x -> w), and (y -> x). Other +// edges which don't introduce cycles are also acceptable (e.g. (z -> +// x), (y -> w) etc). +// +// 4. Implicit unification +// +// c: {z: _, y: _} +// c: {x: _, w: _} +// +// Here, like with embeddings, we choose that the source order is +// important, and so we must have a minimum of (z -> y), (x -> w) and +// (y -> x). +// +// Currently, the evaluator does not always provide enough information +// for us to be able to reliably identify all implicit unifications, +// especially where the ordering is enforced via some intermediate +// node. For example: +// +// a: { +// d: z: _ +// d: t: _ +// e: {x: _, w: _} +// } +// c: a.d & a.e +// +// Here, the information we get when sorting the fields of c (post +// evaluation), is insufficient to be able to establish the edge (z -> +// t), but it is sufficient to establish (x -> w). So in this case, we +// end up only with the edge (x -> w), and so the other field names +// fall back to lexicographical sorting. +// +// 5. Duplicates +// +// a: {z: _, y: _, z: int} +// +// b: c: _ +// b: d: _ +// b: c: int +// +// For a, we want to try to avoid adding an edge (y -> z), and for b +// we want to try to avoid adding an edge (d -> c). So within a +// regular struct, we do not add any additional edges when revisiting +// a declaration previously visited within the same struct. Similarly, +// for implicit unifications within the same file, we do not add any +// additional edges when revisiting a declaration. +// +// In order to get as close as possible to the desired ordering, we +// range over the Vertex's StructInfos, maintaining a list of Features +// which must come before any new Features, i.e. a frontier. For this +// to work, we need to sort the Vertex's StructInfos. Two approaches +// are used: +// +// 1. A topological sorting of a Vertex's StructInfos. This is +// effective for embeddings, and the relationship between embeddings +// and regular fields. For example: +// +// a: {y: _, x: _} +// b: {z: _, a} +// +// For b, a topological analysis will find that we can't enter the +// StructInfo containing y and x, until after we've processed the +// declaration of z. +// +// 2. However, even after a topological analysis, we'll often have +// many root StructInfos. We order these by source position (not the +// soure position of the StructInfo's StructLit itself, but of the +// references (if any) that resolved to the StructInfo's StructLit), +// then group them. If several StructInfos share the same position, +// then they are batched together and considered to be explictly +// unified. Then, consecutive batches of explicitly unified +// StructInfos are grouped together. +// +// The result is that explicit unification is correctly +// identified. E.g.: +// +// a: {x: _} +// b: {z: int} +// c: {y: >10} +// o: a & b & c +// +// for o, the StructInfos corresponding to a, b and c will all be +// grouped together in a single batch and considered to be explicitly +// unified. Also, structInfos that correspond to the same position +// (including no position) will be treated as explicity unified, and +// so no weight will be given to their relative position within the +// Vertex's slice of StructInfos. + +import ( + "fmt" + "slices" + + "cuelang.org/go/cue/token" + "cuelang.org/go/internal/core/adt" +) + +type structMeta struct { + structInfo *adt.StructInfo + pos token.Pos + + // Should this struct be considered to be part of an explicit + // unification (e.g. x & y)? + isExplicit bool + // Does this struct have no incoming edges? + isRoot bool +} + +func (sMeta *structMeta) String() string { + var sl *adt.StructLit + if sMeta.structInfo != nil { + sl = sMeta.structInfo.StructLit + } + return fmt.Sprintf("{%p sl:%p %v (explicit? %v; root? %v)}", + sMeta, sl, sMeta.pos, sMeta.isExplicit, sMeta.isRoot) +} + +func (sm *structMeta) hasDynamic(dynFieldsMap map[*adt.DynamicField][]adt.Feature) bool { + for _, decl := range sm.structInfo.Decls { + if dynField, ok := decl.(*adt.DynamicField); ok { + if _, found := dynFieldsMap[dynField]; found { + return true + } + } + } + return false +} + +// We need to order a Vertex's StructInfos. To do that, we want a +// filename+position for every StructInfo. +// +// We build a map from every StructInfo's StructLit and all its decls +// to a *structMeta, using the structLit's position. +// +// The StructLit in a StructInfo may directly appear in the parent's +// arc conjuncts. In this case, the StructLit's position is the +// correct position to use. But the StructLit may have been reached +// via a FieldReference, or SelectorExpr or something else. We want +// the position of the reference, and not the StructLit itself. E.g. +// +// a: {x: 5} +// b: {y: 7} +// c: b +// c: a +// +// If we're ordering the fields of c, we want the position of b and a +// on lines 3 and 4, not the StructLits which declare a and b on lines +// 1 and 2. To do this, we walk through the Vertex's Arc's +// conjuncts. If a conjunct's Field has been reached via some +// resolver, then the conjunct's Refs will record that, and will allow +// us to update the Field's position (and hence the StructLit's +// position) to that of the reference. +// +// Additionally, we need to discover whether each StructLit is +// included as a result of explicit unification (c: a & b), implicit +// unification: +// +// c: b +// c: a +// +// or embedding: +// +// c: { +// b +// a +// } +// +// Explicit unification needs treating specially so to avoid incorrect +// edges between the fields of the lhs and rhs of the &. To do this, +// we look at the vertex's conjuncts. If a conjunct is a binary +// expression &, then we look up the structMeta for the arguments to +// the binary expression, and mark them as explicit unification. +func analyseStructs(v *adt.Vertex, builder *GraphBuilder) ([]*structMeta, map[adt.Decl][]*structMeta) { + structInfos := v.Structs + nodeToStructMeta := make(map[adt.Node][]*structMeta) + structMetas := make([]structMeta, len(structInfos)) + + // First pass: make sure we create all the structMetas and map to + // them from a StructInfo's StructLit, and all its internal + // Decls. Assume everything is a root. Initial attempt at recording + // a position, which will be correct only for direct use of literal + // structs in the calculation of vertex v. + for i, s := range structInfos { + sl := s.StructLit + sMeta := &structMetas[i] + sMeta.structInfo = s + sMeta.isRoot = true + if src := sl.Source(); src != nil { + sMeta.pos = src.Pos() + } + nodeToStructMeta[sl] = append(nodeToStructMeta[sl], sMeta) + for _, decl := range sl.Decls { + nodeToStructMeta[decl] = append(nodeToStructMeta[decl], sMeta) + } + } + + roots := make([]*structMeta, 0, len(structMetas)) + outgoing := make(map[adt.Decl][]*structMeta) + // Second pass: build outgoing map based on the StructInfo + // parent-child relationship. Children are necessarily not roots. + for i := range structMetas { + sMeta := &structMetas[i] + parentDecl := sMeta.structInfo.Decl + if _, found := nodeToStructMeta[parentDecl]; found { + outgoing[parentDecl] = append(outgoing[parentDecl], sMeta) + sMeta.isRoot = false + } else { + roots = append(roots, sMeta) + } + } + + // If an arc's conjunct's Field is a node we care about, and it has + // been reached via resolution, then unwind those resolutions to + // uncover the position of the earliest reference. + for _, arc := range v.Arcs { + builder.EnsureNode(arc.Label) + arc.VisitLeafConjuncts(func(c adt.Conjunct) bool { + field := c.Field() + debug("self arc conjunct field %p :: %T, expr %p :: %T (%v)\n", + field, field, c.Expr(), c.Expr(), c.Expr().Source()) + sMetas, found := nodeToStructMeta[field] + if !found { + return true + } + if src := field.Source(); src != nil { + for _, sMeta := range sMetas { + sMeta.pos = src.Pos() + } + } + refs := c.CloseInfo.CycleInfo.Refs + if refs == nil { + return true + } + debug(" ref %p :: %T (%v)\n", + refs.Ref, refs.Ref, refs.Ref.Source().Pos()) + for refs.Next != nil { + refs = refs.Next + debug(" ref %p :: %T (%v)\n", + refs.Ref, refs.Ref, refs.Ref.Source().Pos()) + } + nodeToStructMeta[refs.Ref] = append(nodeToStructMeta[refs.Ref], sMetas...) + if pos := refs.Ref.Source().Pos(); pos != token.NoPos { + for _, sMeta := range nodeToStructMeta[refs.Ref] { + sMeta.pos = pos + } + } + + return true + }) + } + + // Explore our own conjuncts, and the decls from our StructList, to + // find explicit unifications, and mark structMetas accordingly. + var worklist []adt.Expr + v.VisitLeafConjuncts(func(c adt.Conjunct) bool { + debug("self conjunct field %p :: %T, expr %p :: %T\n", + c.Field(), c.Field(), c.Expr(), c.Expr()) + worklist = append(worklist, c.Expr()) + return true + }) + for _, si := range structInfos { + for _, decl := range si.StructLit.Decls { + if expr, ok := decl.(adt.Expr); ok { + worklist = append(worklist, expr) + } + } + } + + for len(worklist) != 0 { + expr := worklist[0] + worklist = worklist[1:] + + binExpr, ok := expr.(*adt.BinaryExpr) + if !ok || binExpr.Op != adt.AndOp { + continue + } + for _, expr := range []adt.Expr{binExpr.X, binExpr.Y} { + for _, sMeta := range nodeToStructMeta[expr] { + sMeta.isExplicit = true + debug(" now explicit: %v\n", sMeta) + } + } + worklist = append(worklist, binExpr.X, binExpr.Y) + } + + return roots, outgoing +} + +// Find all fields which have been created as a result of successful +// evaluation of a dynamic field name. +func dynamicFieldsFeatures(v *adt.Vertex) map[*adt.DynamicField][]adt.Feature { + var m map[*adt.DynamicField][]adt.Feature + for _, arc := range v.Arcs { + arc.VisitLeafConjuncts(func(c adt.Conjunct) bool { + if dynField, ok := c.Field().(*adt.DynamicField); ok { + if m == nil { + m = make(map[*adt.DynamicField][]adt.Feature) + } + m[dynField] = append(m[dynField], arc.Label) + } + return true + }) + } + return m +} + +type structMetaBatch []*structMeta + +func (batch structMetaBatch) isExplicit() bool { + return len(batch) > 1 || (len(batch) == 1 && batch[0].isExplicit) +} + +type structMetaBatches []structMetaBatch + +func (batchesPtr *structMetaBatches) appendBatch(batch structMetaBatch) { + if len(batch) == 0 { + return + } + batches := *batchesPtr + if l := len(batches); l == 0 { + *batchesPtr = append(batches, batch) + } else if prevBatch := batches[l-1]; batch.isExplicit() && + prevBatch.isExplicit() && + batch[0].pos.Filename() == prevBatch[0].pos.Filename() { + batches[l-1] = append(batches[l-1], batch...) + } else { + *batchesPtr = append(batches, batch) + } +} + +type vertexFeatures struct { + builder *GraphBuilder + dynFieldsMap map[*adt.DynamicField][]adt.Feature + outgoing map[adt.Decl][]*structMeta +} + +func (vf *vertexFeatures) compareStructMeta(a, b *structMeta) int { + if c := a.pos.Compare(b.pos); c != 0 { + return c + } + aHasDyn := a.hasDynamic(vf.dynFieldsMap) + bHasDyn := b.hasDynamic(vf.dynFieldsMap) + switch { + case aHasDyn == bHasDyn: + return 0 + case aHasDyn: + return 1 // gather dynamic fields at the end + default: + return -1 + } +} + +func VertexFeatures(ctx *adt.OpContext, v *adt.Vertex) []adt.Feature { + debug("\n*** V (%s %v %p) ***\n", v.Label.SelectorString(ctx), v.Label, v) + + builder := NewGraphBuilder(!ctx.Config.SortFields) + dynFieldsMap := dynamicFieldsFeatures(v) + roots, outgoing := analyseStructs(v, builder) + + vf := &vertexFeatures{ + builder: builder, + dynFieldsMap: dynFieldsMap, + outgoing: outgoing, + } + + slices.SortFunc(roots, vf.compareStructMeta) + debug("roots: %v\n", roots) + + var batches structMetaBatches + var batch structMetaBatch + for _, root := range roots { + if len(batch) == 0 || + (batch[0].pos == root.pos && !root.hasDynamic(dynFieldsMap)) { + batch = append(batch, root) + } else { + batches.appendBatch(batch) + batch = structMetaBatch{root} + } + } + batches.appendBatch(batch) + debug("batches: %v\n", batches) + + var previous, next []adt.Feature + var previousBatch structMetaBatch + for _, batch := range batches { + explicit := batch.isExplicit() + if len(previousBatch) != 0 && + previousBatch[0].pos.Filename() != batch[0].pos.Filename() { + previous = nil + } + for _, root := range batch { + root.isExplicit = explicit + debug("starting root. Explicit unification? %v\n", explicit) + next = append(next, vf.addEdges(previous, root)...) + } + previous = next + next = nil + previousBatch = batch + } + + debug("edges: %v\n", builder.edgesSet) + return builder.Build().Sort(ctx) +} + +func (vf *vertexFeatures) addEdges(previous []adt.Feature, sMeta *structMeta) []adt.Feature { + debug("--- S %p (%p :: %T) (sl: %p) (explicit? %v) ---\n", + sMeta, sMeta.structInfo.Decl, sMeta.structInfo.Decl, + sMeta.structInfo.StructLit, sMeta.isExplicit) + debug(" previous: %v\n", previous) + var next []adt.Feature + + filename := sMeta.pos.Filename() + debug(" filename: %s (%v)\n", filename, sMeta.pos) + + for i, decl := range sMeta.structInfo.Decls { + debug(" %p / %d: d (%p :: %T)\n", sMeta, i, decl, decl) + if bin, ok := decl.(*adt.BinaryExpr); ok { + debug(" binary expr: %p :: %T %v %p :: %T\n", + bin.X, bin.X, bin.Op, bin.Y, bin.Y) + } + + currentLabel := adt.InvalidLabel + switch decl := decl.(type) { + case *adt.Field: + currentLabel = decl.Label + debug(" value %p :: %T (%v)\n", decl.Value, decl.Value, decl.Value) + if src := decl.Value.Source(); src != nil { + debug(" field value source: %v\n", src.Pos()) + } + case *adt.DynamicField: + // This struct contains a dynamic field. If that dynamic + // field was successfully evaluated into a field, then insert + // that field into this chain. + if labels := vf.dynFieldsMap[decl]; len(labels) > 0 { + currentLabel = labels[0] + vf.dynFieldsMap[decl] = labels[1:] + } + } + if currentLabel != adt.InvalidLabel { + debug(" label %v\n", currentLabel) + + node, exists := vf.builder.nodesByFeature[currentLabel] + if exists && node.structMeta == sMeta { + // same field within the same structLit + debug(" skipping 1\n") + + } else if exists && !sMeta.isExplicit && sMeta.pos != token.NoPos && + node.structMeta != nil && + node.structMeta.pos.Filename() == filename { + // same field within the same file during implicit unification + debug(" skipping 2\n") + + } else { + debug(" %v %v\n", node, exists) + node = vf.builder.EnsureNode(currentLabel) + node.structMeta = sMeta + next = append(next, currentLabel) + for _, prevLabel := range previous { + vf.builder.AddEdge(prevLabel, currentLabel) + } + previous = next + next = nil + } + } + + if nextStructMetas := vf.outgoing[decl]; len(nextStructMetas) != 0 { + debug(" nextStructs: %v\n", nextStructMetas) + binExpr, isBinary := decl.(*adt.BinaryExpr) + isBinary = isBinary && binExpr.Op == adt.AndOp + + for _, sMeta := range nextStructMetas { + sMeta.isExplicit = isBinary + edges := vf.addEdges(previous, sMeta) + if isBinary { + next = append(next, edges...) + } else { + previous = edges + } + } + if isBinary { + previous = next + next = nil + } + } + } + + return previous +} diff --git a/vendor/cuelang.org/go/internal/core/validate/validate.go b/vendor/cuelang.org/go/internal/core/validate/validate.go index 08ee960aa4..4fba892236 100644 --- a/vendor/cuelang.org/go/internal/core/validate/validate.go +++ b/vendor/cuelang.org/go/internal/core/validate/validate.go @@ -57,6 +57,10 @@ func (v *validator) checkConcrete() bool { return v.Concrete && v.inDefinition == 0 } +func (v *validator) checkFinal() bool { + return (v.Concrete || v.Final) && v.inDefinition == 0 +} + func (v *validator) add(b *adt.Bottom) { if !v.AllErrors { v.err = adt.CombineErrors(nil, v.err, b) @@ -70,19 +74,19 @@ func (v *validator) add(b *adt.Bottom) { func (v *validator) validate(x *adt.Vertex) { defer v.ctx.PopArc(v.ctx.PushArc(x)) - // Dereference values, but only those that are non-rooted. This includes let + // Dereference values, but only those that are not shared. This includes let // values. This prevents us from processing structure-shared nodes more than // once and prevents potential cycles. - x = x.DerefNonRooted() + x = x.DerefNonShared() if b := x.Bottom(); b != nil { switch b.Code { case adt.CycleError: - if v.checkConcrete() || v.DisallowCycles { + if v.checkFinal() || v.DisallowCycles { v.add(b) } case adt.IncompleteError: - if v.checkConcrete() { + if v.checkFinal() { v.add(b) } diff --git a/vendor/cuelang.org/go/internal/core/walk/walk.go b/vendor/cuelang.org/go/internal/core/walk/walk.go index 88b7ef2d21..fb4ac6bf3e 100644 --- a/vendor/cuelang.org/go/internal/core/walk/walk.go +++ b/vendor/cuelang.org/go/internal/core/walk/walk.go @@ -35,9 +35,9 @@ type Visitor struct { // Feature is invoked for all field names. Feature func(f adt.Feature, src adt.Node) - // Before is invoked for all invoked for all nodes in pre-order traversal. - // Return false prevents the visitor from visiting the nodes descendant - // elements. + // Before is invoked for all nodes in pre-order traversal. + // Returning false prevents the visitor from visiting the node's + // children. Before func(adt.Node) bool } diff --git a/vendor/cuelang.org/go/internal/cueconfig/config.go b/vendor/cuelang.org/go/internal/cueconfig/config.go index 93587c5b05..e9b5894fc1 100644 --- a/vendor/cuelang.org/go/internal/cueconfig/config.go +++ b/vendor/cuelang.org/go/internal/cueconfig/config.go @@ -31,6 +31,10 @@ type RegistryLogin struct { // These fields mirror [oauth2.Token]. // We don't directly reference the type so we can be in control of our file format. // Note that Expiry is a pointer, so omitempty can work as intended. + // TODO(mvdan): drop the pointer once we can use json's omitzero: https://go.dev/issue/45669 + // Note that we store Expiry at rest as an absolute timestamp in UTC, + // rather than the ExpiresIn field following the RFC's wire format, + // a duration in seconds relative to the current time which is not useful at rest. AccessToken string `json:"access_token"` diff --git a/vendor/cuelang.org/go/internal/cuedebug/cuedebug.go b/vendor/cuelang.org/go/internal/cuedebug/cuedebug.go new file mode 100644 index 0000000000..089d0be4c4 --- /dev/null +++ b/vendor/cuelang.org/go/internal/cuedebug/cuedebug.go @@ -0,0 +1,81 @@ +package cuedebug + +import ( + "sync" + + "cuelang.org/go/internal/envflag" +) + +// Flags holds the set of global CUE_DEBUG flags. It is initialized by Init. +var Flags Config + +// Flags holds the set of known CUE_DEBUG flags. +// +// When adding, deleting, or modifying entries below, +// update cmd/cue/cmd/help.go as well for `cue help environment`. +type Config struct { + // HTTP enables JSON logging per HTTP request and response made + // when interacting with module registries. + HTTP bool + + // TODO: consider moving these evaluator-related options into a separate + // struct, so that it can be used in an API. We should use embedding, + // or some other mechanism, in that case to allow for the full set of + // allowed environment variables to be known. + + // Strict sets whether extra aggressive checking should be done. + // This should typically default to true for pre-releases and default to + // false otherwise. + Strict bool + + // LogEval sets the log level for the evaluator. + // There are currently only two levels: + // + // 0: no logging + // 1: logging + LogEval int + + // Sharing enables structure sharing. + Sharing bool `envflag:"default:true"` + + // SortFields forces fields in a struct to be sorted + // lexicographically. + SortFields bool + + // OpenInline permits disallowed fields to be selected into literal structs + // that would normally result in a close error. For instance, + // + // #D: {a: 1} + // x: (#D & {b: 2}).b // allow this + // + // This behavior was erroneously permitted in the v2 evaluator and was fixed + // in v3. This allows users that rely on this behavior to use v3. This + // option also discards closedness of the resulting expression. As was + // reported in Issue #3534, this was another erroneous behavior in v2 that + // is otherwise fixed in v3. + // + // To aid the transition to v3, this is enabled by default for now. + // + // A possible solution for both incompatibilities would be the introduction + // of an openAll builtin to recursive open up a cue value. For the first + // issue, the example above could be rewritten as: + // + // x: (openAll(#D) & {b: 2}).b + // + // For the second issue, to open up the entire result of an inline struct, + // such an expression could be written as `openAll(expr).out`. + OpenInline bool `envflag:"default:true"` +} + +// Init initializes Flags. Note: this isn't named "init" because we +// don't always want it to be called (for example we don't want it to be +// called when running "cue help"), and also because we want the failure +// mode to be one of error not panic, which would be the only option if +// it was a top level init function. +func Init() error { + return initOnce() +} + +var initOnce = sync.OnceValue(func() error { + return envflag.Init(&Flags, "CUE_DEBUG") +}) diff --git a/vendor/cuelang.org/go/internal/cuedebug/debug.go b/vendor/cuelang.org/go/internal/cuedebug/debug.go deleted file mode 100644 index 23751575ba..0000000000 --- a/vendor/cuelang.org/go/internal/cuedebug/debug.go +++ /dev/null @@ -1,47 +0,0 @@ -package cuedebug - -import ( - "sync" - - "cuelang.org/go/internal/envflag" -) - -// Flags holds the set of CUE_DEBUG flags. It is initialized by Init. -var Flags Config - -type Config struct { - HTTP bool - - // TODO: consider moving these evaluator-related options into a separate - // struct, so that it can be used in an API. We should use embedding, - // or some other mechanism, in that case to allow for the full set of - // allowed environment variables to be known. - - // Strict sets whether extra aggressive checking should be done. - // This should typically default to true for pre-releases and default to - // false otherwise. - Strict bool - - // LogEval sets the log level for the evaluator. - // There are currently only two levels: - // - // 0: no logging - // 1: logging - LogEval int - - // Sharing enables structure sharing. - Sharing bool `envflag:"default:true"` -} - -// Init initializes Flags. Note: this isn't named "init" because we -// don't always want it to be called (for example we don't want it to be -// called when running "cue help"), and also because we want the failure -// mode to be one of error not panic, which would be the only option if -// it was a top level init function. -func Init() error { - return initOnce() -} - -var initOnce = sync.OnceValue(func() error { - return envflag.Init(&Flags, "CUE_DEBUG") -}) diff --git a/vendor/cuelang.org/go/internal/cueexperiment/exp.go b/vendor/cuelang.org/go/internal/cueexperiment/exp.go index 71396a797b..0f7f59154c 100644 --- a/vendor/cuelang.org/go/internal/cueexperiment/exp.go +++ b/vendor/cuelang.org/go/internal/cueexperiment/exp.go @@ -6,20 +6,36 @@ import ( "cuelang.org/go/internal/envflag" ) -// Flags holds the set of CUE_EXPERIMENT flags. It is initialized by Init. +// Flags holds the set of global CUE_EXPERIMENT flags. It is initialized by Init. // // When adding, deleting, or modifying entries below, // update cmd/cue/cmd/help.go as well for `cue help environment`. var Flags struct { - Modules bool `envflag:"default:true"` - - // YAMLV3Decoder swaps the old internal/third_party/yaml decoder with the new - // decoder implemented in internal/encoding/yaml on top of yaml.v3. - YAMLV3Decoder bool `envflag:"default:true"` - // EvalV3 enables the new evaluator. The new evaluator addresses various // performance concerns. EvalV3 bool + + // Embed enables file embedding. + Embed bool `envflag:"default:true"` + + // DecodeInt64 changes [cuelang.org/go/cue.Value.Decode] to choose + // `int64` rather than `int` as the default type for CUE integer values + // to ensure consistency with 32-bit platforms. + DecodeInt64 bool `envflag:"default:true"` + + // Enable topological sorting of struct fields. + TopoSort bool `envflag:"default:true"` + + // The flags below describe completed experiments; they can still be set + // as long as the value aligns with the final behavior once the experiment finished. + // Breaking users who set such a flag seems unnecessary, + // and it simplifies using the same experiment flags across a range of CUE versions. + + // Modules was an experiment which ran from early 2023 to late 2024. + Modules bool `envflag:"deprecated,default:true"` + + // YAMLV3Decoder was an experiment which ran from early 2024 to late 2024. + YAMLV3Decoder bool `envflag:"deprecated,default:true"` } // Init initializes Flags. Note: this isn't named "init" because we @@ -31,8 +47,6 @@ func Init() error { return initOnce() } -var initOnce = sync.OnceValue(initAlways) - -func initAlways() error { +var initOnce = sync.OnceValue(func() error { return envflag.Init(&Flags, "CUE_EXPERIMENT") -} +}) diff --git a/vendor/cuelang.org/go/internal/cueversion/version.go b/vendor/cuelang.org/go/internal/cueversion/version.go index 4e9541275e..73fc5622f9 100644 --- a/vendor/cuelang.org/go/internal/cueversion/version.go +++ b/vendor/cuelang.org/go/internal/cueversion/version.go @@ -17,7 +17,7 @@ import ( // This determines the latest version of CUE that // is accepted by the module. func LanguageVersion() string { - return "v0.9.2" + return "v0.12.0" } // ModuleVersion returns the version of the cuelang.org/go module as best as can diff --git a/vendor/cuelang.org/go/internal/encoding/encoder.go b/vendor/cuelang.org/go/internal/encoding/encoder.go index 00aa7ef953..ac8f83ffa5 100644 --- a/vendor/cuelang.org/go/internal/encoding/encoder.go +++ b/vendor/cuelang.org/go/internal/encoding/encoder.go @@ -32,9 +32,10 @@ import ( "cuelang.org/go/encoding/openapi" "cuelang.org/go/encoding/protobuf/jsonpb" "cuelang.org/go/encoding/protobuf/textproto" + "cuelang.org/go/encoding/toml" + "cuelang.org/go/encoding/yaml" "cuelang.org/go/internal" "cuelang.org/go/internal/filetypes" - "cuelang.org/go/pkg/encoding/yaml" ) // An Encoder converts CUE to various file formats, including CUE itself. @@ -68,10 +69,7 @@ func (e Encoder) Close() error { // NewEncoder writes content to the file with the given specification. func NewEncoder(ctx *cue.Context, f *build.File, cfg *Config) (*Encoder, error) { - w, close, err := writer(f, cfg) - if err != nil { - return nil, err - } + w, close := writer(f, cfg) e := &Encoder{ ctx: ctx, cfg: cfg, @@ -147,11 +145,14 @@ func NewEncoder(ctx *cue.Context, f *build.File, cfg *Config) (*Encoder, error) // with a newline. f := internal.ToFile(n) if e.cfg.PkgName != "" && f.PackageName() == "" { - f.Decls = append([]ast.Decl{ - &ast.Package{ - Name: ast.NewIdent(e.cfg.PkgName), - }, - }, f.Decls...) + pkg := &ast.Package{ + PackagePos: token.NoPos.WithRel(token.NewSection), + Name: ast.NewIdent(e.cfg.PkgName), + } + doc, rest := internal.FileComments(f) + ast.SetComments(pkg, doc) + ast.SetComments(f, rest) + f.Decls = append([]ast.Decl{pkg}, f.Decls...) } b, err := format.Node(f, opts...) if err != nil { @@ -181,20 +182,26 @@ func NewEncoder(ctx *cue.Context, f *build.File, cfg *Config) (*Encoder, error) case build.YAML: e.concrete = true streamed := false + // TODO(mvdan): use a NewEncoder API like in TOML below. e.encValue = func(v cue.Value) error { if streamed { fmt.Fprintln(w, "---") } streamed = true - str, err := yaml.Marshal(v) + b, err := yaml.Encode(v) if err != nil { return err } - _, err = fmt.Fprint(w, str) + _, err = w.Write(b) return err } + case build.TOML: + e.concrete = true + enc := toml.NewEncoder(w) + e.encValue = enc.Encode + case build.TextProto: // TODO: verify that the schema is given. Otherwise err out. e.concrete = true @@ -283,16 +290,16 @@ func (e *Encoder) encodeFile(f *ast.File, interpret func(cue.Value) (*ast.File, return e.encValue(v) } -func writer(f *build.File, cfg *Config) (_ io.Writer, close func() error, err error) { +func writer(f *build.File, cfg *Config) (_ io.Writer, close func() error) { if cfg.Out != nil { - return cfg.Out, nil, nil + return cfg.Out, nil } path := f.Filename if path == "-" { if cfg.Stdout == nil { - return os.Stdout, nil, nil + return os.Stdout, nil } - return cfg.Stdout, nil, nil + return cfg.Stdout, nil } // Delay opening the file until we can write it to completion. // This prevents clobbering the file in case of a crash. @@ -303,7 +310,7 @@ func writer(f *build.File, cfg *Config) (_ io.Writer, close func() error, err er // Swap O_EXCL for O_TRUNC to allow replacing an entire existing file. mode = os.O_WRONLY | os.O_CREATE | os.O_TRUNC } - f, err := os.OpenFile(path, mode, 0o644) + f, err := os.OpenFile(path, mode, 0o666) if err != nil { if errors.Is(err, fs.ErrExist) { return errors.Wrapf(fs.ErrExist, token.NoPos, "error writing %q", path) @@ -316,5 +323,5 @@ func writer(f *build.File, cfg *Config) (_ io.Writer, close func() error, err er } return err } - return b, fn, nil + return b, fn } diff --git a/vendor/cuelang.org/go/internal/encoding/encoding.go b/vendor/cuelang.org/go/internal/encoding/encoding.go index 2fb7e817e1..e2db48538a 100644 --- a/vendor/cuelang.org/go/internal/encoding/encoding.go +++ b/vendor/cuelang.org/go/internal/encoding/encoding.go @@ -13,15 +13,14 @@ // limitations under the License. // TODO: make this package public in cuelang.org/go/encoding -// once stabalized. +// once stabilized. package encoding import ( "fmt" "io" - "net/url" - "strings" + "maps" "cuelang.org/go/cue" "cuelang.org/go/cue/ast" @@ -37,6 +36,7 @@ import ( "cuelang.org/go/encoding/protobuf" "cuelang.org/go/encoding/protobuf/jsonpb" "cuelang.org/go/encoding/protobuf/textproto" + "cuelang.org/go/encoding/toml" "cuelang.org/go/internal" "cuelang.org/go/internal/encoding/yaml" "cuelang.org/go/internal/filetypes" @@ -56,19 +56,13 @@ type Decoder struct { expr ast.Expr file *ast.File filename string // may change on iteration for some formats - id string index int err error } -type interpretFunc func(cue.Value) (file *ast.File, id string, err error) +type interpretFunc func(cue.Value) (file *ast.File, err error) type rewriteFunc func(*ast.File) (file *ast.File, err error) -// ID returns a canonical identifier for the decoded object or "" if no such -// identifier could be found. -func (i *Decoder) ID() string { - return i.id -} func (i *Decoder) Filename() string { return i.filename } // Interpretation returns the current interpretation detected by Detect. @@ -109,7 +103,7 @@ func (i *Decoder) doInterpret() { i.err = err return } - i.file, i.id, i.err = i.interpretFunc(v) + i.file, i.err = i.interpretFunc(v) } } @@ -144,7 +138,7 @@ type Config struct { PkgName string // package name for files to generate Force bool // overwrite existing files - Strict bool + Strict bool // strict mode for jsonschema (deprecated) Stream bool // potentially write more than one document per file AllErrors bool @@ -160,6 +154,8 @@ type Config struct { // NewDecoder returns a stream of non-rooted data expressions. The encoding // type of f must be a data type, but does not have to be an encoding that // can stream. stdin is used in case the file is "-". +// +// This may change the contents of f. func NewDecoder(ctx *cue.Context, f *build.File, cfg *Config) *Decoder { if cfg == nil { cfg = &Config{} @@ -205,14 +201,15 @@ func NewDecoder(ctx *cue.Context, f *build.File, cfg *Config) *Decoder { case build.Auto: openAPI := openAPIFunc(cfg, f) jsonSchema := jsonSchemaFunc(cfg, f) - i.interpretFunc = func(v cue.Value) (file *ast.File, id string, err error) { + i.interpretFunc = func(v cue.Value) (file *ast.File, err error) { + switch i.interpretation = Detect(v); i.interpretation { case build.JSONSchema: return jsonSchema(v) case build.OpenAPI: return openAPI(v) } - return i.file, "", i.err + return i.file, i.err } case build.OpenAPI: i.interpretation = build.OpenAPI @@ -239,7 +236,17 @@ func NewDecoder(ctx *cue.Context, f *build.File, cfg *Config) *Decoder { if i.err == nil { i.doInterpret() } - case build.JSON, build.JSONL: + case build.JSON: + b, err := io.ReadAll(r) + if err != nil { + i.err = err + break + } + i.expr, i.err = json.Extract(path, b) + if i.err == nil { + i.doInterpret() + } + case build.JSONL: i.next = json.NewDecoder(nil, path, r).Extract i.Next() case build.YAML: @@ -247,6 +254,9 @@ func NewDecoder(ctx *cue.Context, f *build.File, cfg *Config) *Decoder { i.err = err i.next = yaml.NewDecoder(path, b).Decode i.Next() + case build.TOML: + i.next = toml.NewDecoder(path, r).Decode + i.Next() case build.Text: b, err := io.ReadAll(r) i.err = err @@ -277,39 +287,43 @@ func NewDecoder(ctx *cue.Context, f *build.File, cfg *Config) *Decoder { } func jsonSchemaFunc(cfg *Config, f *build.File) interpretFunc { - return func(v cue.Value) (file *ast.File, id string, err error) { - id = f.Tags["id"] - if id == "" { - id, _ = v.LookupPath(cue.MakePath(cue.Str("$id"))).String() - } - if id != "" { - u, err := url.Parse(id) - if err != nil { - return nil, "", errors.Wrapf(err, token.NoPos, "invalid id") - } - u.Scheme = "" - id = strings.TrimPrefix(u.String(), "//") - } + return func(v cue.Value) (file *ast.File, err error) { + tags := boolTagsForFile(f, build.JSONSchema) cfg := &jsonschema.Config{ - ID: id, PkgName: cfg.PkgName, - Strict: cfg.Strict, + // Note: we don't populate Strict because then we'd + // be ignoring the values of the other tags when it's true, + // and there's (deliberately) nothing that Strict does that + // cannot be described by the other two keywords. + // The strictKeywords and strictFeatures tags are + // set by internal/filetypes from the strict tag when appropriate. + + StrictKeywords: cfg.Strict || tags["strictKeywords"], + StrictFeatures: cfg.Strict || tags["strictFeatures"], } file, err = jsonschema.Extract(v, cfg) // TODO: simplify currently erases file line info. Reintroduce after fix. // file, err = simplify(file, err) - return file, id, err + return file, err } } func openAPIFunc(c *Config, f *build.File) interpretFunc { - cfg := &openapi.Config{PkgName: c.PkgName} - return func(v cue.Value) (file *ast.File, id string, err error) { - file, err = openapi.Extract(v, cfg) + return func(v cue.Value) (file *ast.File, err error) { + tags := boolTagsForFile(f, build.JSONSchema) + file, err = openapi.Extract(v, &openapi.Config{ + PkgName: c.PkgName, + + // Note: don't populate Strict (see more detailed + // comment in jsonSchemaFunc) + + StrictKeywords: c.Strict || tags["strictKeywords"], + StrictFeatures: c.Strict || tags["strictFeatures"], + }) // TODO: simplify currently erases file line info. Reintroduce after fix. // file, err = simplify(file, err) - return file, "", err + return file, err } } @@ -323,6 +337,37 @@ func protobufJSONFunc(cfg *Config, file *build.File) rewriteFunc { } } +func boolTagsForFile(f *build.File, interp build.Interpretation) map[string]bool { + if f.Interpretation != build.Auto { + return f.BoolTags + } + defaultTags := filetypes.DefaultTagsForInterpretation(interp, filetypes.Input) + if len(defaultTags) == 0 { + return f.BoolTags + } + // We _could_ probably mutate f.Tags directly, but that doesn't + // seem quite right as it's been passed in from outside of internal/encoding. + // So go the extra mile and make a new map. + + // Set values for tags that have a default value but aren't + // present in f.Tags. + var tags map[string]bool + for tag, val := range defaultTags { + if _, ok := f.BoolTags[tag]; ok { + continue + } + if tags == nil { + tags = make(map[string]bool) + } + tags[tag] = val + } + if tags == nil { + return f.BoolTags + } + maps.Copy(tags, f.BoolTags) + return tags +} + func shouldValidate(i *filetypes.FileInfo) bool { // TODO: We ignore attributes for now. They should be enabled by default. return false || diff --git a/vendor/cuelang.org/go/internal/encoding/json/encode.go b/vendor/cuelang.org/go/internal/encoding/json/encode.go index 40c2efdb9b..7d6a11dcd7 100644 --- a/vendor/cuelang.org/go/internal/encoding/json/encode.go +++ b/vendor/cuelang.org/go/internal/encoding/json/encode.go @@ -17,15 +17,6 @@ package json import ( "bytes" "encoding/json" - "math/big" - "strings" - - "cuelang.org/go/cue/ast" - "cuelang.org/go/cue/errors" - "cuelang.org/go/cue/literal" - "cuelang.org/go/cue/token" - "cuelang.org/go/internal" - "cuelang.org/go/internal/astinternal" ) // Marshal is a replacement for [json.Marshal] without HTML escaping. @@ -41,282 +32,3 @@ func Marshal(v any) ([]byte, error) { p = bytes.TrimSuffix(p, []byte("\n")) return p, nil } - -// Encode converts a CUE AST to unescaped JSON. -// -// The given file must only contain values that can be directly supported by -// JSON: -// -// Type Restrictions -// BasicLit -// File no imports, aliases, or definitions -// StructLit no embeddings, aliases, or definitions -// List -// Field must be regular; label must be a BasicLit or Ident -// -// Comments and attributes are ignored. -func Encode(n ast.Node) (b []byte, err error) { - e := encoder{} - err = e.encode(n) - if err != nil { - return nil, err - } - return e.w.Bytes(), nil -} - -type encoder struct { - w bytes.Buffer - tab []byte - indentsAtLevel []int - indenting bool - unIndenting int -} - -func (e *encoder) writeIndent(b byte) { - if e.indenting { - e.indentsAtLevel[len(e.indentsAtLevel)-1]++ - } else { - e.indentsAtLevel = append(e.indentsAtLevel, 0) - } - e.indenting = true - _ = e.w.WriteByte(b) -} - -func (e *encoder) writeUnindent(b byte, pos, def token.Pos) { - if e.unIndenting > 0 { - e.unIndenting-- - } else { - e.unIndenting = e.indentsAtLevel[len(e.indentsAtLevel)-1] - e.indentsAtLevel = e.indentsAtLevel[:len(e.indentsAtLevel)-1] - } - e.indenting = false - e.ws(pos, def.RelPos()) - _ = e.w.WriteByte(b) -} - -func (e *encoder) writeString(s string) { - _, _ = e.w.WriteString(s) - e.indenting = false -} - -func (e *encoder) writeByte(b byte) { - _ = e.w.WriteByte(b) -} - -func (e *encoder) write(b []byte) { - _, _ = e.w.Write(b) - e.indenting = false -} - -func (e *encoder) indent() { - for range e.indentsAtLevel { - e.write(e.tab) - } -} - -func (e *encoder) ws(pos token.Pos, default_ token.RelPos) { - rel := pos.RelPos() - if pos == token.NoPos { - rel = default_ - } - switch rel { - case token.NoSpace: - case token.Blank: - e.writeByte(' ') - case token.Newline: - e.writeByte('\n') - e.indent() - case token.NewSection: - e.writeString("\n\n") - e.indent() - } -} -func (e *encoder) encode(n ast.Node) error { - if e.tab == nil { - e.tab = []byte(" ") - } - const defPos = token.NoSpace - switch x := n.(type) { - case *ast.BasicLit: - e.ws(x.Pos(), defPos) - return e.encodeScalar(x, true) - - case *ast.ListLit: - e.ws(foldNewline(x.Pos()), token.NoRelPos) - if len(x.Elts) == 0 { - e.writeString("[]") - return nil - } - e.writeIndent('[') - for i, x := range x.Elts { - if i > 0 { - e.writeString(",") - } - if err := e.encode(x); err != nil { - return err - } - } - e.writeUnindent(']', x.Rbrack, compactNewline(x.Elts[0].Pos())) - return nil - - case *ast.StructLit: - e.ws(foldNewline(n.Pos()), token.NoRelPos) - return e.encodeDecls(x.Elts, x.Rbrace) - - case *ast.File: - return e.encodeDecls(x.Decls, token.NoPos) - - case *ast.UnaryExpr: - e.ws(foldNewline(x.Pos()), defPos) - l, ok := x.X.(*ast.BasicLit) - if ok && x.Op == token.SUB && (l.Kind == token.INT || l.Kind == token.FLOAT) { - e.writeByte('-') - return e.encodeScalar(l, false) - } - } - return errors.Newf(n.Pos(), "json: unsupported node %s (%T)", astinternal.DebugStr(n), n) -} - -func (e *encoder) encodeScalar(l *ast.BasicLit, allowMinus bool) error { - switch l.Kind { - case token.INT: - var x big.Int - return e.setNum(l, allowMinus, &x) - - case token.FLOAT: - var x big.Float - return e.setNum(l, allowMinus, &x) - - case token.TRUE: - e.writeString("true") - - case token.FALSE: - e.writeString("false") - - case token.NULL: - e.writeString("null") - - case token.STRING: - str, err := literal.Unquote(l.Value) - if err != nil { - return err - } - b, err := Marshal(str) - if err != nil { - return err - } - e.write(b) - - default: - return errors.Newf(l.Pos(), "unknown literal type %v", l.Kind) - } - return nil -} - -func (e *encoder) setNum(l *ast.BasicLit, allowMinus bool, x interface{}) error { - if !allowMinus && strings.HasPrefix(l.Value, "-") { - return errors.Newf(l.Pos(), "double minus not allowed") - } - var ni literal.NumInfo - if err := literal.ParseNum(l.Value, &ni); err != nil { - return err - } - e.writeString(ni.String()) - return nil -} - -// encodeDecls converts a sequence of declarations to a value. If it encounters -// an embedded value, it will return this expression. This is more relaxed for -// structs than is currently allowed for CUE, but the expectation is that this -// will be allowed at some point. The input would still be illegal CUE. -func (e *encoder) encodeDecls(decls []ast.Decl, endPos token.Pos) error { - var embed ast.Expr - var fields []*ast.Field - - for _, d := range decls { - switch x := d.(type) { - default: - return errors.Newf(x.Pos(), "json: unsupported node %s (%T)", astinternal.DebugStr(x), x) - - case *ast.Package: - if embed != nil || fields != nil { - return errors.Newf(x.Pos(), "invalid package clause") - } - continue - - case *ast.Field: - if !internal.IsRegularField(x) { - return errors.Newf(x.TokenPos, "json: definition or hidden field not allowed") - } - if x.Optional != token.NoPos { - return errors.Newf(x.Optional, "json: optional fields not allowed") - } - fields = append(fields, x) - - case *ast.EmbedDecl: - if embed != nil { - return errors.Newf(x.Pos(), "json: multiple embedded values") - } - embed = x.Expr - - case *ast.CommentGroup: - } - } - - if embed != nil { - if fields != nil { - return errors.Newf(embed.Pos(), "json: embedding mixed with fields") - } - return e.encode(embed) - } - - if len(fields) == 0 { - e.writeString("{}") - return nil - } - - e.writeIndent('{') - pos := compactNewline(fields[0].Pos()) - if endPos == token.NoPos && pos.RelPos() == token.Blank { - pos = token.NoPos - } - firstPos := pos - const defPos = token.NoRelPos - for i, x := range fields { - if i > 0 { - e.writeByte(',') - pos = x.Pos() - } - name, _, err := ast.LabelName(x.Label) - if err != nil { - return errors.Newf(x.Label.Pos(), "json: only literal labels allowed") - } - b, err := Marshal(name) - if err != nil { - return err - } - e.ws(pos, defPos) - e.write(b) - e.writeByte(':') - - if err := e.encode(x.Value); err != nil { - return err - } - } - e.writeUnindent('}', endPos, firstPos) - return nil -} - -func compactNewline(pos token.Pos) token.Pos { - if pos.RelPos() == token.NewSection { - pos = token.Newline.Pos() - } - return pos -} - -func foldNewline(pos token.Pos) token.Pos { - if pos.RelPos() >= token.Newline { - pos = token.Blank.Pos() - } - return pos -} diff --git a/vendor/cuelang.org/go/internal/encoding/yaml/decode.go b/vendor/cuelang.org/go/internal/encoding/yaml/decode.go index 327b0908c4..bd8b4986a5 100644 --- a/vendor/cuelang.org/go/internal/encoding/yaml/decode.go +++ b/vendor/cuelang.org/go/internal/encoding/yaml/decode.go @@ -9,6 +9,7 @@ import ( "regexp" "strconv" "strings" + "sync" "gopkg.in/yaml.v3" @@ -16,8 +17,6 @@ import ( "cuelang.org/go/cue/literal" "cuelang.org/go/cue/token" "cuelang.org/go/internal" - "cuelang.org/go/internal/cueexperiment" - tpyaml "cuelang.org/go/internal/third_party/yaml" ) // TODO(mvdan): we should sanity check that the decoder always produces valid CUE, @@ -34,20 +33,6 @@ type Decoder interface { Decode() (ast.Expr, error) } -// NewDecoder is a temporary constructor compatible with both the old and new yaml decoders. -// Note that the signature matches the new yaml decoder, as the old signature can only error -// when reading a source that isn't []byte. -func NewDecoder(filename string, b []byte) Decoder { - if cueexperiment.Flags.YAMLV3Decoder { - return newDecoder(filename, b) - } - dec, err := tpyaml.NewDecoder(filename, b) - if err != nil { - panic(err) // should never happen as we give it []byte - } - return dec -} - // decoder wraps a [yaml.Decoder] to extract CUE syntax tree nodes. type decoder struct { yamlDecoder yaml.Decoder @@ -86,11 +71,11 @@ type decoder struct { // With json we can use RawMessage to know the size of the input // before we extract into ast.Expr, but unfortunately, yaml.Node has no size. -// newDecoder creates a decoder for YAML values to extract CUE syntax tree nodes. +// NewDecoder creates a decoder for YAML values to extract CUE syntax tree nodes. // // The filename is used for position information in CUE syntax tree nodes // as well as any errors encountered while decoding YAML. -func newDecoder(filename string, b []byte) *decoder { +func NewDecoder(filename string, b []byte) *decoder { // Note that yaml.v3 can insert a null node just past the end of the input // in some edge cases, so we pretend that there's an extra newline // so that we don't panic when handling such a position. @@ -120,10 +105,7 @@ func (d *decoder) Decode() (ast.Expr, error) { // If the input is empty, we produce a single null literal with EOF. // Note that when the input contains "---", we get an empty document // with a null scalar value inside instead. - // - // TODO(mvdan): the old decoder seemingly intended to do this, - // but returned a "null" literal with io.EOF, which consumers ignored. - if false && !d.yamlNonEmpty { + if !d.yamlNonEmpty { return &ast.BasicLit{ Kind: token.NULL, Value: "null", @@ -401,7 +383,7 @@ outer: if err != nil { return err } - d.addCommentsToNode(label, yk, 1) + d.addCommentsToNode(field, yk, 2) field.Label = label if mergeValues { @@ -496,7 +478,9 @@ const ( // rxAnyOctalYaml11 uses the implicit tag resolution regular expression for base-8 integers // from YAML's 1.1 spec, but including the 8 and 9 digits which aren't valid for octal integers. -var rxAnyOctalYaml11 = regexp.MustCompile(`^[-+]?0[0-9_]+$`) +var rxAnyOctalYaml11 = sync.OnceValue(func() *regexp.Regexp { + return regexp.MustCompile(`^[-+]?0[0-9_]+$`) +}) func (d *decoder) scalar(yn *yaml.Node) (ast.Expr, error) { tag := yn.ShortTag() @@ -504,7 +488,7 @@ func (d *decoder) scalar(yn *yaml.Node) (ast.Expr, error) { // and the value looks like a YAML 1.1 octal literal, // that means the input value was like `01289` and not a valid octal integer. // The safest thing to do, and what most YAML decoders do, is to interpret as a string. - if yn.Style&yaml.TaggedStyle == 0 && tag == floatTag && rxAnyOctalYaml11.MatchString(yn.Value) { + if yn.Style&yaml.TaggedStyle == 0 && tag == floatTag && rxAnyOctalYaml11().MatchString(yn.Value) { tag = strTag } switch tag { diff --git a/vendor/cuelang.org/go/internal/encoding/yaml/encode.go b/vendor/cuelang.org/go/internal/encoding/yaml/encode.go index 87aec6e417..be970c90e9 100644 --- a/vendor/cuelang.org/go/internal/encoding/yaml/encode.go +++ b/vendor/cuelang.org/go/internal/encoding/yaml/encode.go @@ -21,6 +21,7 @@ import ( "math/big" "regexp" "strings" + "sync" "gopkg.in/yaml.v3" @@ -159,12 +160,14 @@ func encodeScalar(b *ast.BasicLit) (n *yaml.Node, err error) { // shouldQuote indicates that a string may be a YAML 1.1. legacy value and that // the string should be quoted. func shouldQuote(str string) bool { - return legacyStrings[str] || useQuote.MatchString(str) + return legacyStrings[str] || useQuote().MatchString(str) } // This regular expression conservatively matches any date, time string, // or base60 float. -var useQuote = regexp.MustCompile(`^[\-+0-9:\. \t]+([-:]|[tT])[\-+0-9:\. \t]+[zZ]?$|^0x[a-fA-F0-9]+$`) +var useQuote = sync.OnceValue(func() *regexp.Regexp { + return regexp.MustCompile(`^[\-+0-9:\. \t]+([-:]|[tT])[\-+0-9:\. \t]+[zZ]?$|^0x[a-fA-F0-9]+$`) +}) // legacyStrings contains a map of fixed strings with special meaning for any // type in the YAML Tag registry (https://yaml.org/type/index.html) as used diff --git a/vendor/cuelang.org/go/internal/envflag/flag.go b/vendor/cuelang.org/go/internal/envflag/flag.go index 4c640ffafd..3b57ea9fb9 100644 --- a/vendor/cuelang.org/go/internal/envflag/flag.go +++ b/vendor/cuelang.org/go/internal/envflag/flag.go @@ -24,6 +24,10 @@ func Init[T any](flags *T, envVar string) error { // The struct field tag may contain a default value other than the zero value, // such as `envflag:"default:true"` to set a boolean field to true by default. // +// The tag may be marked as deprecated with `envflag:"deprecated"` +// which will cause Parse to return an error if the user attempts to set +// its value to anything but the default value. +// // The string may contain a comma-separated list of name=value pairs values // representing the boolean fields in the struct type T. If the value is omitted // entirely, the value is assumed to be name=true. @@ -34,25 +38,35 @@ func Init[T any](flags *T, envVar string) error { func Parse[T any](flags *T, env string) error { // Collect the field indices and set the default values. indexByName := make(map[string]int) + deprecated := make(map[string]bool) fv := reflect.ValueOf(flags).Elem() ft := fv.Type() for i := 0; i < ft.NumField(); i++ { field := ft.Field(i) + name := strings.ToLower(field.Name) defaultValue := false if tagStr, ok := field.Tag.Lookup("envflag"); ok { - defaultStr, ok := strings.CutPrefix(tagStr, "default:") - // TODO: consider panicking for these error types. - if !ok { - return fmt.Errorf("expected tag like `envflag:\"default:true\"`: %s", tagStr) - } - v, err := strconv.ParseBool(defaultStr) - if err != nil { - return fmt.Errorf("invalid default bool value for %s: %v", field.Name, err) + for _, f := range strings.Split(tagStr, ",") { + key, rest, hasRest := strings.Cut(f, ":") + switch key { + case "default": + v, err := strconv.ParseBool(rest) + if err != nil { + return fmt.Errorf("invalid default bool value for %s: %v", field.Name, err) + } + defaultValue = v + fv.Field(i).SetBool(defaultValue) + case "deprecated": + if hasRest { + return fmt.Errorf("cannot have a value for deprecated tag") + } + deprecated[name] = true + default: + return fmt.Errorf("unknown envflag tag %q", f) + } } - defaultValue = v - fv.Field(i).SetBool(defaultValue) } - indexByName[strings.ToLower(field.Name)] = i + indexByName[name] = i } if env == "" { @@ -67,7 +81,7 @@ func Parse[T any](flags *T, env string) error { v, err := strconv.ParseBool(valueStr) if err != nil { // Invalid format, return an error immediately. - return invalidError{ + return errInvalid{ fmt.Errorf("invalid bool value for %s: %v", name, err), } } @@ -80,16 +94,26 @@ func Parse[T any](flags *T, env string) error { errs = append(errs, fmt.Errorf("unknown %s", elem)) continue } + if deprecated[name] { + // We allow setting deprecated flags to their default value so + // that bold explorers will not be penalised for their + // experimentation. + if fv.Field(index).Bool() != value { + errs = append(errs, fmt.Errorf("cannot change default value of deprecated flag %q", name)) + } + continue + } + fv.Field(index).SetBool(value) } return errors.Join(errs...) } -// An InvalidError indicates a malformed input string. -var InvalidError = errors.New("invalid value") +// An ErrInvalid indicates a malformed input string. +var ErrInvalid = errors.New("invalid value") -type invalidError struct{ error } +type errInvalid struct{ error } -func (invalidError) Is(err error) bool { - return err == InvalidError +func (errInvalid) Is(err error) bool { + return err == ErrInvalid } diff --git a/vendor/cuelang.org/go/internal/filetypes/filetypes.go b/vendor/cuelang.org/go/internal/filetypes/filetypes.go index 2d3139b58d..6330c0eedf 100644 --- a/vendor/cuelang.org/go/internal/filetypes/filetypes.go +++ b/vendor/cuelang.org/go/internal/filetypes/filetypes.go @@ -15,7 +15,9 @@ package filetypes import ( + "fmt" "path/filepath" + "strconv" "strings" "cuelang.org/go/cue" @@ -78,7 +80,7 @@ func FromFile(b *build.File, mode Mode) (*FileInfo, error) { // isolation without interference from evaluating these files. if mode == Input && b.Encoding == build.CUE && - b.Form == build.Schema && + b.Form == "" && b.Interpretation == "" { return &FileInfo{ File: b, @@ -92,7 +94,6 @@ func FromFile(b *build.File, mode Mode) (*FileInfo, error) { KeepDefaults: true, Incomplete: true, Imports: true, - Stream: true, Docs: true, Attributes: true, }, nil @@ -175,25 +176,13 @@ func ParseArgs(args []string) (files []*build.File, err error) { if !fileVal.Exists() { if len(a) == 1 && strings.HasSuffix(a[0], ".cue") { // Handle majority case. - files = append(files, &build.File{ - Filename: a[0], - Encoding: build.CUE, - Form: build.Schema, - }) + f := *fileForCUE + f.Filename = a[0] + files = append(files, &f) hasFiles = true continue } - // The CUE command works just fine without this (how?), - // but the API tests require this for some reason. - // - // This is almost certainly wrong, and in the wrong place. - // - // TODO(aram): why do we need this here? - if len(a) == 1 && strings.HasSuffix(a[0], ".wasm") { - continue - } - modeVal, fileVal, err = parseType("", Input) if err != nil { return nil, err @@ -236,6 +225,27 @@ func ParseArgs(args []string) (files []*build.File, err error) { return files, nil } +// DefaultTagsForInterpretation returns any tags that would be set by default +// in the given interpretation in the given mode. +func DefaultTagsForInterpretation(interp build.Interpretation, mode Mode) map[string]bool { + if interp == "" { + return nil + } + // TODO this could be done once only. + + // This should never fail if called with a legitimate build.Interpretation constant. + + mv, fv, err := parseType(string(interp), mode) + if err != nil { + panic(err) + } + f, err := toFile(mv, fv, "-") + if err != nil { + panic(err) + } + return f.BoolTags +} + // ParseFile parses a single-argument file specifier, such as when a file is // passed to a command line argument. // @@ -260,18 +270,29 @@ func ParseFile(s string, mode Mode) (*build.File, error) { } return nil, errors.Newf(token.NoPos, "empty file name") } + + return ParseFileAndType(file, scope, mode) +} + +// ParseFileAndType parses a file and type combo. +func ParseFileAndType(file, scope string, mode Mode) (*build.File, error) { // Quickly discard files which we aren't interested in. // These cases are very common when loading `./...` in a large repository. typesInit() - if scope == "" { + if scope == "" && file != "-" { ext := fileExt(file) - if file == "-" { - // not handled here - } else if ext == "" { + if ext == "" { return nil, errors.Newf(token.NoPos, "no encoding specified for file %q", file) - } else if !knownExtensions[ext] { + } + f, ok := fileForExt[ext] + if !ok { return nil, errors.Newf(token.NoPos, "unknown file extension %s", ext) } + if mode == Input { + f1 := *f + f1.Filename = file + return &f1, nil + } } modeVal, fileVal, err := parseType(scope, mode) if err != nil { @@ -313,23 +334,59 @@ func toFile(modeVal, fileVal cue.Value, filename string) (*build.File, error) { func parseType(scope string, mode Mode) (modeVal, fileVal cue.Value, _ error) { modeVal = typesValue.LookupPath(cue.MakePath(cue.Str("modes"), cue.Str(mode.String()))) - fileVal = modeVal.LookupPath(cue.MakePath(cue.Str("File"))) + fileVal = modeVal.LookupPath(cue.MakePath(cue.Str("FileInfo"))) - if scope != "" { - for _, tag := range strings.Split(scope, "+") { - tagName, tagVal, ok := strings.Cut(tag, "=") - if ok { - fileVal = fileVal.FillPath(cue.MakePath(cue.Str("tags"), cue.Str(tagName)), tagVal) - } else { - info := typesValue.LookupPath(cue.MakePath(cue.Str("tags"), cue.Str(tag))) - if !info.Exists() { - return cue.Value{}, cue.Value{}, errors.Newf(token.NoPos, "unknown filetype %s", tag) - } + if scope == "" { + return modeVal, fileVal, nil + } + var otherTags []string + for _, tag := range strings.Split(scope, "+") { + tagName, _, ok := strings.Cut(tag, "=") + if ok { + otherTags = append(otherTags, tag) + } else { + info := typesValue.LookupPath(cue.MakePath(cue.Str("tagInfo"), cue.Str(tagName))) + if info.Exists() { fileVal = fileVal.Unify(info) + } else { + // The tag might only be available when all the + // other tags have been evaluated. + otherTags = append(otherTags, tag) } } } - + if len(otherTags) == 0 { + return modeVal, fileVal, nil + } + // There are tags that aren't mentioned in tagInfo. + // They might still be valid, but just only valid within the file types that + // have been specified above, so look at the schema that we've got + // and see if it specifies any tags. + allowedTags := fileVal.LookupPath(cue.MakePath(cue.Str("tags"))) + allowedBoolTags := fileVal.LookupPath(cue.MakePath(cue.Str("boolTags"))) + for _, tag := range otherTags { + tagName, tagVal, hasValue := strings.Cut(tag, "=") + tagNamePath := cue.MakePath(cue.Str(tagName)).Optional() + tagSchema := allowedTags.LookupPath(tagNamePath) + if tagSchema.Exists() { + fileVal = fileVal.FillPath(cue.MakePath(cue.Str("tags"), cue.Str(tagName)), tagVal) + continue + } + if !allowedBoolTags.LookupPath(tagNamePath).Exists() { + return cue.Value{}, cue.Value{}, errors.Newf(token.NoPos, "unknown filetype %s", tagName) + } + tagValBool := true + if hasValue { + // It's a boolean tag and an explicit value has been specified. + // Allow the usual boolean string values. + t, err := strconv.ParseBool(tagVal) + if err != nil { + return cue.Value{}, cue.Value{}, fmt.Errorf("invalid boolean value for tag %q", tagName) + } + tagValBool = t + } + fileVal = fileVal.FillPath(cue.MakePath(cue.Str("boolTags"), cue.Str(tagName)), tagValBool) + } return modeVal, fileVal, nil } diff --git a/vendor/cuelang.org/go/internal/filetypes/types.cue b/vendor/cuelang.org/go/internal/filetypes/types.cue index 9ebd42397b..3597c1a420 100644 --- a/vendor/cuelang.org/go/internal/filetypes/types.cue +++ b/vendor/cuelang.org/go/internal/filetypes/types.cue @@ -3,7 +3,7 @@ // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software @@ -26,12 +26,14 @@ package build encoding!: #Encoding interpretation?: #Interpretation form?: #Form + // Note: tags includes values for non-boolean tags only. tags?: [string]: string + boolTags?: [string]: bool } // Default is the file used for stdin and stdout. The settings depend // on the file mode. -#Default: #File & { +#Default: #FileInfo & { filename: *"-" | string } @@ -56,23 +58,27 @@ package build attributes?: bool // include/allow attributes } -// knownExtensions derives all the known file extensions -// from those that are mentioned in modes, -// allowing us to quickly discard files with unknown extensions. -knownExtensions: { - for mode in modes - for ext, _ in mode.extensions { - (ext): true - } -} +// fileForExtVanilla holds the extensions supported in +// input mode with scope="" - the most common form +// of file type to evaluate. +// +// It's also used as a source of truth for all known file +// extensions as all modes define attributes for +// all file extensions. If that ever changed, we'd need +// to change this. +fileForExtVanilla: modes.input.extensions // modes sets defaults for different operational modes. +// The key corresponds to the Go internal/filetypes.Mode type. modes: [string]: { - // TODO(mvdan): Document these once they are better understood. - // Perhaps make them required as well. - File: #File - FileInfo: #FileInfo - Default: #Default + // FileInfo holds the base file information for this mode. + // This will be unified with information derived from the + // file extension and any filetype tags explicitly provided. + FileInfo!: #FileInfo + + // Default holds the base file information for standard input + // or output, where we don't have any file extension available. + Default!: #Default } // input defines modes for input, such as import, eval, vet or def. @@ -92,6 +98,7 @@ modes: input: { extensions: ".json": interpretation: *"auto" | _ extensions: ".yaml": interpretation: *"auto" | _ extensions: ".yml": interpretation: *"auto" | _ + extensions: ".toml": interpretation: *"auto" | _ } modes: export: { @@ -102,23 +109,7 @@ modes: export: { docs: true | *false attributes: true | *false } - encodings: cue: { - *forms.data | _ - } -} - -// TODO(mvdan): this "output" mode appears to be unused at the moment. -modes: output: { - Default: { - encoding: *"cue" | _ - } - FileInfo: { - docs: true | *false - attributes: true | *false - } - encodings: cue: { - *forms.data | _ - } + encodings: cue: forms.data } // eval is a legacy mode @@ -130,9 +121,7 @@ modes: eval: { docs: true | *false attributes: true | *false } - encodings: cue: { - *forms.final | _ - } + encodings: cue: forms.final } modes: def: { @@ -143,9 +132,7 @@ modes: def: { docs: *true | false attributes: *true | false } - encodings: cue: { - *forms.schema | _ - } + encodings: cue: forms.schema } // A Encoding indicates a file format for representing a program. @@ -154,28 +141,34 @@ modes: def: { // An Interpretation determines how a certain program should be interpreted. // For instance, data may be interpreted as describing a schema, which itself // can be converted to a CUE schema. +// This corresponds to the Go cue/build.Interpretation type. #Interpretation: string -#Form: string + +// A Form specifies the form in which a program should be represented. +// It corresponds to the Go cue/build.Form type. +#Form: string modes: [string]: { // extensions maps a file extension to its associated default file properties. extensions: { // "": _ - ".cue": tags.cue - ".json": tags.json - ".jsonl": tags.jsonl - ".ldjson": tags.jsonl - ".ndjson": tags.jsonl - ".yaml": tags.yaml - ".yml": tags.yaml - ".txt": tags.text - ".go": tags.go - ".proto": tags.proto - ".textproto": tags.textproto - ".textpb": tags.textproto // perhaps also pbtxt + ".cue": tagInfo.cue + ".json": tagInfo.json + ".jsonl": tagInfo.jsonl + ".ldjson": tagInfo.jsonl + ".ndjson": tagInfo.jsonl + ".yaml": tagInfo.yaml + ".yml": tagInfo.yaml + ".toml": tagInfo.toml + ".txt": tagInfo.text + ".go": tagInfo.go + ".wasm": tagInfo.binary + ".proto": tagInfo.proto + ".textproto": tagInfo.textproto + ".textpb": tagInfo.textproto // perhaps also pbtxt // TODO: jsonseq, - // ".pb": tags.binpb // binarypb + // ".pb": tagInfo.binpb // binarypb } // encodings: "": error("no encoding specified") @@ -233,11 +226,6 @@ modes: [string]: { stream: false } - // encodings: binproto: { - // forms.DataEncoding - // encoding: "binproto" - // } - encodings: code: { forms.schema stream: false @@ -248,16 +236,15 @@ modes: [string]: { forms: [Name=string]: #FileInfo forms: schema: { - form: *"schema" | "final" | "graph" - stream: true | *false + form: *"schema" | "final" | "graph" + stream: true | *false incomplete: *true | false definitions: *true | false optional: *true | false constraints: *true | false keepDefaults: *true | false imports: *true | false - optional: *true | false } forms: final: { @@ -298,20 +285,31 @@ forms: data: { optional: false } -interpretations: [Name=string]: #FileInfo - -interpretations: auto: { - forms.schema +interpretations: [Name=string]: #FileInfo & { + interpretation: Name } +interpretations: auto: forms.schema + interpretations: jsonschema: { forms.schema encoding: *"json" | _ + boolTags: { + strict: *false | bool + strictKeywords: *strict | bool + // TODO(v0.12): enable strictFeatures by default + strictFeatures: *strict | bool + } } interpretations: openapi: { forms.schema encoding: *"json" | _ + boolTags: { + strict: *false | bool + strictKeywords: *strict | bool + strictFeatures: *strict | bool + } } interpretations: pb: { @@ -319,18 +317,18 @@ interpretations: pb: { stream: true } -// tags maps command line tags to file properties. -tags: { +// tagInfo maps command line tags to file properties. +tagInfo: { schema: form: "schema" graph: form: "graph" dag: form: "dag" data: form: "data" - cue: encoding: "cue" - + cue: encoding: "cue" json: encoding: "json" jsonl: encoding: "jsonl" yaml: encoding: "yaml" + toml: encoding: "toml" proto: encoding: "proto" textproto: encoding: "textproto" // "binpb": encodings.binproto @@ -362,17 +360,9 @@ tags: { interpretation: "" tags: lang: *"" | string } - - auto: { - interpretation: "auto" - encoding: *"json" | _ - } - jsonschema: { - interpretation: "jsonschema" - encoding: *"json" | _ - } - openapi: { - interpretation: "openapi" - encoding: *"json" | _ + auto: interpretations.auto & { + encoding: *"json" | string } + jsonschema: interpretations.jsonschema + openapi: interpretations.openapi } diff --git a/vendor/cuelang.org/go/internal/filetypes/types.go b/vendor/cuelang.org/go/internal/filetypes/types.go index 21981b7eb0..22d390c6be 100644 --- a/vendor/cuelang.org/go/internal/filetypes/types.go +++ b/vendor/cuelang.org/go/internal/filetypes/types.go @@ -16,17 +16,22 @@ package filetypes import ( _ "embed" + "fmt" "sync" "cuelang.org/go/cue" + "cuelang.org/go/cue/build" "cuelang.org/go/cue/cuecontext" ) //go:embed types.cue var typesCUE string -var typesValue cue.Value -var knownExtensions map[string]bool +var ( + typesValue cue.Value + fileForExt map[string]*build.File + fileForCUE *build.File +) var typesInit = sync.OnceFunc(func() { ctx := cuecontext.New() @@ -34,7 +39,15 @@ var typesInit = sync.OnceFunc(func() { if err := typesValue.Err(); err != nil { panic(err) } - if err := typesValue.LookupPath(cue.MakePath(cue.Str("knownExtensions"))).Decode(&knownExtensions); err != nil { + // Reading a file in input mode with a non-explicit scope is a very + // common operation, so cache the build.File value for all + // the known file extensions. + if err := typesValue.LookupPath(cue.MakePath(cue.Str("fileForExtVanilla"))).Decode(&fileForExt); err != nil { panic(err) } + fileForCUE = fileForExt[".cue"] + // Check invariants assumed by FromFile + if fileForCUE.Form != "" || fileForCUE.Interpretation != "" || fileForCUE.Encoding != build.CUE { + panic(fmt.Errorf("unexpected value for CUE file type: %#v", fileForCUE)) + } }) diff --git a/vendor/cuelang.org/go/internal/internal.go b/vendor/cuelang.org/go/internal/internal.go index bb459deade..bb23caf51f 100644 --- a/vendor/cuelang.org/go/internal/internal.go +++ b/vendor/cuelang.org/go/internal/internal.go @@ -23,6 +23,7 @@ import ( "bufio" "fmt" "path/filepath" + "slices" "strings" "github.com/cockroachdb/apd/v3" @@ -107,14 +108,27 @@ func Version(minor, patch int) int { return -1000 + 100*minor + patch } +// EvaluatorVersion is declared here so it can be used everywhere without import cycles, +// but the canonical documentation lives at [cuelang.org/go/cue/cuecontext.EvalVersion]. +// +// TODO(mvdan): rename to EvalVersion for consistency with cuecontext. type EvaluatorVersion int const ( - DefaultVersion EvaluatorVersion = iota + // EvalVersionUnset is the zero value, which signals that no evaluator version is provided. + EvalVersionUnset EvaluatorVersion = 0 + + // The values below are documented under [cuelang.org/go/cue/cuecontext.EvalVersion]. + // We should never change or delete the values below, as they describe all known past versions + // which is useful for understanding old debug output. + + EvalV2 EvaluatorVersion = 2 + EvalV3 EvaluatorVersion = 3 - // The DevVersion is used for new implementations of the evaluator that - // do not cover all features of the CUE language yet. - DevVersion + // The current default and experimental versions. + + DefaultVersion = EvalV2 // TODO(mvdan): rename to EvalDefault for consistency with cuecontext + DevVersion = EvalV3 // TODO(mvdan): rename to EvalExperiment for consistency with cuecontext ) // ListEllipsis reports the list type and remaining elements of a list. If we @@ -132,41 +146,31 @@ func ListEllipsis(n *ast.ListLit) (elts []ast.Expr, e *ast.Ellipsis) { return elts, e } -type PkgInfo struct { - Package *ast.Package - Index int // position in File.Decls - Name string -} - -// IsAnonymous reports whether the package is anonymous. -func (p *PkgInfo) IsAnonymous() bool { - return p.Name == "" || p.Name == "_" -} - -func GetPackageInfo(f *ast.File) PkgInfo { - for i, d := range f.Decls { - switch x := d.(type) { +// Package finds the package declaration from the preamble of a file. +func Package(f *ast.File) *ast.Package { + for _, d := range f.Decls { + switch d := d.(type) { case *ast.CommentGroup: case *ast.Attribute: case *ast.Package: - if x.Name == nil { - return PkgInfo{} + if d.Name == nil { // malformed package declaration + return nil } - return PkgInfo{x, i, x.Name.Name} + return d default: - return PkgInfo{} + return nil } } - return PkgInfo{} + return nil } func SetPackage(f *ast.File, name string, overwrite bool) { - if pi := GetPackageInfo(f); pi.Package != nil { - if !overwrite || pi.Name == name { + if pkg := Package(f); pkg != nil { + if !overwrite || pkg.Name.Name == name { return } ident := ast.NewIdent(name) - astutil.CopyMeta(ident, pi.Package.Name) + astutil.CopyMeta(ident, pkg.Name) return } @@ -226,34 +230,61 @@ func NewComment(isDoc bool, s string) *ast.CommentGroup { return cg } -func FileComment(f *ast.File) *ast.CommentGroup { - var cgs []*ast.CommentGroup - if pkg := GetPackageInfo(f).Package; pkg != nil { - cgs = pkg.Comments() - } else if cgs = f.Comments(); len(cgs) > 0 { - // Use file comment. - } else { - // Use first comment before any declaration. - for _, d := range f.Decls { - if cg, ok := d.(*ast.CommentGroup); ok { - return cg - } - if cgs = ast.Comments(d); cgs != nil { - break - } - // TODO: what to do here? - if _, ok := d.(*ast.Attribute); !ok { - break - } +func FileComments(f *ast.File) (docs, rest []*ast.CommentGroup) { + hasPkg := false + if pkg := Package(f); pkg != nil { + hasPkg = true + docs = pkg.Comments() + } + + for _, c := range f.Comments() { + if c.Doc { + docs = append(docs, c) + } else { + rest = append(rest, c) + } + } + + if !hasPkg && len(docs) == 0 && len(rest) > 0 { + // use the first file comment group as as doc comment. + docs, rest = rest[:1], rest[1:] + docs[0].Doc = true + } + + return +} + +// MergeDocs merges multiple doc comments into one single doc comment. +func MergeDocs(comments []*ast.CommentGroup) []*ast.CommentGroup { + if len(comments) <= 1 || !hasDocComment(comments) { + return comments + } + + comments1 := make([]*ast.CommentGroup, 0, len(comments)) + comments1 = append(comments1, nil) + var docComment *ast.CommentGroup + for _, c := range comments { + switch { + case !c.Doc: + comments1 = append(comments1, c) + case docComment == nil: + docComment = c + default: + docComment.List = append(slices.Clip(docComment.List), &ast.Comment{Text: "//"}) + docComment.List = append(docComment.List, c.List...) } } - var cg *ast.CommentGroup - for _, c := range cgs { - if c.Position == 0 { - cg = c + comments1[0] = docComment + return comments1 +} + +func hasDocComment(comments []*ast.CommentGroup) bool { + for _, c := range comments { + if c.Doc { + return true } } - return cg + return false } func NewAttr(name, str string) *ast.Attribute { @@ -440,28 +471,3 @@ func GenPath(root string) string { } var ErrInexact = errors.New("inexact subsumption") - -func DecorateError(info error, err errors.Error) errors.Error { - return &decorated{cueError: err, info: info} -} - -type cueError = errors.Error - -type decorated struct { - cueError - - info error -} - -func (e *decorated) Is(err error) bool { - return errors.Is(e.info, err) || errors.Is(e.cueError, err) -} - -// MaxDepth indicates the maximum evaluation depth. This is there to break -// cycles in the absence of cycle detection. -// -// It is registered in a central place to make it easy to find all spots where -// cycles are broken in this brute-force manner. -// -// TODO(eval): have cycle detection. -const MaxDepth = 20 diff --git a/vendor/cuelang.org/go/internal/mod/modimports/modimports.go b/vendor/cuelang.org/go/internal/mod/modimports/modimports.go index 49f04708ee..2f7640ca1d 100644 --- a/vendor/cuelang.org/go/internal/mod/modimports/modimports.go +++ b/vendor/cuelang.org/go/internal/mod/modimports/modimports.go @@ -1,10 +1,11 @@ package modimports import ( + "errors" "fmt" "io/fs" "path" - "sort" + "slices" "strconv" "strings" @@ -59,7 +60,7 @@ func AllImports(modFilesIter func(func(ModuleFile, error) bool)) (_ []string, re for p := range pkgPaths { pkgPathSlice = append(pkgPathSlice, p) } - sort.Strings(pkgPathSlice) + slices.Sort(pkgPathSlice) return pkgPathSlice, nil } @@ -105,6 +106,10 @@ func PackageFiles(fsys fs.FS, dir string, pkgQualifier string) func(func(ModuleF if e.Name() == "cue.mod" { inModRoot = true } + if e.IsDir() { + // Directories are never package files, even when their filename ends with ".cue". + continue + } pkgName, cont := yieldPackageFile(fsys, path.Join(dir, e.Name()), selectPackage, yield) if !cont { return @@ -214,26 +219,44 @@ func yieldPackageFile(fsys fs.FS, fpath string, selectPackage func(pkgName strin pf := ModuleFile{ FilePath: fpath, } - f, err := fsys.Open(fpath) - if err != nil { - return "", yield(pf, err) + var syntax *ast.File + var err error + if cueFS, ok := fsys.(module.ReadCUEFS); ok { + // The FS implementation supports reading CUE syntax directly. + // A notable FS implementation that does this is the one + // provided by cue/load, allowing that package to cache + // the parsed CUE. + syntax, err = cueFS.ReadCUEFile(fpath) + if err != nil && !errors.Is(err, errors.ErrUnsupported) { + return "", yield(pf, err) + } } - defer f.Close() + if syntax == nil { + // Either the FS doesn't implement [module.ReadCUEFS] + // or the ReadCUEFile method returned ErrUnsupported, + // so we need to acquire the syntax ourselves. - // Note that we use cueimports.Read before parser.ParseFile as cue/parser - // will always consume the whole input reader, which is often wasteful. - // - // TODO(mvdan): the need for cueimports.Read can go once cue/parser can work - // on a reader in a streaming manner. - data, err := cueimports.Read(f) - if err != nil { - return "", yield(pf, err) - } - // Add a leading "./" so that a parse error filename is consistent - // with the other error filenames created elsewhere in the codebase. - syntax, err := parser.ParseFile("./"+fpath, data, parser.ImportsOnly) - if err != nil { - return "", yield(pf, err) + f, err := fsys.Open(fpath) + if err != nil { + return "", yield(pf, err) + } + defer f.Close() + + // Note that we use cueimports.Read before parser.ParseFile as cue/parser + // will always consume the whole input reader, which is often wasteful. + // + // TODO(mvdan): the need for cueimports.Read can go once cue/parser can work + // on a reader in a streaming manner. + data, err := cueimports.Read(f) + if err != nil { + return "", yield(pf, err) + } + // Add a leading "./" so that a parse error filename is consistent + // with the other error filenames created elsewhere in the codebase. + syntax, err = parser.ParseFile("./"+fpath, data, parser.ImportsOnly) + if err != nil { + return "", yield(pf, err) + } } if !selectPackage(syntax.PackageName()) { diff --git a/vendor/cuelang.org/go/internal/mod/modload/query.go b/vendor/cuelang.org/go/internal/mod/modload/query.go index 45a73c1023..9895183134 100644 --- a/vendor/cuelang.org/go/internal/mod/modload/query.go +++ b/vendor/cuelang.org/go/internal/mod/modload/query.go @@ -95,7 +95,6 @@ func (ld *loader) queryLatestModules(ctx context.Context, pkgPath string, rs *mo ) logf("initial module path %q", parts.Path) for prefix := parts.Path; prefix != "."; prefix = path.Dir(prefix) { - prefix := prefix work.Add(func() { v, err := latestModuleForPrefix(prefix) mu.Lock() diff --git a/vendor/cuelang.org/go/internal/mod/modload/tidy.go b/vendor/cuelang.org/go/internal/mod/modload/tidy.go index d5af2dccee..6106fb2d0b 100644 --- a/vendor/cuelang.org/go/internal/mod/modload/tidy.go +++ b/vendor/cuelang.org/go/internal/mod/modload/tidy.go @@ -10,7 +10,9 @@ import ( "path" "runtime" "slices" + "strings" + "cuelang.org/go/internal/buildattr" "cuelang.org/go/internal/mod/modimports" "cuelang.org/go/internal/mod/modpkgload" "cuelang.org/go/internal/mod/modrequirements" @@ -64,7 +66,10 @@ func tidy(ctx context.Context, fsys fs.FS, modRoot string, reg Registry, checkTi } // TODO check that module path is well formed etc origRs := modrequirements.NewRequirements(mf.QualifiedModule(), reg, mf.DepVersions(), mf.DefaultMajorVersions()) - rootPkgPaths, err := modimports.AllImports(modimports.AllModuleFiles(fsys, modRoot)) + // Note: we can ignore build tags and the fact that we might + // have _tool.cue and _test.cue files, because we want to include + // all of those, but we do need to consider @ignore() attributes. + rootPkgPaths, err := modimports.AllImports(withoutIgnoredFiles(modimports.AllModuleFiles(fsys, modRoot))) if err != nil { return nil, err } @@ -136,7 +141,7 @@ func readModuleFile(fsys fs.FS, modRoot string) (module.Version, *modfile.File, } mainModuleVersion, err := module.NewVersion(mf.QualifiedModule(), "") if err != nil { - return module.Version{}, nil, fmt.Errorf("invalid module path %q: %v", mf.QualifiedModule(), err) + return module.Version{}, nil, fmt.Errorf("%s: invalid module path: %v", modFilePath, err) } return mainModuleVersion, mf, nil } @@ -165,10 +170,39 @@ func modfileFromRequirements(old *modfile.File, rs *modrequirements.Requirements return mf } +// shouldIncludePkgFile reports whether a file from a package should be included +// for dependency-analysis purposes. +// +// In general a file should always be considered unless it's a _tool.cue file +// that's not in the main module. +func (ld *loader) shouldIncludePkgFile(pkgPath string, mod module.Version, fsys fs.FS, mf modimports.ModuleFile) (_ok bool) { + if buildattr.ShouldIgnoreFile(mf.Syntax) { + // The file is marked to be explicitly ignored. + return false + } + if mod.Path() == ld.mainModule.Path() { + // All files in the main module are considered. + return true + } + if strings.HasSuffix(mf.FilePath, "_tool.cue") || strings.HasSuffix(mf.FilePath, "_test.cue") { + // tool and test files are only considered when they are part of the main module. + return false + } + ok, _, err := buildattr.ShouldBuildFile(mf.Syntax, func(key string) bool { + // Keys of build attributes are considered always false when + // outside the main module. + return false + }) + if err != nil { + return false + } + return ok +} + func (ld *loader) resolveDependencies(ctx context.Context, rootPkgPaths []string, rs *modrequirements.Requirements) (*modrequirements.Requirements, *modpkgload.Packages, error) { for { logf("---- LOADING from requirements %q", rs.RootModules()) - pkgs := modpkgload.LoadPackages(ctx, ld.mainModule.Path(), ld.mainModuleLoc, rs, ld.registry, rootPkgPaths) + pkgs := modpkgload.LoadPackages(ctx, ld.mainModule.Path(), ld.mainModuleLoc, rs, ld.registry, rootPkgPaths, ld.shouldIncludePkgFile) if ld.checkTidy { for _, pkg := range pkgs.All() { err := pkg.Error() @@ -492,7 +526,6 @@ func (ld *loader) resolveMissingImports(ctx context.Context, pkgs *modpkgload.Pa var pkgMods []pkgMod work := par.NewQueue(runtime.GOMAXPROCS(0)) for _, pkg := range pkgs.All() { - pkg := pkg if pkg.Error() == nil { continue } @@ -655,7 +688,6 @@ func (ld *loader) spotCheckRoots(ctx context.Context, rs *modrequirements.Requir work := par.NewQueue(runtime.GOMAXPROCS(0)) for m := range mods { - m := m work.Add(func() { if ctx.Err() != nil { return @@ -686,6 +718,18 @@ func (ld *loader) spotCheckRoots(ctx context.Context, rs *modrequirements.Requir return true } +func withoutIgnoredFiles(iter func(func(modimports.ModuleFile, error) bool)) func(func(modimports.ModuleFile, error) bool) { + return func(yield func(modimports.ModuleFile, error) bool) { + // TODO for mf, err := range iter { + iter(func(mf modimports.ModuleFile, err error) bool { + if err == nil && buildattr.ShouldIgnoreFile(mf.Syntax) { + return true + } + return yield(mf, err) + }) + } +} + func logf(f string, a ...any) { if logging { log.Printf(f, a...) diff --git a/vendor/cuelang.org/go/internal/mod/modload/update.go b/vendor/cuelang.org/go/internal/mod/modload/update.go index 9ab8c1944c..5bc585cb27 100644 --- a/vendor/cuelang.org/go/internal/mod/modload/update.go +++ b/vendor/cuelang.org/go/internal/mod/modload/update.go @@ -73,6 +73,7 @@ func UpdateVersions(ctx context.Context, fsys fs.FS, modRoot string, reg Registr for _, v := range mversionsMap { newVersions = append(newVersions, v) } + module.Sort(newVersions) rs = modrequirements.NewRequirements(mf.QualifiedModule(), reg, newVersions, mf.DefaultMajorVersions()) g, err = rs.Graph(ctx) if err != nil { @@ -150,6 +151,10 @@ func resolveUpdateVersions(ctx context.Context, reg Registry, rs *modrequirement possibleVersions = append(possibleVersions, v) } } + if len(possibleVersions) == 0 { + setError(fmt.Errorf("no versions found for module %s", v)) + return + } chosen := latestVersion(possibleVersions) mv, err := module.NewVersion(mpath, chosen) if err != nil { diff --git a/vendor/cuelang.org/go/internal/mod/modpkgload/import.go b/vendor/cuelang.org/go/internal/mod/modpkgload/import.go index 252a8d13ae..6dc51d1f1d 100644 --- a/vendor/cuelang.org/go/internal/mod/modpkgload/import.go +++ b/vendor/cuelang.org/go/internal/mod/modpkgload/import.go @@ -249,7 +249,20 @@ func isDirWithCUEFiles(loc module.SourceLoc) (bool, error) { return false, err } for _, e := range entries { - if strings.HasSuffix(e.Name(), ".cue") && e.Type().IsRegular() { + if !strings.HasSuffix(e.Name(), ".cue") { + continue + } + ftype := e.Type() + // If the directory entry is a symlink, stat it to obtain the info for the + // link target instead of the link itself. + if ftype&fs.ModeSymlink != 0 { + info, err := fs.Stat(loc.FS, filepath.Join(loc.Dir, e.Name())) + if err != nil { + continue // Ignore broken symlinks. + } + ftype = info.Mode() + } + if ftype.IsRegular() { return true, nil } } diff --git a/vendor/cuelang.org/go/internal/mod/modpkgload/pkgload.go b/vendor/cuelang.org/go/internal/mod/modpkgload/pkgload.go index 05d5235b4c..15d936035e 100644 --- a/vendor/cuelang.org/go/internal/mod/modpkgload/pkgload.go +++ b/vendor/cuelang.org/go/internal/mod/modpkgload/pkgload.go @@ -3,9 +3,9 @@ package modpkgload import ( "context" "fmt" + "io/fs" "runtime" "slices" - "sort" "strings" "sync/atomic" @@ -76,14 +76,15 @@ func (f Flags) has(cond Flags) bool { } type Packages struct { - mainModuleVersion module.Version - mainModuleLoc module.SourceLoc - pkgCache par.Cache[string, *Package] - pkgs []*Package - rootPkgs []*Package - work *par.Queue - requirements *modrequirements.Requirements - registry Registry + mainModuleVersion module.Version + mainModuleLoc module.SourceLoc + shouldIncludePkgFile func(pkgPath string, mod module.Version, fsys fs.FS, mf modimports.ModuleFile) bool + pkgCache par.Cache[string, *Package] + pkgs []*Package + rootPkgs []*Package + work *par.Queue + requirements *modrequirements.Requirements + registry Registry } type Package struct { @@ -148,6 +149,12 @@ func (pkg *Package) Mod() module.Version { // and reg to download module contents. // // rootPkgPaths should only contain canonical import paths. +// +// The shouldIncludePkgFile function is used to determine whether a +// given file in a package should be considered to be part of the build. +// If it returns true for a package, the file's imports will be followed. +// A nil value corresponds to a function that always returns true. +// It may be called concurrently. func LoadPackages( ctx context.Context, mainModulePath string, @@ -155,13 +162,15 @@ func LoadPackages( rs *modrequirements.Requirements, reg Registry, rootPkgPaths []string, + shouldIncludePkgFile func(pkgPath string, mod module.Version, fsys fs.FS, mf modimports.ModuleFile) bool, ) *Packages { pkgs := &Packages{ - mainModuleVersion: module.MustNewVersion(mainModulePath, ""), - mainModuleLoc: mainModuleLoc, - requirements: rs, - registry: reg, - work: par.NewQueue(runtime.GOMAXPROCS(0)), + mainModuleVersion: module.MustNewVersion(mainModulePath, ""), + mainModuleLoc: mainModuleLoc, + shouldIncludePkgFile: shouldIncludePkgFile, + requirements: rs, + registry: reg, + work: par.NewQueue(runtime.GOMAXPROCS(0)), } inRoots := map[*Package]bool{} pkgs.rootPkgs = make([]*Package, 0, len(rootPkgPaths)) @@ -247,23 +256,42 @@ func (pkgs *Packages) load(ctx context.Context, pkg *Package) { if pkgs.mainModuleVersion.Path() == pkg.mod.Path() { pkgs.applyPkgFlags(pkg, PkgInAll) } - pkgQual := module.ParseImportPath(pkg.path).Qualifier - if pkgQual == "" { - pkg.err = fmt.Errorf("cannot determine package name from import path %q", pkg.path) + ip := module.ParseImportPath(pkg.path) + pkgQual := ip.Qualifier + switch pkgQual { + case "": + // If we are tidying a module which imports "foo.com/bar-baz@v0", + // a qualifier is needed as no valid package name can be derived from the path. + // Don't fail here, however, as tidy can simply ensure that bar-baz is a dependency, + // much like how `cue mod get foo.com/bar-baz` works just fine to add a module. + // Any command which later attempts to actually import bar-baz without a qualifier + // will result in a helpful error which the user can resolve at that point. + return + case "_": + pkg.err = fmt.Errorf("_ is not a valid import path qualifier in %q", pkg.path) return } importsMap := make(map[string]bool) foundPackageFile := false + excludedPackageFiles := 0 for _, loc := range pkg.locs { // Layer an iterator whose yield function keeps track of whether we have seen // a single valid CUE file in the package directory. // Otherwise we would have to iterate twice, causing twice as many io/fs operations. pkgFileIter := func(yield func(modimports.ModuleFile, error) bool) { - yield2 := func(mf modimports.ModuleFile, err error) bool { - foundPackageFile = err == nil + modimports.PackageFiles(loc.FS, loc.Dir, pkgQual)(func(mf modimports.ModuleFile, err error) bool { + if err != nil { + return yield(mf, err) + } + ip1 := ip + ip1.Qualifier = mf.Syntax.PackageName() + if !pkgs.shouldIncludePkgFile(ip1.String(), pkg.mod, loc.FS, mf) { + excludedPackageFiles++ + return true + } + foundPackageFile = true return yield(mf, err) - } - modimports.PackageFiles(loc.FS, loc.Dir, pkgQual)(yield2) + }) } imports, err := modimports.AllImports(pkgFileIter) if err != nil { @@ -275,14 +303,18 @@ func (pkgs *Packages) load(ctx context.Context, pkg *Package) { } } if !foundPackageFile { - pkg.err = fmt.Errorf("no files in package directory with package name %q", pkgQual) + if excludedPackageFiles > 0 { + pkg.err = fmt.Errorf("no files in package directory with package name %q (%d files were excluded)", pkgQual, excludedPackageFiles) + } else { + pkg.err = fmt.Errorf("no files in package directory with package name %q", pkgQual) + } return } imports := make([]string, 0, len(importsMap)) for imp := range importsMap { imports = append(imports, imp) } - sort.Strings(imports) // Make the algorithm deterministic for tests. + slices.Sort(imports) // Make the algorithm deterministic for tests. pkg.imports = make([]*Package, 0, len(imports)) var importFlags Flags diff --git a/vendor/cuelang.org/go/internal/mod/modresolve/resolve.go b/vendor/cuelang.org/go/internal/mod/modresolve/resolve.go index 878777029b..60253eb476 100644 --- a/vendor/cuelang.org/go/internal/mod/modresolve/resolve.go +++ b/vendor/cuelang.org/go/internal/mod/modresolve/resolve.go @@ -15,13 +15,14 @@ package modresolve import ( + "cmp" "crypto/sha256" _ "embed" "fmt" "net" "net/netip" "path" - "sort" + "slices" "strings" "sync" @@ -379,8 +380,8 @@ func (r *resolver) initHosts() error { Insecure: insecure, }) } - sort.Slice(allHosts, func(i, j int) bool { - return allHosts[i].Name < allHosts[j].Name + slices.SortFunc(allHosts, func(a, b Host) int { + return cmp.Compare(a.Name, b.Name) }) r.allHosts = allHosts return nil diff --git a/vendor/cuelang.org/go/internal/mod/mvs/graph.go b/vendor/cuelang.org/go/internal/mod/mvs/graph.go index 6cab7c3ed2..7ae9d05309 100644 --- a/vendor/cuelang.org/go/internal/mod/mvs/graph.go +++ b/vendor/cuelang.org/go/internal/mod/mvs/graph.go @@ -5,9 +5,9 @@ package mvs import ( + "cmp" "fmt" "slices" - "sort" ) // Versions is an interface that should be provided by implementations @@ -157,12 +157,11 @@ func (g *Graph[V]) BuildList() []V { } func (g *Graph[V]) sortVersions(vs []V) { - sort.Slice(vs, func(i, j int) bool { - v0, v1 := vs[i], vs[j] - if p0, p1 := g.v.Path(v0), g.v.Path(v1); p0 != p1 { - return p0 < p1 + slices.SortFunc(vs, func(a, b V) int { + if c := cmp.Compare(g.v.Path(a), g.v.Path(b)); c != 0 { + return c } - return g.cmp(g.v.Version(v0), g.v.Version(v1)) < 0 + return g.cmp(g.v.Version(a), g.v.Version(b)) }) } diff --git a/vendor/cuelang.org/go/internal/mod/mvs/mvs.go b/vendor/cuelang.org/go/internal/mod/mvs/mvs.go index 45d444f332..4003b71bd6 100644 --- a/vendor/cuelang.org/go/internal/mod/mvs/mvs.go +++ b/vendor/cuelang.org/go/internal/mod/mvs/mvs.go @@ -7,9 +7,9 @@ package mvs import ( + "cmp" "fmt" "slices" - "sort" "sync" "cuelang.org/go/internal/par" @@ -268,8 +268,8 @@ func Req[V comparable](mainModule V, base []string, reqs Reqs[V]) ([]V, error) { walk(m) } } - sort.Slice(min, func(i, j int) bool { - return reqs.Path(min[i]) < reqs.Path(min[j]) + slices.SortFunc(min, func(a, b V) int { + return cmp.Compare(reqs.Path(a), reqs.Path(b)) }) return min, nil } diff --git a/vendor/cuelang.org/go/internal/mod/semver/semver.go b/vendor/cuelang.org/go/internal/mod/semver/semver.go index e463c7de36..0d33ac41cf 100644 --- a/vendor/cuelang.org/go/internal/mod/semver/semver.go +++ b/vendor/cuelang.org/go/internal/mod/semver/semver.go @@ -140,20 +140,6 @@ func Compare(v, w string) int { return comparePrerelease(pv.prerelease, pw.prerelease) } -// Max canonicalizes its arguments and then returns the version string -// that compares greater. -// -// Deprecated: use Compare instead. In most cases, returning a canonicalized -// version is not expected or desired. -func Max(v, w string) string { - v = Canonical(v) - w = Canonical(w) - if Compare(v, w) > 0 { - return v - } - return w -} - // Sort sorts a list of semantic version strings. func Sort(list []string) { slices.SortFunc(list, func(a, b string) int { diff --git a/vendor/cuelang.org/go/internal/par/work.go b/vendor/cuelang.org/go/internal/par/work.go index 5b6de9425a..4a03e89be9 100644 --- a/vendor/cuelang.org/go/internal/par/work.go +++ b/vendor/cuelang.org/go/internal/par/work.go @@ -64,7 +64,7 @@ func (w *Work[T]) Do(n int, f func(item T)) { w.f = f w.wait.L = &w.mu - for i := 0; i < n-1; i++ { + for range n - 1 { go w.runner() } w.runner() diff --git a/vendor/cuelang.org/go/internal/pkg/builtin.go b/vendor/cuelang.org/go/internal/pkg/builtin.go index c4227e662d..6795df32c2 100644 --- a/vendor/cuelang.org/go/internal/pkg/builtin.go +++ b/vendor/cuelang.org/go/internal/pkg/builtin.go @@ -44,12 +44,13 @@ import ( // []T // map[string]T type Builtin struct { - Name string - Pkg adt.Feature - Params []Param - Result adt.Kind - Func func(c *CallCtxt) - Const string + Name string + Pkg adt.Feature + Params []Param + Result adt.Kind + NonConcrete bool + Func func(c *CallCtxt) + Const string } type Param struct { @@ -119,10 +120,11 @@ func ToBuiltin(b *Builtin) *adt.Builtin { } x := &adt.Builtin{ - Params: params, - Result: b.Result, - Package: b.Pkg, - Name: b.Name, + Params: params, + Result: b.Result, + NonConcrete: b.NonConcrete, + Package: b.Pkg, + Name: b.Name, } x.Func = func(ctx *adt.OpContext, args []adt.Value) (ret adt.Expr) { // call, _ := ctx.Source().(*ast.CallExpr) diff --git a/vendor/cuelang.org/go/internal/pkg/context.go b/vendor/cuelang.org/go/internal/pkg/context.go index 335c5b2ccf..f8e3634152 100644 --- a/vendor/cuelang.org/go/internal/pkg/context.go +++ b/vendor/cuelang.org/go/internal/pkg/context.go @@ -49,10 +49,22 @@ func (c *CallCtxt) Do() bool { return c.Err == nil } +// Schema returns the ith argument as is, without converting it to a cue.Value. +func (c *CallCtxt) Schema(i int) Schema { + return value.Make(c.ctx, c.args[i]) +} + +// Value returns a finalized cue.Value for the ith argument. func (c *CallCtxt) Value(i int) cue.Value { v := value.Make(c.ctx, c.args[i]) - // TODO: remove default - // v, _ = v.Default() + if c.builtin.NonConcrete { + // In case NonConcrete is false, the concreteness is already checked + // at call time. We may want to use finalize semantics in both cases, + // though. + _, f := value.ToInternal(v) + f = f.ToDataAll(c.ctx) + v = value.Make(c.ctx, f) + } if !v.IsConcrete() { c.errcf(adt.IncompleteError, "non-concrete argument %d", i) } @@ -61,6 +73,9 @@ func (c *CallCtxt) Value(i int) cue.Value { func (c *CallCtxt) Struct(i int) Struct { x := c.args[i] + if c.builtin.NonConcrete { + x = adt.Default(x) + } switch v, ok := x.(*adt.Vertex); { case ok && !v.IsList(): v.CompleteArcs(c.ctx) @@ -254,14 +269,22 @@ func (c *CallCtxt) Iter(i int) (a cue.Iterator) { func (c *CallCtxt) getList(i int) *adt.Vertex { x := c.args[i] + if c.builtin.NonConcrete { + x = adt.Default(x) + } switch v, ok := x.(*adt.Vertex); { case ok && v.IsList(): v.Finalize(c.ctx) + if err := v.Bottom(); err != nil { + c.Err = &callError{err} + return nil + } return v case v != nil: x = v.Value() } + if x.Kind()&adt.ListKind == 0 { var err error if b, ok := x.(*adt.Bottom); ok { @@ -295,7 +318,7 @@ func (c *CallCtxt) DecimalList(i int) (a []*apd.Decimal) { } default: - if k := w.Kind(); k&adt.NumKind == 0 { + if k := w.Kind(); k&adt.NumberKind == 0 { err := c.ctx.NewErrf( "invalid list element %d in argument %d to call: cannot use value %v (%s) as number", j, i, w, k) diff --git a/vendor/cuelang.org/go/internal/pkg/types.go b/vendor/cuelang.org/go/internal/pkg/types.go index c2535a7b10..801971bcce 100644 --- a/vendor/cuelang.org/go/internal/pkg/types.go +++ b/vendor/cuelang.org/go/internal/pkg/types.go @@ -15,9 +15,14 @@ package pkg import ( + "cuelang.org/go/cue" "cuelang.org/go/internal/core/adt" ) +// A Schema represents an arbitrary cue.Value that can hold non-concrete values. +// By default function arguments are checked to be concrete. +type Schema = cue.Value + // List represents a CUE list, which can be open or closed. type List struct { runtime adt.Runtime @@ -57,7 +62,7 @@ func (s *Struct) Len() int { return count } -// IsOpen reports whether s allows more fields than are currently defined. +// IsOpen reports whether s is open or has pattern constraints. func (s *Struct) IsOpen() bool { if !s.node.IsClosedStruct() { return true @@ -69,10 +74,19 @@ func (s *Struct) IsOpen() bool { } // The equivalent code for the old implementation. ot := s.node.OptionalTypes() - if ot&^adt.HasDynamic != 0 { - return true + return ot&^adt.HasDynamic != 0 +} + +// NumConstraintFields reports the number of explicit optional and required +// fields, excluding pattern constraints. +func (s Struct) NumConstraintFields() (count int) { + // If we have any optional arcs, we allow more fields. + for _, a := range s.node.Arcs { + if a.ArcType != adt.ArcMember && a.Label.IsRegular() { + count++ + } } - return false + return count } // A ValidationError indicates an error that is only valid if a builtin is used diff --git a/vendor/cuelang.org/go/internal/third_party/yaml/LICENSE.libyaml b/vendor/cuelang.org/go/internal/third_party/yaml/LICENSE.libyaml deleted file mode 100644 index 8da58fbf6f..0000000000 --- a/vendor/cuelang.org/go/internal/third_party/yaml/LICENSE.libyaml +++ /dev/null @@ -1,31 +0,0 @@ -The following files were ported to Go from C files of libyaml, and thus -are still covered by their original copyright and license: - - apic.go - emitterc.go - parserc.go - readerc.go - scannerc.go - writerc.go - yamlh.go - yamlprivateh.go - -Copyright (c) 2006 Kirill Simonov - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/cuelang.org/go/internal/third_party/yaml/METADATA b/vendor/cuelang.org/go/internal/third_party/yaml/METADATA deleted file mode 100644 index 746edf0614..0000000000 --- a/vendor/cuelang.org/go/internal/third_party/yaml/METADATA +++ /dev/null @@ -1,15 +0,0 @@ -name: "go-yaml" -description: - "Heavily modified version of go-yaml files. Most of the original " - "functionality is gone and replaced with CUE-specific code." - -third_party { - url { - type: GIT - value: "https://github.com/go-yaml/yaml" - } - version: "v2.2.1" - last_upgrade_date { year: 2018 month: 10 day: 24 } - license_type: NOTICE - local_modifications: "Replace Go-struct with CUE mapping." -} \ No newline at end of file diff --git a/vendor/cuelang.org/go/internal/third_party/yaml/NOTICE b/vendor/cuelang.org/go/internal/third_party/yaml/NOTICE deleted file mode 100644 index 866d74a7ad..0000000000 --- a/vendor/cuelang.org/go/internal/third_party/yaml/NOTICE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2011-2016 Canonical Ltd. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/vendor/cuelang.org/go/internal/third_party/yaml/README.md b/vendor/cuelang.org/go/internal/third_party/yaml/README.md deleted file mode 100644 index ea39618bbd..0000000000 --- a/vendor/cuelang.org/go/internal/third_party/yaml/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# YAML reader for CUE - -This yaml parser is a heavily modified version of Canonical's go-yaml parser, -which in turn is a port of the [libyaml](http://pyyaml.org/wiki/LibYAML) parser. - - -License -------- - -The yaml package is licensed under the Apache License 2.0. Please see the LICENSE file for details. - diff --git a/vendor/cuelang.org/go/internal/third_party/yaml/apic.go b/vendor/cuelang.org/go/internal/third_party/yaml/apic.go deleted file mode 100644 index d515bdb5a9..0000000000 --- a/vendor/cuelang.org/go/internal/third_party/yaml/apic.go +++ /dev/null @@ -1,740 +0,0 @@ -package yaml - -import ( - "io" -) - -func yaml_insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) { - //fmt.Println("yaml_insert_token", "pos:", pos, "typ:", token.typ, "head:", parser.tokens_head, "len:", len(parser.tokens)) - - // Check if we can move the queue at the beginning of the buffer. - if parser.tokens_head > 0 && len(parser.tokens) == cap(parser.tokens) { - if parser.tokens_head != len(parser.tokens) { - copy(parser.tokens, parser.tokens[parser.tokens_head:]) - } - parser.tokens = parser.tokens[:len(parser.tokens)-parser.tokens_head] - parser.tokens_head = 0 - } - parser.tokens = append(parser.tokens, *token) - if pos < 0 { - return - } - copy(parser.tokens[parser.tokens_head+pos+1:], parser.tokens[parser.tokens_head+pos:]) - parser.tokens[parser.tokens_head+pos] = *token -} - -// Create a new parser object. -func yaml_parser_initialize(parser *yaml_parser_t, filename string) bool { - *parser = yaml_parser_t{ - filename: filename, - raw_buffer: make([]byte, 0, input_raw_buffer_size), - buffer: make([]byte, 0, input_buffer_size), - } - return true -} - -// Destroy a parser object. -func yaml_parser_delete(parser *yaml_parser_t) { - *parser = yaml_parser_t{} -} - -// String read handler. -func yaml_string_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { - if parser.input_pos == len(parser.input) { - return 0, io.EOF - } - n = copy(buffer, parser.input[parser.input_pos:]) - parser.input_pos += n - return n, nil -} - -// Reader read handler. -func yaml_reader_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { - return parser.input_reader.Read(buffer) -} - -// Set a string input. -func yaml_parser_set_input_string(parser *yaml_parser_t, input []byte) { - if parser.read_handler != nil { - panic("must set the input source only once") - } - parser.read_handler = yaml_string_read_handler - parser.input = input - parser.input_pos = 0 -} - -// Set a file input. -func yaml_parser_set_input_reader(parser *yaml_parser_t, r io.Reader) { - if parser.read_handler != nil { - panic("must set the input source only once") - } - parser.read_handler = yaml_reader_read_handler - parser.input_reader = r -} - -// Set the source encoding. -func yaml_parser_set_encoding(parser *yaml_parser_t, encoding yaml_encoding_t) { - if parser.encoding != yaml_ANY_ENCODING { - panic("must set the encoding only once") - } - parser.encoding = encoding -} - -// Create a new emitter object. -func yaml_emitter_initialize(emitter *yaml_emitter_t) { - *emitter = yaml_emitter_t{ - buffer: make([]byte, output_buffer_size), - raw_buffer: make([]byte, 0, output_raw_buffer_size), - states: make([]yaml_emitter_state_t, 0, initial_stack_size), - events: make([]yaml_event_t, 0, initial_queue_size), - } -} - -// Destroy an emitter object. -func yaml_emitter_delete(emitter *yaml_emitter_t) { - *emitter = yaml_emitter_t{} -} - -// String write handler. -func yaml_string_write_handler(emitter *yaml_emitter_t, buffer []byte) error { - *emitter.output_buffer = append(*emitter.output_buffer, buffer...) - return nil -} - -// yaml_writer_write_handler uses emitter.output_writer to write the -// emitted text. -func yaml_writer_write_handler(emitter *yaml_emitter_t, buffer []byte) error { - _, err := emitter.output_writer.Write(buffer) - return err -} - -// Set a string output. -func yaml_emitter_set_output_string(emitter *yaml_emitter_t, output_buffer *[]byte) { - if emitter.write_handler != nil { - panic("must set the output target only once") - } - emitter.write_handler = yaml_string_write_handler - emitter.output_buffer = output_buffer -} - -// Set a file output. -func yaml_emitter_set_output_writer(emitter *yaml_emitter_t, w io.Writer) { - if emitter.write_handler != nil { - panic("must set the output target only once") - } - emitter.write_handler = yaml_writer_write_handler - emitter.output_writer = w -} - -// Set the output encoding. -func yaml_emitter_set_encoding(emitter *yaml_emitter_t, encoding yaml_encoding_t) { - if emitter.encoding != yaml_ANY_ENCODING { - panic("must set the output encoding only once") - } - emitter.encoding = encoding -} - -// Set the canonical output style. -func yaml_emitter_set_canonical(emitter *yaml_emitter_t, canonical bool) { - emitter.canonical = canonical -} - -// // Set the indentation increment. -func yaml_emitter_set_indent(emitter *yaml_emitter_t, indent int) { - if indent < 2 || indent > 9 { - indent = 2 - } - emitter.best_indent = indent -} - -// Set the preferred line width. -func yaml_emitter_set_width(emitter *yaml_emitter_t, width int) { - if width < 0 { - width = -1 - } - emitter.best_width = width -} - -// Set if unescaped non-ASCII characters are allowed. -func yaml_emitter_set_unicode(emitter *yaml_emitter_t, unicode bool) { - emitter.unicode = unicode -} - -// Set the preferred line break character. -func yaml_emitter_set_break(emitter *yaml_emitter_t, line_break yaml_break_t) { - emitter.line_break = line_break -} - -///* -// * Destroy a token object. -// */ -// -//YAML_DECLARE(void) -//yaml_token_delete(yaml_token_t *token) -//{ -// assert(token); // Non-NULL token object expected. -// -// switch (token.type) -// { -// case YAML_TAG_DIRECTIVE_TOKEN: -// yaml_free(token.data.tag_directive.handle); -// yaml_free(token.data.tag_directive.prefix); -// break; -// -// case YAML_ALIAS_TOKEN: -// yaml_free(token.data.alias.value); -// break; -// -// case YAML_ANCHOR_TOKEN: -// yaml_free(token.data.anchor.value); -// break; -// -// case YAML_TAG_TOKEN: -// yaml_free(token.data.tag.handle); -// yaml_free(token.data.tag.suffix); -// break; -// -// case YAML_SCALAR_TOKEN: -// yaml_free(token.data.scalar.value); -// break; -// -// default: -// break; -// } -// -// memset(token, 0, sizeof(yaml_token_t)); -//} -// -///* -// * Check if a string is a valid UTF-8 sequence. -// * -// * Check 'reader.c' for more details on UTF-8 encoding. -// */ -// -//static int -//yaml_check_utf8(yaml_char_t *start, size_t length) -//{ -// yaml_char_t *end = start+length; -// yaml_char_t *pointer = start; -// -// while (pointer < end) { -// unsigned char octet; -// unsigned int width; -// unsigned int value; -// size_t k; -// -// octet = pointer[0]; -// width = (octet & 0x80) == 0x00 ? 1 : -// (octet & 0xE0) == 0xC0 ? 2 : -// (octet & 0xF0) == 0xE0 ? 3 : -// (octet & 0xF8) == 0xF0 ? 4 : 0; -// value = (octet & 0x80) == 0x00 ? octet & 0x7F : -// (octet & 0xE0) == 0xC0 ? octet & 0x1F : -// (octet & 0xF0) == 0xE0 ? octet & 0x0F : -// (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0; -// if (!width) return 0; -// if (pointer+width > end) return 0; -// for (k = 1; k < width; k ++) { -// octet = pointer[k]; -// if ((octet & 0xC0) != 0x80) return 0; -// value = (value << 6) + (octet & 0x3F); -// } -// if (!((width == 1) || -// (width == 2 && value >= 0x80) || -// (width == 3 && value >= 0x800) || -// (width == 4 && value >= 0x10000))) return 0; -// -// pointer += width; -// } -// -// return 1; -//} -// - -// Create STREAM-START. -func yaml_stream_start_event_initialize(event *yaml_event_t, encoding yaml_encoding_t) { - *event = yaml_event_t{ - typ: yaml_STREAM_START_EVENT, - encoding: encoding, - } -} - -// Create STREAM-END. -func yaml_stream_end_event_initialize(event *yaml_event_t) { - *event = yaml_event_t{ - typ: yaml_STREAM_END_EVENT, - } -} - -// Create DOCUMENT-START. -func yaml_document_start_event_initialize( - event *yaml_event_t, - version_directive *yaml_version_directive_t, - tag_directives []yaml_tag_directive_t, - implicit bool, -) { - *event = yaml_event_t{ - typ: yaml_DOCUMENT_START_EVENT, - version_directive: version_directive, - tag_directives: tag_directives, - implicit: implicit, - } -} - -// Create DOCUMENT-END. -func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) { - *event = yaml_event_t{ - typ: yaml_DOCUMENT_END_EVENT, - implicit: implicit, - } -} - -///* -// * Create ALIAS. -// */ -// -//YAML_DECLARE(int) -//yaml_alias_event_initialize(event *yaml_event_t, anchor *yaml_char_t) -//{ -// mark yaml_mark_t = { 0, 0, 0 } -// anchor_copy *yaml_char_t = NULL -// -// assert(event) // Non-NULL event object is expected. -// assert(anchor) // Non-NULL anchor is expected. -// -// if (!yaml_check_utf8(anchor, strlen((char *)anchor))) return 0 -// -// anchor_copy = yaml_strdup(anchor) -// if (!anchor_copy) -// return 0 -// -// ALIAS_EVENT_INIT(*event, anchor_copy, mark, mark) -// -// return 1 -//} - -// Create SCALAR. -func yaml_scalar_event_initialize(event *yaml_event_t, anchor, tag, value []byte, plain_implicit, quoted_implicit bool, style yaml_scalar_style_t) bool { - *event = yaml_event_t{ - typ: yaml_SCALAR_EVENT, - anchor: anchor, - tag: tag, - value: value, - implicit: plain_implicit, - quoted_implicit: quoted_implicit, - style: yaml_style_t(style), - } - return true -} - -// Create SEQUENCE-START. -func yaml_sequence_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_sequence_style_t) bool { - *event = yaml_event_t{ - typ: yaml_SEQUENCE_START_EVENT, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(style), - } - return true -} - -// Create SEQUENCE-END. -func yaml_sequence_end_event_initialize(event *yaml_event_t) bool { - *event = yaml_event_t{ - typ: yaml_SEQUENCE_END_EVENT, - } - return true -} - -// Create MAPPING-START. -func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_mapping_style_t) { - *event = yaml_event_t{ - typ: yaml_MAPPING_START_EVENT, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(style), - } -} - -// Create MAPPING-END. -func yaml_mapping_end_event_initialize(event *yaml_event_t) { - *event = yaml_event_t{ - typ: yaml_MAPPING_END_EVENT, - } -} - -// Destroy an event object. -func yaml_event_delete(event *yaml_event_t) { - *event = yaml_event_t{} -} - -///* -// * Create a document object. -// */ -// -//YAML_DECLARE(int) -//yaml_document_initialize(document *yaml_document_t, -// version_directive *yaml_version_directive_t, -// tag_directives_start *yaml_tag_directive_t, -// tag_directives_end *yaml_tag_directive_t, -// start_implicit int, end_implicit int) -//{ -// struct { -// error yaml_error_type_t -// } context -// struct { -// start *yaml_node_t -// end *yaml_node_t -// top *yaml_node_t -// } nodes = { NULL, NULL, NULL } -// version_directive_copy *yaml_version_directive_t = NULL -// struct { -// start *yaml_tag_directive_t -// end *yaml_tag_directive_t -// top *yaml_tag_directive_t -// } tag_directives_copy = { NULL, NULL, NULL } -// value yaml_tag_directive_t = { NULL, NULL } -// mark yaml_mark_t = { 0, 0, 0 } -// -// assert(document) // Non-NULL document object is expected. -// assert((tag_directives_start && tag_directives_end) || -// (tag_directives_start == tag_directives_end)) -// // Valid tag directives are expected. -// -// if (!STACK_INIT(&context, nodes, INITIAL_STACK_SIZE)) goto error -// -// if (version_directive) { -// version_directive_copy = yaml_malloc(sizeof(yaml_version_directive_t)) -// if (!version_directive_copy) goto error -// version_directive_copy.major = version_directive.major -// version_directive_copy.minor = version_directive.minor -// } -// -// if (tag_directives_start != tag_directives_end) { -// tag_directive *yaml_tag_directive_t -// if (!STACK_INIT(&context, tag_directives_copy, INITIAL_STACK_SIZE)) -// goto error -// for (tag_directive = tag_directives_start -// tag_directive != tag_directives_end; tag_directive ++) { -// assert(tag_directive.handle) -// assert(tag_directive.prefix) -// if (!yaml_check_utf8(tag_directive.handle, -// strlen((char *)tag_directive.handle))) -// goto error -// if (!yaml_check_utf8(tag_directive.prefix, -// strlen((char *)tag_directive.prefix))) -// goto error -// value.handle = yaml_strdup(tag_directive.handle) -// value.prefix = yaml_strdup(tag_directive.prefix) -// if (!value.handle || !value.prefix) goto error -// if (!PUSH(&context, tag_directives_copy, value)) -// goto error -// value.handle = NULL -// value.prefix = NULL -// } -// } -// -// DOCUMENT_INIT(*document, nodes.start, nodes.end, version_directive_copy, -// tag_directives_copy.start, tag_directives_copy.top, -// start_implicit, end_implicit, mark, mark) -// -// return 1 -// -//error: -// STACK_DEL(&context, nodes) -// yaml_free(version_directive_copy) -// while (!STACK_EMPTY(&context, tag_directives_copy)) { -// value yaml_tag_directive_t = POP(&context, tag_directives_copy) -// yaml_free(value.handle) -// yaml_free(value.prefix) -// } -// STACK_DEL(&context, tag_directives_copy) -// yaml_free(value.handle) -// yaml_free(value.prefix) -// -// return 0 -//} -// -///* -// * Destroy a document object. -// */ -// -//YAML_DECLARE(void) -//yaml_document_delete(document *yaml_document_t) -//{ -// struct { -// error yaml_error_type_t -// } context -// tag_directive *yaml_tag_directive_t -// -// context.error = YAML_NO_ERROR // Eliminate a compiler warning. -// -// assert(document) // Non-NULL document object is expected. -// -// while (!STACK_EMPTY(&context, document.nodes)) { -// node yaml_node_t = POP(&context, document.nodes) -// yaml_free(node.tag) -// switch (node.type) { -// case YAML_SCALAR_NODE: -// yaml_free(node.data.scalar.value) -// break -// case YAML_SEQUENCE_NODE: -// STACK_DEL(&context, node.data.sequence.items) -// break -// case YAML_MAPPING_NODE: -// STACK_DEL(&context, node.data.mapping.pairs) -// break -// default: -// assert(0) // Should not happen. -// } -// } -// STACK_DEL(&context, document.nodes) -// -// yaml_free(document.version_directive) -// for (tag_directive = document.tag_directives.start -// tag_directive != document.tag_directives.end -// tag_directive++) { -// yaml_free(tag_directive.handle) -// yaml_free(tag_directive.prefix) -// } -// yaml_free(document.tag_directives.start) -// -// memset(document, 0, sizeof(yaml_document_t)) -//} -// -///** -// * Get a document node. -// */ -// -//YAML_DECLARE(yaml_node_t *) -//yaml_document_get_node(document *yaml_document_t, index int) -//{ -// assert(document) // Non-NULL document object is expected. -// -// if (index > 0 && document.nodes.start + index <= document.nodes.top) { -// return document.nodes.start + index - 1 -// } -// return NULL -//} -// -///** -// * Get the root object. -// */ -// -//YAML_DECLARE(yaml_node_t *) -//yaml_document_get_root_node(document *yaml_document_t) -//{ -// assert(document) // Non-NULL document object is expected. -// -// if (document.nodes.top != document.nodes.start) { -// return document.nodes.start -// } -// return NULL -//} -// -///* -// * Add a scalar node to a document. -// */ -// -//YAML_DECLARE(int) -//yaml_document_add_scalar(document *yaml_document_t, -// tag *yaml_char_t, value *yaml_char_t, length int, -// style yaml_scalar_style_t) -//{ -// struct { -// error yaml_error_type_t -// } context -// mark yaml_mark_t = { 0, 0, 0 } -// tag_copy *yaml_char_t = NULL -// value_copy *yaml_char_t = NULL -// node yaml_node_t -// -// assert(document) // Non-NULL document object is expected. -// assert(value) // Non-NULL value is expected. -// -// if (!tag) { -// tag = (yaml_char_t *)YAML_DEFAULT_SCALAR_TAG -// } -// -// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error -// tag_copy = yaml_strdup(tag) -// if (!tag_copy) goto error -// -// if (length < 0) { -// length = strlen((char *)value) -// } -// -// if (!yaml_check_utf8(value, length)) goto error -// value_copy = yaml_malloc(length+1) -// if (!value_copy) goto error -// memcpy(value_copy, value, length) -// value_copy[length] = '\0' -// -// SCALAR_NODE_INIT(node, tag_copy, value_copy, length, style, mark, mark) -// if (!PUSH(&context, document.nodes, node)) goto error -// -// return document.nodes.top - document.nodes.start -// -//error: -// yaml_free(tag_copy) -// yaml_free(value_copy) -// -// return 0 -//} -// -///* -// * Add a sequence node to a document. -// */ -// -//YAML_DECLARE(int) -//yaml_document_add_sequence(document *yaml_document_t, -// tag *yaml_char_t, style yaml_sequence_style_t) -//{ -// struct { -// error yaml_error_type_t -// } context -// mark yaml_mark_t = { 0, 0, 0 } -// tag_copy *yaml_char_t = NULL -// struct { -// start *yaml_node_item_t -// end *yaml_node_item_t -// top *yaml_node_item_t -// } items = { NULL, NULL, NULL } -// node yaml_node_t -// -// assert(document) // Non-NULL document object is expected. -// -// if (!tag) { -// tag = (yaml_char_t *)YAML_DEFAULT_SEQUENCE_TAG -// } -// -// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error -// tag_copy = yaml_strdup(tag) -// if (!tag_copy) goto error -// -// if (!STACK_INIT(&context, items, INITIAL_STACK_SIZE)) goto error -// -// SEQUENCE_NODE_INIT(node, tag_copy, items.start, items.end, -// style, mark, mark) -// if (!PUSH(&context, document.nodes, node)) goto error -// -// return document.nodes.top - document.nodes.start -// -//error: -// STACK_DEL(&context, items) -// yaml_free(tag_copy) -// -// return 0 -//} -// -///* -// * Add a mapping node to a document. -// */ -// -//YAML_DECLARE(int) -//yaml_document_add_mapping(document *yaml_document_t, -// tag *yaml_char_t, style yaml_mapping_style_t) -//{ -// struct { -// error yaml_error_type_t -// } context -// mark yaml_mark_t = { 0, 0, 0 } -// tag_copy *yaml_char_t = NULL -// struct { -// start *yaml_node_pair_t -// end *yaml_node_pair_t -// top *yaml_node_pair_t -// } pairs = { NULL, NULL, NULL } -// node yaml_node_t -// -// assert(document) // Non-NULL document object is expected. -// -// if (!tag) { -// tag = (yaml_char_t *)YAML_DEFAULT_MAPPING_TAG -// } -// -// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error -// tag_copy = yaml_strdup(tag) -// if (!tag_copy) goto error -// -// if (!STACK_INIT(&context, pairs, INITIAL_STACK_SIZE)) goto error -// -// MAPPING_NODE_INIT(node, tag_copy, pairs.start, pairs.end, -// style, mark, mark) -// if (!PUSH(&context, document.nodes, node)) goto error -// -// return document.nodes.top - document.nodes.start -// -//error: -// STACK_DEL(&context, pairs) -// yaml_free(tag_copy) -// -// return 0 -//} -// -///* -// * Append an item to a sequence node. -// */ -// -//YAML_DECLARE(int) -//yaml_document_append_sequence_item(document *yaml_document_t, -// sequence int, item int) -//{ -// struct { -// error yaml_error_type_t -// } context -// -// assert(document) // Non-NULL document is required. -// assert(sequence > 0 -// && document.nodes.start + sequence <= document.nodes.top) -// // Valid sequence id is required. -// assert(document.nodes.start[sequence-1].type == YAML_SEQUENCE_NODE) -// // A sequence node is required. -// assert(item > 0 && document.nodes.start + item <= document.nodes.top) -// // Valid item id is required. -// -// if (!PUSH(&context, -// document.nodes.start[sequence-1].data.sequence.items, item)) -// return 0 -// -// return 1 -//} -// -///* -// * Append a pair of a key and a value to a mapping node. -// */ -// -//YAML_DECLARE(int) -//yaml_document_append_mapping_pair(document *yaml_document_t, -// mapping int, key int, value int) -//{ -// struct { -// error yaml_error_type_t -// } context -// -// pair yaml_node_pair_t -// -// assert(document) // Non-NULL document is required. -// assert(mapping > 0 -// && document.nodes.start + mapping <= document.nodes.top) -// // Valid mapping id is required. -// assert(document.nodes.start[mapping-1].type == YAML_MAPPING_NODE) -// // A mapping node is required. -// assert(key > 0 && document.nodes.start + key <= document.nodes.top) -// // Valid key id is required. -// assert(value > 0 && document.nodes.start + value <= document.nodes.top) -// // Valid value id is required. -// -// pair.key = key -// pair.value = value -// -// if (!PUSH(&context, -// document.nodes.start[mapping-1].data.mapping.pairs, pair)) -// return 0 -// -// return 1 -//} -// -// diff --git a/vendor/cuelang.org/go/internal/third_party/yaml/decode.go b/vendor/cuelang.org/go/internal/third_party/yaml/decode.go deleted file mode 100644 index 290e77f6cf..0000000000 --- a/vendor/cuelang.org/go/internal/third_party/yaml/decode.go +++ /dev/null @@ -1,725 +0,0 @@ -package yaml - -import ( - "encoding/base64" - "fmt" - "math" - "strconv" - "strings" - - "cuelang.org/go/cue/ast" - "cuelang.org/go/cue/literal" - "cuelang.org/go/cue/token" - "cuelang.org/go/internal" - "cuelang.org/go/internal/source" -) - -const ( - documentNode = 1 << iota - mappingNode - sequenceNode - scalarNode - aliasNode -) - -type node struct { - kind int - startPos yaml_mark_t - endPos yaml_mark_t - tag string - // For an alias node, alias holds the resolved alias. - alias *node - value string - implicit bool - children []*node - anchors map[string]*node -} - -// ---------------------------------------------------------------------------- -// Parser, produces a node tree out of a libyaml event stream. - -type parser struct { - parser yaml_parser_t - event yaml_event_t - doc *node - info *token.File - doneInit bool -} - -func newParser(filename string, src interface{}) (*parser, error) { - b, err := source.ReadAll(filename, src) - if err != nil { - return nil, err - } - info := token.NewFile(filename, -1, len(b)+2) - info.SetLinesForContent(b) - p := parser{info: info} - if !yaml_parser_initialize(&p.parser, filename) { - panic("failed to initialize YAML emitter") - } - if len(b) == 0 { - b = []byte{'\n'} - } - yaml_parser_set_input_string(&p.parser, b) - return &p, nil -} - -func (p *parser) init() { - if p.doneInit { - return - } - p.expect(yaml_STREAM_START_EVENT) - p.doneInit = true -} - -func (p *parser) destroy() { - if p.event.typ != yaml_NO_EVENT { - yaml_event_delete(&p.event) - } - yaml_parser_delete(&p.parser) -} - -// expect consumes an event from the event stream and -// checks that it's of the expected type. -func (p *parser) expect(e yaml_event_type_t) { - if p.event.typ == yaml_NO_EVENT { - if !yaml_parser_parse(&p.parser, &p.event) { - p.fail() - } - } - if p.event.typ == yaml_STREAM_END_EVENT { - p.failf(p.event.end_mark.line, "attempted to go past the end of stream; corrupted value?") - } - if p.event.typ != e { - p.parser.problem = fmt.Sprintf("expected %s event but got %s", e, p.event.typ) - p.fail() - } - yaml_event_delete(&p.event) - p.event.typ = yaml_NO_EVENT -} - -// peek peeks at the next event in the event stream, -// puts the results into p.event and returns the event type. -func (p *parser) peek() yaml_event_type_t { - if p.event.typ != yaml_NO_EVENT { - return p.event.typ - } - if !yaml_parser_parse(&p.parser, &p.event) { - p.fail() - } - return p.event.typ -} - -func (p *parser) fail() { - var line int - if p.parser.problem_mark.line != 0 { - line = p.parser.problem_mark.line - // Scanner errors don't iterate line before returning error - if p.parser.error != yaml_SCANNER_ERROR { - line-- - } - } else if p.parser.context_mark.line != 0 { - line = p.parser.context_mark.line - 1 - } - var msg string - if len(p.parser.problem) > 0 { - msg = p.parser.problem - } else { - msg = "unknown problem parsing YAML content" - } - p.failf(line, msg) -} - -func (p *parser) anchor(n *node, anchor []byte) { - if anchor != nil { - p.doc.anchors[string(anchor)] = n - } -} - -func (p *parser) parse() *node { - p.init() - switch p.peek() { - case yaml_SCALAR_EVENT: - return p.scalar() - case yaml_ALIAS_EVENT: - return p.alias() - case yaml_MAPPING_START_EVENT: - return p.mapping() - case yaml_SEQUENCE_START_EVENT: - return p.sequence() - case yaml_DOCUMENT_START_EVENT: - return p.document() - case yaml_STREAM_END_EVENT: - // Happens when attempting to decode an empty buffer. - return nil - default: - panic("attempted to parse unknown event: " + p.event.typ.String()) - } -} - -func (p *parser) node(kind int) *node { - n := &node{ - kind: kind, - startPos: p.event.start_mark, - endPos: p.event.end_mark, - } - return n -} - -func (p *parser) document() *node { - n := p.node(documentNode) - n.anchors = make(map[string]*node) - p.doc = n - p.expect(yaml_DOCUMENT_START_EVENT) - n.children = append(n.children, p.parse()) - p.expect(yaml_DOCUMENT_END_EVENT) - return n -} - -func (p *parser) alias() *node { - n := p.node(aliasNode) - n.value = string(p.event.anchor) - n.alias = p.doc.anchors[n.value] - if n.alias == nil { - p.failf(n.startPos.line, "unknown anchor '%s' referenced", n.value) - } - p.expect(yaml_ALIAS_EVENT) - return n -} - -func (p *parser) scalar() *node { - n := p.node(scalarNode) - n.value = string(p.event.value) - n.tag = string(p.event.tag) - n.implicit = p.event.implicit - p.anchor(n, p.event.anchor) - p.expect(yaml_SCALAR_EVENT) - return n -} - -func (p *parser) sequence() *node { - n := p.node(sequenceNode) - p.anchor(n, p.event.anchor) - p.expect(yaml_SEQUENCE_START_EVENT) - for p.peek() != yaml_SEQUENCE_END_EVENT { - n.children = append(n.children, p.parse()) - } - if len(n.children) > 0 { - n.endPos = n.children[len(n.children)-1].endPos - } else { - n.endPos = p.event.start_mark - } - p.expect(yaml_SEQUENCE_END_EVENT) - return n -} - -func (p *parser) mapping() *node { - n := p.node(mappingNode) - p.anchor(n, p.event.anchor) - p.expect(yaml_MAPPING_START_EVENT) - for p.peek() != yaml_MAPPING_END_EVENT { - n.children = append(n.children, p.parse(), p.parse()) - } - if len(n.children) > 0 { - n.endPos = n.children[len(n.children)-1].endPos - } - p.expect(yaml_MAPPING_END_EVENT) - return n -} - -// ---------------------------------------------------------------------------- -// Decoder, unmarshals a node into a provided value. - -type decoder struct { - p *parser - doc *node - aliases map[*node]bool - terrors []string - prev token.Pos - forceNewline bool -} - -func newDecoder(p *parser) *decoder { - d := &decoder{p: p} - d.aliases = make(map[*node]bool) - return d -} - -func (d *decoder) terror(n *node, tag string) string { - if n.tag != "" { - tag = n.tag - } - value := n.value - if tag != yaml_SEQ_TAG && tag != yaml_MAP_TAG { - if len(value) > 10 { - value = " `" + value[:7] + "...`" - } else { - value = " `" + value + "`" - } - } - msg := fmt.Sprintf("line %d: cannot unmarshal %s%s", n.startPos.line+1, shortTag(tag), value) - d.terrors = append(d.terrors, msg) - return msg -} - -func (d *decoder) unmarshal(n *node) (node ast.Expr) { - switch n.kind { - case documentNode: - node = d.document(n) - case aliasNode: - node = d.alias(n) - default: - switch n.kind { - case scalarNode: - node = d.scalar(n) - case mappingNode: - node = d.mapping(n) - case sequenceNode: - node = d.sequence(n) - default: - panic("internal error: unknown node kind: " + strconv.Itoa(n.kind)) - } - } - return node -} - -func (d *decoder) attachDocComments(m yaml_mark_t, pos int8, expr ast.Node) { - comments := []*ast.Comment{} - line := 0 - for len(d.p.parser.comments) > 0 { - c := d.p.parser.comments[0] - if c.mark.index >= m.index { - break - } - comments = append(comments, &ast.Comment{ - Slash: d.pos(c.mark), - Text: "//" + c.text[1:], - }) - d.p.parser.comments = d.p.parser.comments[1:] - line = c.mark.line - } - if len(comments) > 0 { - ast.AddComment(expr, &ast.CommentGroup{ - Doc: pos == 0 && line+1 == m.line, - Position: pos, - List: comments, - }) - } -} - -func (d *decoder) attachLineComment(m yaml_mark_t, pos int8, expr ast.Node) { - if len(d.p.parser.comments) == 0 { - return - } - c := d.p.parser.comments[0] - if c.mark.index == m.index { - comment := &ast.Comment{ - Slash: d.pos(c.mark), - Text: "//" + c.text[1:], - } - ast.AddComment(expr, &ast.CommentGroup{ - Line: true, - Position: pos, - List: []*ast.Comment{comment}, - }) - } -} - -func (d *decoder) pos(m yaml_mark_t) token.Pos { - pos := d.absPos(m) - - if d.forceNewline { - d.forceNewline = false - pos = pos.WithRel(token.Newline) - } else if d.prev.IsValid() { - c := pos.Position() - p := d.prev.Position() - switch { - case c.Line-p.Line >= 2: - pos = pos.WithRel(token.NewSection) - case c.Line-p.Line == 1: - pos = pos.WithRel(token.Newline) - case c.Column-p.Column > 0: - pos = pos.WithRel(token.Blank) - default: - pos = pos.WithRel(token.NoSpace) - } - if pos.Before(d.prev) { - return token.NoPos - } - } - - d.prev = pos - return pos -} - -func (d *decoder) absPos(m yaml_mark_t) token.Pos { - return d.p.info.Pos(m.index, token.NoRelPos) -} - -func (d *decoder) start(n *node) token.Pos { - if n.startPos == n.endPos { - return token.NoPos - } - return d.pos(n.startPos) -} - -func (d *decoder) ident(n *node, name string) *ast.Ident { - return &ast.Ident{ - NamePos: d.pos(n.startPos), - Name: name, - } -} - -func (d *decoder) document(n *node) ast.Expr { - if len(n.children) == 1 { - d.doc = n - return d.unmarshal(n.children[0]) - } - return &ast.BottomLit{} // TODO: more informatives -} - -func (d *decoder) alias(n *node) ast.Expr { - if d.aliases[n] { - // TODO this could actually be allowed in some circumstances. - d.p.failf(n.startPos.line, "anchor '%s' value contains itself", n.value) - } - d.aliases[n] = true - node := d.unmarshal(n.alias) - delete(d.aliases, n) - return node -} - -func (d *decoder) scalar(n *node) ast.Expr { - var tag string - var resolved interface{} - if n.tag == "" && !n.implicit { - tag = yaml_STR_TAG - resolved = n.value - } else { - tag, resolved = d.resolve(n) - if tag == yaml_BINARY_TAG { - data, err := base64.StdEncoding.DecodeString(resolved.(string)) - if err != nil { - d.p.failf(n.startPos.line, "!!binary value contains invalid base64 data") - } - resolved = string(data) - } - } - if resolved == nil { - return &ast.BasicLit{ - ValuePos: d.start(n).WithRel(token.Blank), - Kind: token.NULL, - Value: "null", - } - } - switch tag { - // TODO: use parse literal or parse expression instead. - case yaml_TIMESTAMP_TAG: - return &ast.BasicLit{ - ValuePos: d.start(n), - Kind: token.STRING, - Value: literal.String.Quote(n.value), - } - - case yaml_STR_TAG: - return &ast.BasicLit{ - ValuePos: d.start(n), - Kind: token.STRING, - Value: quoteString(n.value), - } - - case yaml_BINARY_TAG: - return &ast.BasicLit{ - ValuePos: d.start(n), - Kind: token.STRING, - Value: literal.Bytes.Quote(resolved.(string)), - } - - case yaml_BOOL_TAG: - tok := token.FALSE - str := "false" - if b, _ := resolved.(bool); b { - tok = token.TRUE - str = "true" - } - return &ast.BasicLit{ - ValuePos: d.start(n), - Kind: tok, - Value: str, - } - - case yaml_INT_TAG: - // Convert YAML octal to CUE octal. If YAML accepted an invalid - // integer, just convert it as well to ensure CUE will fail. - s := n.value - if len(s) > 1 && s[0] == '0' && s[1] <= '9' { - s = "0o" + s[1:] - } - return d.makeNum(n, s, token.INT) - - case yaml_FLOAT_TAG: - value := n.value - if f, ok := resolved.(float64); ok { - switch { - case math.IsInf(f, -1), - math.IsInf(f, 1), - math.IsNaN(f): - value = fmt.Sprint(f) - } - } - if n.tag != "" { - if p := strings.IndexAny(value, ".eEiInN"); p == -1 { - // TODO: float(v) when we have conversions - value = fmt.Sprintf("float & %s", value) - } - } - return d.makeNum(n, value, token.FLOAT) - - case yaml_NULL_TAG: - return &ast.BasicLit{ - ValuePos: d.start(n).WithRel(token.Blank), - Kind: token.NULL, - Value: "null", - } - } - d.terror(n, tag) - return &ast.BottomLit{} -} - -func (d *decoder) label(n *node) ast.Label { - pos := d.pos(n.startPos) - - switch x := d.scalar(n).(type) { - case *ast.BasicLit: - if x.Kind == token.STRING { - if ast.IsValidIdent(n.value) && !internal.IsDefOrHidden(n.value) { - return &ast.Ident{ - NamePos: pos, - Name: n.value, - } - } - ast.SetPos(x, pos) - return x - } - - return &ast.BasicLit{ - ValuePos: pos, - Kind: token.STRING, - Value: literal.Label.Quote(x.Value), - } - - default: - d.p.failf(n.startPos.line, "invalid label: %q", n.value) - } - - return &ast.BasicLit{ - ValuePos: pos, - Kind: token.STRING, - Value: "", - } -} - -func (d *decoder) makeNum(n *node, val string, kind token.Token) (expr ast.Expr) { - minuses := 0 - for ; val[0] == '-'; val = val[1:] { - minuses++ - } - expr = &ast.BasicLit{ - ValuePos: d.start(n), // + minuses.Pos(), - Kind: kind, - Value: val, - } - if minuses > 0 { - expr = &ast.UnaryExpr{ - OpPos: d.start(n), - Op: token.SUB, - X: expr, - } - } - return expr -} - -// quoteString converts a string to a CUE multiline string if needed. -func quoteString(s string) string { - lines := []string{} - last := 0 - for i, c := range s { - if c == '\n' { - lines = append(lines, s[last:i]) - last = i + 1 - } - if c == '\r' { - goto quoted - } - } - lines = append(lines, s[last:]) - if len(lines) >= 2 { - buf := []byte{} - buf = append(buf, `"""`+"\n"...) - for _, l := range lines { - if l == "" { - // no indentation for empty lines - buf = append(buf, '\n') - continue - } - buf = append(buf, '\t') - p := len(buf) - buf = strconv.AppendQuote(buf, l) - // remove quotes - buf[p] = '\t' - buf[len(buf)-1] = '\n' - } - buf = append(buf, "\t\t"+`"""`...) - return string(buf) - } -quoted: - return literal.String.Quote(s) -} - -func (d *decoder) sequence(n *node) ast.Expr { - list := &ast.ListLit{} - list.Lbrack = d.pos(n.startPos).WithRel(token.Blank) - switch ln := len(n.children); ln { - case 0: - d.prev = list.Lbrack - default: - d.prev = d.pos(n.children[ln-1].endPos) - } - list.Rbrack = d.pos(n.endPos) - - noNewline := true - single := d.isOneLiner(n.startPos, n.endPos) - for _, c := range n.children { - d.forceNewline = !single - elem := d.unmarshal(c) - list.Elts = append(list.Elts, elem) - _, noNewline = elem.(*ast.StructLit) - } - if !single && !noNewline { - list.Rbrack = list.Rbrack.WithRel(token.Newline) - } - return list -} - -func (d *decoder) isOneLiner(start, end yaml_mark_t) bool { - s := d.absPos(start).Position() - e := d.absPos(end).Position() - return s.Line == e.Line -} - -func (d *decoder) mapping(n *node) ast.Expr { - newline := d.forceNewline - - structure := &ast.StructLit{} - d.insertMap(n, structure, false) - - // NOTE: we currently translate YAML without curly braces to CUE with - // curly braces, even for single elements. Removing the following line - // would generate the folded form. - structure.Lbrace = d.absPos(n.startPos).WithRel(token.NoSpace) - structure.Rbrace = d.absPos(n.endPos).WithRel(token.Newline) - if d.isOneLiner(n.startPos, n.endPos) && !newline { - if len(structure.Elts) != 1 { - structure.Lbrace = d.absPos(n.startPos).WithRel(token.Blank) - } - if len(structure.Elts) != 1 || structure.Elts[0].Pos().RelPos() < token.Newline { - structure.Rbrace = structure.Rbrace.WithRel(token.Blank) - } - } - return structure -} - -func (d *decoder) insertMap(n *node, m *ast.StructLit, merge bool) { - l := len(n.children) -outer: - for i := 0; i < l; i += 2 { - if isMerge(n.children[i]) { - merge = true - d.merge(n.children[i+1], m) - continue - } - switch n.children[i].kind { - case mappingNode: - d.p.failf(n.startPos.line, "invalid map key: map") - case sequenceNode: - d.p.failf(n.startPos.line, "invalid map key: sequence") - } - - field := &ast.Field{} - d.attachDocComments(n.children[i].startPos, 0, field) - - label := d.label(n.children[i]) - field.Label = label - d.attachLineComment(n.children[i].endPos, 1, label) - - if merge { - key := labelStr(label) - for _, decl := range m.Elts { - f := decl.(*ast.Field) - name, _, err := ast.LabelName(f.Label) - if err == nil && name == key { - f.Value = d.unmarshal(n.children[i+1]) - continue outer - } - } - } - - value := d.unmarshal(n.children[i+1]) - field.Value = value - d.attachDocComments(n.children[i+1].startPos, 0, value) - d.attachLineComment(n.children[i+1].endPos, 10, value) - - m.Elts = append(m.Elts, field) - } -} - -func labelStr(l ast.Label) string { - switch x := l.(type) { - case *ast.Ident: - return x.Name - case *ast.BasicLit: - s, _ := strconv.Unquote(x.Value) - return s - } - return "" -} - -func (d *decoder) failWantMap(n *node) { - d.p.failf(n.startPos.line, "map merge requires map or sequence of maps as the value") -} - -func (d *decoder) merge(n *node, m *ast.StructLit) { - switch n.kind { - case mappingNode: - d.insertMap(n, m, true) - case aliasNode: - an, ok := d.doc.anchors[n.value] - if ok && an.kind != mappingNode { - d.failWantMap(n) - } - d.insertMap(an, m, true) - case sequenceNode: - // Step backwards as earlier nodes take precedence. - for i := len(n.children) - 1; i >= 0; i-- { - ni := n.children[i] - if ni.kind == aliasNode { - an, ok := d.doc.anchors[ni.value] - if ok && an.kind != mappingNode { - d.failWantMap(n) - } - d.insertMap(an, m, true) - continue - } else if ni.kind != mappingNode { - d.failWantMap(n) - } - d.insertMap(ni, m, true) - } - default: - d.failWantMap(n) - } -} - -func isMerge(n *node) bool { - return n.kind == scalarNode && n.value == "<<" && (n.implicit == true || n.tag == yaml_MERGE_TAG) -} diff --git a/vendor/cuelang.org/go/internal/third_party/yaml/parserc.go b/vendor/cuelang.org/go/internal/third_party/yaml/parserc.go deleted file mode 100644 index 6fcb5ec6f9..0000000000 --- a/vendor/cuelang.org/go/internal/third_party/yaml/parserc.go +++ /dev/null @@ -1,1117 +0,0 @@ -package yaml - -import ( - "bytes" -) - -// The parser implements the following grammar: -// -// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END -// implicit_document ::= block_node DOCUMENT-END* -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// block_node_or_indentless_sequence ::= -// ALIAS -// | properties (block_content | indentless_block_sequence)? -// | block_content -// | indentless_block_sequence -// block_node ::= ALIAS -// | properties block_content? -// | block_content -// flow_node ::= ALIAS -// | properties flow_content? -// | flow_content -// properties ::= TAG ANCHOR? | ANCHOR TAG? -// block_content ::= block_collection | flow_collection | SCALAR -// flow_content ::= flow_collection | SCALAR -// block_collection ::= block_sequence | block_mapping -// flow_collection ::= flow_sequence | flow_mapping -// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END -// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ -// block_mapping ::= BLOCK-MAPPING_START -// ((KEY block_node_or_indentless_sequence?)? -// (VALUE block_node_or_indentless_sequence?)?)* -// BLOCK-END -// flow_sequence ::= FLOW-SEQUENCE-START -// (flow_sequence_entry FLOW-ENTRY)* -// flow_sequence_entry? -// FLOW-SEQUENCE-END -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// flow_mapping ::= FLOW-MAPPING-START -// (flow_mapping_entry FLOW-ENTRY)* -// flow_mapping_entry? -// FLOW-MAPPING-END -// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? - -// Peek the next token in the token queue. -func peek_token(parser *yaml_parser_t) *yaml_token_t { - if parser.token_available || yaml_parser_fetch_more_tokens(parser) { - return &parser.tokens[parser.tokens_head] - } - return nil -} - -// Remove the next token from the queue (must be called after peek_token). -func skip_token(parser *yaml_parser_t) { - parser.token_available = false - parser.tokens_parsed++ - parser.stream_end_produced = parser.tokens[parser.tokens_head].typ == yaml_STREAM_END_TOKEN - parser.tokens_head++ -} - -func add_comment(parser *yaml_parser_t, m yaml_mark_t, text string) { - parser.comments = append(parser.comments, yaml_comment_t{ - mark: m, - text: text, - }) -} - -// Get the next event. -func yaml_parser_parse(parser *yaml_parser_t, event *yaml_event_t) bool { - // Erase the event object. - *event = yaml_event_t{} - - // No events after the end of the stream or error. - if parser.stream_end_produced || parser.error != yaml_NO_ERROR || parser.state == yaml_PARSE_END_STATE { - return true - } - - // Generate the next event. - return yaml_parser_state_machine(parser, event) -} - -// Set parser error. -func yaml_parser_set_parser_error(parser *yaml_parser_t, problem string, problem_mark yaml_mark_t) bool { - parser.error = yaml_PARSER_ERROR - parser.problem = problem - parser.problem_mark = problem_mark - return false -} - -func yaml_parser_set_parser_error_context(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string, problem_mark yaml_mark_t) bool { - parser.error = yaml_PARSER_ERROR - parser.context = context - parser.context_mark = context_mark - parser.problem = problem - parser.problem_mark = problem_mark - return false -} - -// State dispatcher. -func yaml_parser_state_machine(parser *yaml_parser_t, event *yaml_event_t) bool { - //trace("yaml_parser_state_machine", "state:", parser.state.String()) - - switch parser.state { - case yaml_PARSE_STREAM_START_STATE: - return yaml_parser_parse_stream_start(parser, event) - - case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: - return yaml_parser_parse_document_start(parser, event, true) - - case yaml_PARSE_DOCUMENT_START_STATE: - return yaml_parser_parse_document_start(parser, event, false) - - case yaml_PARSE_DOCUMENT_CONTENT_STATE: - return yaml_parser_parse_document_content(parser, event) - - case yaml_PARSE_DOCUMENT_END_STATE: - return yaml_parser_parse_document_end(parser, event) - - case yaml_PARSE_BLOCK_NODE_STATE: - return yaml_parser_parse_node(parser, event, true, false) - - case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: - return yaml_parser_parse_node(parser, event, true, true) - - case yaml_PARSE_FLOW_NODE_STATE: - return yaml_parser_parse_node(parser, event, false, false) - - case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: - return yaml_parser_parse_block_sequence_entry(parser, event, true) - - case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: - return yaml_parser_parse_block_sequence_entry(parser, event, false) - - case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: - return yaml_parser_parse_indentless_sequence_entry(parser, event) - - case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: - return yaml_parser_parse_block_mapping_key(parser, event, true) - - case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: - return yaml_parser_parse_block_mapping_key(parser, event, false) - - case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: - return yaml_parser_parse_block_mapping_value(parser, event) - - case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: - return yaml_parser_parse_flow_sequence_entry(parser, event, true) - - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: - return yaml_parser_parse_flow_sequence_entry(parser, event, false) - - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: - return yaml_parser_parse_flow_sequence_entry_mapping_key(parser, event) - - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: - return yaml_parser_parse_flow_sequence_entry_mapping_value(parser, event) - - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: - return yaml_parser_parse_flow_sequence_entry_mapping_end(parser, event) - - case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: - return yaml_parser_parse_flow_mapping_key(parser, event, true) - - case yaml_PARSE_FLOW_MAPPING_KEY_STATE: - return yaml_parser_parse_flow_mapping_key(parser, event, false) - - case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: - return yaml_parser_parse_flow_mapping_value(parser, event, false) - - case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: - return yaml_parser_parse_flow_mapping_value(parser, event, true) - - default: - panic("invalid parser state") - } -} - -// Parse the production: -// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END -// -// ************ -func yaml_parser_parse_stream_start(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_STREAM_START_TOKEN { - return yaml_parser_set_parser_error(parser, "did not find expected ", token.start_mark) - } - parser.state = yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE - *event = yaml_event_t{ - typ: yaml_STREAM_START_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - encoding: token.encoding, - } - skip_token(parser) - return true -} - -// Parse the productions: -// implicit_document ::= block_node DOCUMENT-END* -// -// * -// -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// -// ************************* -func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t, implicit bool) bool { - - token := peek_token(parser) - if token == nil { - return false - } - - // Parse extra document end indicators. - if !implicit { - for token.typ == yaml_DOCUMENT_END_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } - } - - if implicit && token.typ != yaml_VERSION_DIRECTIVE_TOKEN && - token.typ != yaml_TAG_DIRECTIVE_TOKEN && - token.typ != yaml_DOCUMENT_START_TOKEN && - token.typ != yaml_STREAM_END_TOKEN { - // Parse an implicit document. - if !yaml_parser_process_directives(parser, nil, nil) { - return false - } - parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) - parser.state = yaml_PARSE_BLOCK_NODE_STATE - - *event = yaml_event_t{ - typ: yaml_DOCUMENT_START_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - - } else if token.typ != yaml_STREAM_END_TOKEN { - // Parse an explicit document. - var version_directive *yaml_version_directive_t - var tag_directives []yaml_tag_directive_t - start_mark := token.start_mark - if !yaml_parser_process_directives(parser, &version_directive, &tag_directives) { - return false - } - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_DOCUMENT_START_TOKEN { - yaml_parser_set_parser_error(parser, - "did not find expected ", token.start_mark) - return false - } - parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) - parser.state = yaml_PARSE_DOCUMENT_CONTENT_STATE - end_mark := token.end_mark - - *event = yaml_event_t{ - typ: yaml_DOCUMENT_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - version_directive: version_directive, - tag_directives: tag_directives, - implicit: false, - } - skip_token(parser) - - } else { - // Parse the stream end. - parser.state = yaml_PARSE_END_STATE - *event = yaml_event_t{ - typ: yaml_STREAM_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - skip_token(parser) - } - - return true -} - -// Parse the productions: -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// -// *********** -func yaml_parser_parse_document_content(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_VERSION_DIRECTIVE_TOKEN || - token.typ == yaml_TAG_DIRECTIVE_TOKEN || - token.typ == yaml_DOCUMENT_START_TOKEN || - token.typ == yaml_DOCUMENT_END_TOKEN || - token.typ == yaml_STREAM_END_TOKEN { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - return yaml_parser_process_empty_scalar(parser, event, - token.start_mark) - } - return yaml_parser_parse_node(parser, event, true, false) -} - -// Parse the productions: -// implicit_document ::= block_node DOCUMENT-END* -// -// ************* -// -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -func yaml_parser_parse_document_end(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - - start_mark := token.start_mark - end_mark := token.start_mark - - implicit := true - if token.typ == yaml_DOCUMENT_END_TOKEN { - end_mark = token.end_mark - skip_token(parser) - implicit = false - } - - parser.tag_directives = parser.tag_directives[:0] - - parser.state = yaml_PARSE_DOCUMENT_START_STATE - *event = yaml_event_t{ - typ: yaml_DOCUMENT_END_EVENT, - start_mark: start_mark, - end_mark: end_mark, - implicit: implicit, - } - return true -} - -// Parse the productions: -// block_node_or_indentless_sequence ::= -// -// ALIAS -// ***** -// | properties (block_content | indentless_block_sequence)? -// ********** * -// | block_content | indentless_block_sequence -// * -// -// block_node ::= ALIAS -// -// ***** -// | properties block_content? -// ********** * -// | block_content -// * -// -// flow_node ::= ALIAS -// -// ***** -// | properties flow_content? -// ********** * -// | flow_content -// * -// -// properties ::= TAG ANCHOR? | ANCHOR TAG? -// -// ************************* -// -// block_content ::= block_collection | flow_collection | SCALAR -// -// ****** -// -// flow_content ::= flow_collection | SCALAR -// -// ****** -func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, indentless_sequence bool) bool { - //defer trace("yaml_parser_parse_node", "block:", block, "indentless_sequence:", indentless_sequence)() - - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ == yaml_ALIAS_TOKEN { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - *event = yaml_event_t{ - typ: yaml_ALIAS_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - anchor: token.value, - } - skip_token(parser) - return true - } - - start_mark := token.start_mark - end_mark := token.start_mark - - var tag_token bool - var tag_handle, tag_suffix, anchor []byte - var tag_mark yaml_mark_t - if token.typ == yaml_ANCHOR_TOKEN { - anchor = token.value - start_mark = token.start_mark - end_mark = token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_TAG_TOKEN { - tag_token = true - tag_handle = token.value - tag_suffix = token.suffix - tag_mark = token.start_mark - end_mark = token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } - } else if token.typ == yaml_TAG_TOKEN { - tag_token = true - tag_handle = token.value - tag_suffix = token.suffix - start_mark = token.start_mark - tag_mark = token.start_mark - end_mark = token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_ANCHOR_TOKEN { - anchor = token.value - end_mark = token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } - } - - var tag []byte - if tag_token { - if len(tag_handle) == 0 { - tag = tag_suffix - tag_suffix = nil - } else { - for i := range parser.tag_directives { - if bytes.Equal(parser.tag_directives[i].handle, tag_handle) { - tag = append([]byte(nil), parser.tag_directives[i].prefix...) - tag = append(tag, tag_suffix...) - break - } - } - if len(tag) == 0 { - yaml_parser_set_parser_error_context(parser, - "while parsing a node", start_mark, - "found undefined tag handle", tag_mark) - return false - } - } - } - - implicit := len(tag) == 0 - if indentless_sequence && token.typ == yaml_BLOCK_ENTRY_TOKEN { - end_mark = token.end_mark - parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE - *event = yaml_event_t{ - typ: yaml_SEQUENCE_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), - } - return true - } - if token.typ == yaml_SCALAR_TOKEN { - var plain_implicit, quoted_implicit bool - end_mark = token.end_mark - if (len(tag) == 0 && token.style == yaml_PLAIN_SCALAR_STYLE) || (len(tag) == 1 && tag[0] == '!') { - plain_implicit = true - } else if len(tag) == 0 { - quoted_implicit = true - } - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - - *event = yaml_event_t{ - typ: yaml_SCALAR_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - value: token.value, - implicit: plain_implicit, - quoted_implicit: quoted_implicit, - style: yaml_style_t(token.style), - } - skip_token(parser) - return true - } - if token.typ == yaml_FLOW_SEQUENCE_START_TOKEN { - // [Go] Some of the events below can be merged as they differ only on style. - end_mark = token.end_mark - parser.state = yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE - *event = yaml_event_t{ - typ: yaml_SEQUENCE_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_FLOW_SEQUENCE_STYLE), - } - return true - } - if token.typ == yaml_FLOW_MAPPING_START_TOKEN { - end_mark = token.end_mark - parser.state = yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE - *event = yaml_event_t{ - typ: yaml_MAPPING_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), - } - return true - } - if block && token.typ == yaml_BLOCK_SEQUENCE_START_TOKEN { - end_mark = token.end_mark - parser.state = yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE - *event = yaml_event_t{ - typ: yaml_SEQUENCE_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), - } - return true - } - if block && token.typ == yaml_BLOCK_MAPPING_START_TOKEN { - end_mark = token.end_mark - parser.state = yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE - *event = yaml_event_t{ - typ: yaml_MAPPING_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_BLOCK_MAPPING_STYLE), - } - return true - } - if len(anchor) > 0 || len(tag) > 0 { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - - *event = yaml_event_t{ - typ: yaml_SCALAR_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - quoted_implicit: false, - style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), - } - return true - } - - context := "while parsing a flow node" - if block { - context = "while parsing a block node" - } - yaml_parser_set_parser_error_context(parser, context, start_mark, - "did not find expected node content", token.start_mark) - return false -} - -// Parse the productions: -// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END -// -// ******************** *********** * ********* -func yaml_parser_parse_block_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { - if first { - token := peek_token(parser) - parser.marks = append(parser.marks, token.start_mark) - skip_token(parser) - } - - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ == yaml_BLOCK_ENTRY_TOKEN { - mark := token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_BLOCK_ENTRY_TOKEN && token.typ != yaml_BLOCK_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE) - return yaml_parser_parse_node(parser, event, true, false) - } else { - parser.state = yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) - } - } - if token.typ == yaml_BLOCK_END_TOKEN { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - - *event = yaml_event_t{ - typ: yaml_SEQUENCE_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - - skip_token(parser) - return true - } - - context_mark := parser.marks[len(parser.marks)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - return yaml_parser_set_parser_error_context(parser, - "while parsing a block collection", context_mark, - "did not find expected '-' indicator", token.start_mark) -} - -// Parse the productions: -// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ -// -// *********** * -func yaml_parser_parse_indentless_sequence_entry(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ == yaml_BLOCK_ENTRY_TOKEN { - mark := token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_BLOCK_ENTRY_TOKEN && - token.typ != yaml_KEY_TOKEN && - token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_BLOCK_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE) - return yaml_parser_parse_node(parser, event, true, false) - } - parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) - } - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - - *event = yaml_event_t{ - typ: yaml_SEQUENCE_END_EVENT, - start_mark: token.start_mark, - end_mark: token.start_mark, // [Go] Shouldn't this be token.end_mark? - } - return true -} - -// Parse the productions: -// block_mapping ::= BLOCK-MAPPING_START -// -// ******************* -// ((KEY block_node_or_indentless_sequence?)? -// *** * -// (VALUE block_node_or_indentless_sequence?)?)* -// -// BLOCK-END -// ********* -func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { - if first { - token := peek_token(parser) - parser.marks = append(parser.marks, token.start_mark) - skip_token(parser) - } - - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ == yaml_KEY_TOKEN { - mark := token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_KEY_TOKEN && - token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_BLOCK_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_VALUE_STATE) - return yaml_parser_parse_node(parser, event, true, true) - } else { - parser.state = yaml_PARSE_BLOCK_MAPPING_VALUE_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) - } - } else if token.typ == yaml_BLOCK_END_TOKEN { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - *event = yaml_event_t{ - typ: yaml_MAPPING_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - skip_token(parser) - return true - } - - context_mark := parser.marks[len(parser.marks)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - return yaml_parser_set_parser_error_context(parser, - "while parsing a block mapping", context_mark, - "did not find expected key", token.start_mark) -} - -// Parse the productions: -// block_mapping ::= BLOCK-MAPPING_START -// -// ((KEY block_node_or_indentless_sequence?)? -// -// (VALUE block_node_or_indentless_sequence?)?)* -// ***** * -// BLOCK-END -func yaml_parser_parse_block_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_VALUE_TOKEN { - mark := token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_KEY_TOKEN && - token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_BLOCK_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_KEY_STATE) - return yaml_parser_parse_node(parser, event, true, true) - } - parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) - } - parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) -} - -// Parse the productions: -// flow_sequence ::= FLOW-SEQUENCE-START -// -// ******************* -// (flow_sequence_entry FLOW-ENTRY)* -// * ********** -// flow_sequence_entry? -// * -// FLOW-SEQUENCE-END -// ***************** -// -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// -// * -func yaml_parser_parse_flow_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { - if first { - token := peek_token(parser) - parser.marks = append(parser.marks, token.start_mark) - skip_token(parser) - } - token := peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { - if !first { - if token.typ == yaml_FLOW_ENTRY_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } else { - context_mark := parser.marks[len(parser.marks)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - return yaml_parser_set_parser_error_context(parser, - "while parsing a flow sequence", context_mark, - "did not find expected ',' or ']'", token.start_mark) - } - } - - if token.typ == yaml_KEY_TOKEN { - parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE - *event = yaml_event_t{ - typ: yaml_MAPPING_START_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - implicit: true, - style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), - } - skip_token(parser) - return true - } else if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - } - - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - - *event = yaml_event_t{ - typ: yaml_SEQUENCE_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - - skip_token(parser) - return true -} - -// Parse the productions: -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// -// *** * -func yaml_parser_parse_flow_sequence_entry_mapping_key(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_FLOW_ENTRY_TOKEN && - token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - mark := token.end_mark - skip_token(parser) - parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) -} - -// Parse the productions: -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// -// ***** * -func yaml_parser_parse_flow_sequence_entry_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_VALUE_TOKEN { - skip_token(parser) - token := peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - } - parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) -} - -// Parse the productions: -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// -// * -func yaml_parser_parse_flow_sequence_entry_mapping_end(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE - *event = yaml_event_t{ - typ: yaml_MAPPING_END_EVENT, - start_mark: token.start_mark, - end_mark: token.start_mark, // [Go] Shouldn't this be end_mark? - } - return true -} - -// Parse the productions: -// flow_mapping ::= FLOW-MAPPING-START -// -// ****************** -// (flow_mapping_entry FLOW-ENTRY)* -// * ********** -// flow_mapping_entry? -// ****************** -// FLOW-MAPPING-END -// **************** -// -// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// - *** * -func yaml_parser_parse_flow_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { - if first { - token := peek_token(parser) - parser.marks = append(parser.marks, token.start_mark) - skip_token(parser) - } - - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ != yaml_FLOW_MAPPING_END_TOKEN { - if !first { - if token.typ == yaml_FLOW_ENTRY_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } else { - context_mark := parser.marks[len(parser.marks)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - return yaml_parser_set_parser_error_context(parser, - "while parsing a flow mapping", context_mark, - "did not find expected ',' or '}'", token.start_mark) - } - } - - if token.typ == yaml_KEY_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_FLOW_ENTRY_TOKEN && - token.typ != yaml_FLOW_MAPPING_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_VALUE_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } else { - parser.state = yaml_PARSE_FLOW_MAPPING_VALUE_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) - } - } else if token.typ != yaml_FLOW_MAPPING_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - } - - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - *event = yaml_event_t{ - typ: yaml_MAPPING_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - skip_token(parser) - return true -} - -// Parse the productions: -// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// - ***** * -func yaml_parser_parse_flow_mapping_value(parser *yaml_parser_t, event *yaml_event_t, empty bool) bool { - token := peek_token(parser) - if token == nil { - return false - } - if empty { - parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) - } - if token.typ == yaml_VALUE_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_MAPPING_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_KEY_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - } - parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) -} - -// Generate an empty scalar event. -func yaml_parser_process_empty_scalar(parser *yaml_parser_t, event *yaml_event_t, mark yaml_mark_t) bool { - *event = yaml_event_t{ - typ: yaml_SCALAR_EVENT, - start_mark: mark, - end_mark: mark, - value: nil, // Empty - implicit: true, - style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), - } - return true -} - -var default_tag_directives = []yaml_tag_directive_t{ - {[]byte("!"), []byte("!")}, - {[]byte("!!"), []byte("tag:yaml.org,2002:")}, -} - -// Parse directives. -func yaml_parser_process_directives(parser *yaml_parser_t, version_directive_ref **yaml_version_directive_t, - tag_directives_ref *[]yaml_tag_directive_t) bool { - - var version_directive *yaml_version_directive_t - var tag_directives []yaml_tag_directive_t - - token := peek_token(parser) - if token == nil { - return false - } - - for token.typ == yaml_VERSION_DIRECTIVE_TOKEN || token.typ == yaml_TAG_DIRECTIVE_TOKEN { - if token.typ == yaml_VERSION_DIRECTIVE_TOKEN { - if version_directive != nil { - yaml_parser_set_parser_error(parser, - "found duplicate %YAML directive", token.start_mark) - return false - } - if token.major != 1 || token.minor != 1 { - yaml_parser_set_parser_error(parser, - "found incompatible YAML document", token.start_mark) - return false - } - version_directive = &yaml_version_directive_t{ - major: token.major, - minor: token.minor, - } - } else if token.typ == yaml_TAG_DIRECTIVE_TOKEN { - value := yaml_tag_directive_t{ - handle: token.value, - prefix: token.prefix, - } - if !yaml_parser_append_tag_directive(parser, value, false, token.start_mark) { - return false - } - tag_directives = append(tag_directives, value) - } - - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } - - for i := range default_tag_directives { - if !yaml_parser_append_tag_directive(parser, default_tag_directives[i], true, token.start_mark) { - return false - } - } - - if version_directive_ref != nil { - *version_directive_ref = version_directive - } - if tag_directives_ref != nil { - *tag_directives_ref = tag_directives - } - return true -} - -// Append a tag directive to the directives stack. -func yaml_parser_append_tag_directive(parser *yaml_parser_t, value yaml_tag_directive_t, allow_duplicates bool, mark yaml_mark_t) bool { - for i := range parser.tag_directives { - if bytes.Equal(value.handle, parser.tag_directives[i].handle) { - if allow_duplicates { - return true - } - return yaml_parser_set_parser_error(parser, "found duplicate %TAG directive", mark) - } - } - - // [Go] I suspect the copy is unnecessary. This was likely done - // because there was no way to track ownership of the data. - value_copy := yaml_tag_directive_t{ - handle: make([]byte, len(value.handle)), - prefix: make([]byte, len(value.prefix)), - } - copy(value_copy.handle, value.handle) - copy(value_copy.prefix, value.prefix) - parser.tag_directives = append(parser.tag_directives, value_copy) - return true -} diff --git a/vendor/cuelang.org/go/internal/third_party/yaml/readerc.go b/vendor/cuelang.org/go/internal/third_party/yaml/readerc.go deleted file mode 100644 index b0c436c4a8..0000000000 --- a/vendor/cuelang.org/go/internal/third_party/yaml/readerc.go +++ /dev/null @@ -1,412 +0,0 @@ -package yaml - -import ( - "io" -) - -// Set the reader error and return 0. -func yaml_parser_set_reader_error(parser *yaml_parser_t, problem string, offset int, value int) bool { - parser.error = yaml_READER_ERROR - parser.problem = problem - parser.problem_offset = offset - parser.problem_value = value - return false -} - -// Byte order marks. -const ( - bom_UTF8 = "\xef\xbb\xbf" - bom_UTF16LE = "\xff\xfe" - bom_UTF16BE = "\xfe\xff" -) - -// Determine the input stream encoding by checking the BOM symbol. If no BOM is -// found, the UTF-8 encoding is assumed. Return 1 on success, 0 on failure. -func yaml_parser_determine_encoding(parser *yaml_parser_t) bool { - // Ensure that we had enough bytes in the raw buffer. - for !parser.eof && len(parser.raw_buffer)-parser.raw_buffer_pos < 3 { - if !yaml_parser_update_raw_buffer(parser) { - return false - } - } - - // Determine the encoding. - buf := parser.raw_buffer - pos := parser.raw_buffer_pos - avail := len(buf) - pos - if avail >= 2 && buf[pos] == bom_UTF16LE[0] && buf[pos+1] == bom_UTF16LE[1] { - parser.encoding = yaml_UTF16LE_ENCODING - parser.raw_buffer_pos += 2 - parser.offset += 2 - } else if avail >= 2 && buf[pos] == bom_UTF16BE[0] && buf[pos+1] == bom_UTF16BE[1] { - parser.encoding = yaml_UTF16BE_ENCODING - parser.raw_buffer_pos += 2 - parser.offset += 2 - } else if avail >= 3 && buf[pos] == bom_UTF8[0] && buf[pos+1] == bom_UTF8[1] && buf[pos+2] == bom_UTF8[2] { - parser.encoding = yaml_UTF8_ENCODING - parser.raw_buffer_pos += 3 - parser.offset += 3 - } else { - parser.encoding = yaml_UTF8_ENCODING - } - return true -} - -// Update the raw buffer. -func yaml_parser_update_raw_buffer(parser *yaml_parser_t) bool { - size_read := 0 - - // Return if the raw buffer is full. - if parser.raw_buffer_pos == 0 && len(parser.raw_buffer) == cap(parser.raw_buffer) { - return true - } - - // Return on EOF. - if parser.eof { - return true - } - - // Move the remaining bytes in the raw buffer to the beginning. - if parser.raw_buffer_pos > 0 && parser.raw_buffer_pos < len(parser.raw_buffer) { - copy(parser.raw_buffer, parser.raw_buffer[parser.raw_buffer_pos:]) - } - parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)-parser.raw_buffer_pos] - parser.raw_buffer_pos = 0 - - // Call the read handler to fill the buffer. - size_read, err := parser.read_handler(parser, parser.raw_buffer[len(parser.raw_buffer):cap(parser.raw_buffer)]) - parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)+size_read] - if err == io.EOF { - parser.eof = true - } else if err != nil { - return yaml_parser_set_reader_error(parser, "input error: "+err.Error(), parser.offset, -1) - } - return true -} - -// Ensure that the buffer contains at least `length` characters. -// Return true on success, false on failure. -// -// The length is supposed to be significantly less that the buffer size. -func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool { - if parser.read_handler == nil { - panic("read handler must be set") - } - - // [Go] This function was changed to guarantee the requested length size at EOF. - // The fact we need to do this is pretty awful, but the description above implies - // for that to be the case, and there are tests - - // If the EOF flag is set and the raw buffer is empty, do nothing. - if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) { - // [Go] ACTUALLY! Read the documentation of this function above. - // This is just broken. To return true, we need to have the - // given length in the buffer. Not doing that means every single - // check that calls this function to make sure the buffer has a - // given length is Go) panicking; or C) accessing invalid memory. - //return true - } - - // Return if the buffer contains enough characters. - if parser.unread >= length { - return true - } - - // Determine the input encoding if it is not known yet. - if parser.encoding == yaml_ANY_ENCODING { - if !yaml_parser_determine_encoding(parser) { - return false - } - } - - // Move the unread characters to the beginning of the buffer. - buffer_len := len(parser.buffer) - if parser.buffer_pos > 0 && parser.buffer_pos < buffer_len { - copy(parser.buffer, parser.buffer[parser.buffer_pos:]) - buffer_len -= parser.buffer_pos - parser.buffer_pos = 0 - } else if parser.buffer_pos == buffer_len { - buffer_len = 0 - parser.buffer_pos = 0 - } - - // Open the whole buffer for writing, and cut it before returning. - parser.buffer = parser.buffer[:cap(parser.buffer)] - - // Fill the buffer until it has enough characters. - first := true - for parser.unread < length { - - // Fill the raw buffer if necessary. - if !first || parser.raw_buffer_pos == len(parser.raw_buffer) { - if !yaml_parser_update_raw_buffer(parser) { - parser.buffer = parser.buffer[:buffer_len] - return false - } - } - first = false - - // Decode the raw buffer. - inner: - for parser.raw_buffer_pos != len(parser.raw_buffer) { - var value rune - var width int - - raw_unread := len(parser.raw_buffer) - parser.raw_buffer_pos - - // Decode the next character. - switch parser.encoding { - case yaml_UTF8_ENCODING: - // Decode a UTF-8 character. Check RFC 3629 - // (http://www.ietf.org/rfc/rfc3629.txt) for more details. - // - // The following table (taken from the RFC) is used for - // decoding. - // - // Char. number range | UTF-8 octet sequence - // (hexadecimal) | (binary) - // --------------------+------------------------------------ - // 0000 0000-0000 007F | 0xxxxxxx - // 0000 0080-0000 07FF | 110xxxxx 10xxxxxx - // 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx - // 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - // - // Additionally, the characters in the range 0xD800-0xDFFF - // are prohibited as they are reserved for use with UTF-16 - // surrogate pairs. - - // Determine the length of the UTF-8 sequence. - octet := parser.raw_buffer[parser.raw_buffer_pos] - switch { - case octet&0x80 == 0x00: - width = 1 - case octet&0xE0 == 0xC0: - width = 2 - case octet&0xF0 == 0xE0: - width = 3 - case octet&0xF8 == 0xF0: - width = 4 - default: - // The leading octet is invalid. - return yaml_parser_set_reader_error(parser, - "invalid leading UTF-8 octet", - parser.offset, int(octet)) - } - - // Check if the raw buffer contains an incomplete character. - if width > raw_unread { - if parser.eof { - return yaml_parser_set_reader_error(parser, - "incomplete UTF-8 octet sequence", - parser.offset, -1) - } - break inner - } - - // Decode the leading octet. - switch { - case octet&0x80 == 0x00: - value = rune(octet & 0x7F) - case octet&0xE0 == 0xC0: - value = rune(octet & 0x1F) - case octet&0xF0 == 0xE0: - value = rune(octet & 0x0F) - case octet&0xF8 == 0xF0: - value = rune(octet & 0x07) - default: - value = 0 - } - - // Check and decode the trailing octets. - for k := 1; k < width; k++ { - octet = parser.raw_buffer[parser.raw_buffer_pos+k] - - // Check if the octet is valid. - if (octet & 0xC0) != 0x80 { - return yaml_parser_set_reader_error(parser, - "invalid trailing UTF-8 octet", - parser.offset+k, int(octet)) - } - - // Decode the octet. - value = (value << 6) + rune(octet&0x3F) - } - - // Check the length of the sequence against the value. - switch { - case width == 1: - case width == 2 && value >= 0x80: - case width == 3 && value >= 0x800: - case width == 4 && value >= 0x10000: - default: - return yaml_parser_set_reader_error(parser, - "invalid length of a UTF-8 sequence", - parser.offset, -1) - } - - // Check the range of the value. - if value >= 0xD800 && value <= 0xDFFF || value > 0x10FFFF { - return yaml_parser_set_reader_error(parser, - "invalid Unicode character", - parser.offset, int(value)) - } - - case yaml_UTF16LE_ENCODING, yaml_UTF16BE_ENCODING: - var low, high int - if parser.encoding == yaml_UTF16LE_ENCODING { - low, high = 0, 1 - } else { - low, high = 1, 0 - } - - // The UTF-16 encoding is not as simple as one might - // naively think. Check RFC 2781 - // (http://www.ietf.org/rfc/rfc2781.txt). - // - // Normally, two subsequent bytes describe a Unicode - // character. However a special technique (called a - // surrogate pair) is used for specifying character - // values larger than 0xFFFF. - // - // A surrogate pair consists of two pseudo-characters: - // high surrogate area (0xD800-0xDBFF) - // low surrogate area (0xDC00-0xDFFF) - // - // The following formulas are used for decoding - // and encoding characters using surrogate pairs: - // - // U = U' + 0x10000 (0x01 00 00 <= U <= 0x10 FF FF) - // U' = yyyyyyyyyyxxxxxxxxxx (0 <= U' <= 0x0F FF FF) - // W1 = 110110yyyyyyyyyy - // W2 = 110111xxxxxxxxxx - // - // where U is the character value, W1 is the high surrogate - // area, W2 is the low surrogate area. - - // Check for incomplete UTF-16 character. - if raw_unread < 2 { - if parser.eof { - return yaml_parser_set_reader_error(parser, - "incomplete UTF-16 character", - parser.offset, -1) - } - break inner - } - - // Get the character. - value = rune(parser.raw_buffer[parser.raw_buffer_pos+low]) + - (rune(parser.raw_buffer[parser.raw_buffer_pos+high]) << 8) - - // Check for unexpected low surrogate area. - if value&0xFC00 == 0xDC00 { - return yaml_parser_set_reader_error(parser, - "unexpected low surrogate area", - parser.offset, int(value)) - } - - // Check for a high surrogate area. - if value&0xFC00 == 0xD800 { - width = 4 - - // Check for incomplete surrogate pair. - if raw_unread < 4 { - if parser.eof { - return yaml_parser_set_reader_error(parser, - "incomplete UTF-16 surrogate pair", - parser.offset, -1) - } - break inner - } - - // Get the next character. - value2 := rune(parser.raw_buffer[parser.raw_buffer_pos+low+2]) + - (rune(parser.raw_buffer[parser.raw_buffer_pos+high+2]) << 8) - - // Check for a low surrogate area. - if value2&0xFC00 != 0xDC00 { - return yaml_parser_set_reader_error(parser, - "expected low surrogate area", - parser.offset+2, int(value2)) - } - - // Generate the value of the surrogate pair. - value = 0x10000 + ((value & 0x3FF) << 10) + (value2 & 0x3FF) - } else { - width = 2 - } - - default: - panic("impossible") - } - - // Check if the character is in the allowed range: - // #x9 | #xA | #xD | [#x20-#x7E] (8 bit) - // | #x85 | [#xA0-#xD7FF] | [#xE000-#xFFFD] (16 bit) - // | [#x10000-#x10FFFF] (32 bit) - switch { - case value == 0x09: - case value == 0x0A: - case value == 0x0D: - case value >= 0x20 && value <= 0x7E: - case value == 0x85: - case value >= 0xA0 && value <= 0xD7FF: - case value >= 0xE000 && value <= 0xFFFD: - case value >= 0x10000 && value <= 0x10FFFF: - default: - return yaml_parser_set_reader_error(parser, - "control characters are not allowed", - parser.offset, int(value)) - } - - // Move the raw pointers. - parser.raw_buffer_pos += width - parser.offset += width - - // Finally put the character into the buffer. - if value <= 0x7F { - // 0000 0000-0000 007F . 0xxxxxxx - parser.buffer[buffer_len+0] = byte(value) - buffer_len += 1 - } else if value <= 0x7FF { - // 0000 0080-0000 07FF . 110xxxxx 10xxxxxx - parser.buffer[buffer_len+0] = byte(0xC0 + (value >> 6)) - parser.buffer[buffer_len+1] = byte(0x80 + (value & 0x3F)) - buffer_len += 2 - } else if value <= 0xFFFF { - // 0000 0800-0000 FFFF . 1110xxxx 10xxxxxx 10xxxxxx - parser.buffer[buffer_len+0] = byte(0xE0 + (value >> 12)) - parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 6) & 0x3F)) - parser.buffer[buffer_len+2] = byte(0x80 + (value & 0x3F)) - buffer_len += 3 - } else { - // 0001 0000-0010 FFFF . 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - parser.buffer[buffer_len+0] = byte(0xF0 + (value >> 18)) - parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 12) & 0x3F)) - parser.buffer[buffer_len+2] = byte(0x80 + ((value >> 6) & 0x3F)) - parser.buffer[buffer_len+3] = byte(0x80 + (value & 0x3F)) - buffer_len += 4 - } - - parser.unread++ - } - - // On EOF, put NUL into the buffer and return. - if parser.eof { - parser.buffer[buffer_len] = 0 - buffer_len++ - parser.unread++ - break - } - } - // [Go] Read the documentation of this function above. To return true, - // we need to have the given length in the buffer. Not doing that means - // every single check that calls this function to make sure the buffer - // has a given length is Go) panicking; or C) accessing invalid memory. - // This happens here due to the EOF above breaking early. - for buffer_len < length { - parser.buffer[buffer_len] = 0 - buffer_len++ - } - parser.buffer = parser.buffer[:buffer_len] - return true -} diff --git a/vendor/cuelang.org/go/internal/third_party/yaml/resolve.go b/vendor/cuelang.org/go/internal/third_party/yaml/resolve.go deleted file mode 100644 index f7ca87d7be..0000000000 --- a/vendor/cuelang.org/go/internal/third_party/yaml/resolve.go +++ /dev/null @@ -1,256 +0,0 @@ -package yaml - -import ( - "encoding/base64" - "math" - "regexp" - "strconv" - "strings" - "time" -) - -type resolveMapItem struct { - value interface{} - tag string -} - -var resolveTable = make([]byte, 256) -var resolveMap = make(map[string]resolveMapItem) - -func init() { - t := resolveTable - t[int('+')] = 'S' // Sign - t[int('-')] = 'S' - for _, c := range "0123456789" { - t[int(c)] = 'D' // Digit - } - for _, c := range "nNtTfF~" { - t[int(c)] = 'M' // In map - } - t[int('.')] = '.' // Float (potentially in map) - - var resolveMapList = []struct { - v interface{} - tag string - l []string - }{ - {true, yaml_BOOL_TAG, []string{"true", "True", "TRUE"}}, - {false, yaml_BOOL_TAG, []string{"false", "False", "FALSE"}}, - {nil, yaml_NULL_TAG, []string{"", "~", "null", "Null", "NULL"}}, - {math.NaN(), yaml_FLOAT_TAG, []string{".nan", ".NaN", ".NAN"}}, - {math.Inf(+1), yaml_FLOAT_TAG, []string{".inf", ".Inf", ".INF"}}, - {math.Inf(+1), yaml_FLOAT_TAG, []string{"+.inf", "+.Inf", "+.INF"}}, - {math.Inf(-1), yaml_FLOAT_TAG, []string{"-.inf", "-.Inf", "-.INF"}}, - {"<<", yaml_MERGE_TAG, []string{"<<"}}, - } - - m := resolveMap - for _, item := range resolveMapList { - for _, s := range item.l { - m[s] = resolveMapItem{item.v, item.tag} - } - } -} - -const longTagPrefix = "tag:yaml.org,2002:" - -func shortTag(tag string) string { - // TODO This can easily be made faster and produce less garbage. - if strings.HasPrefix(tag, longTagPrefix) { - return "!!" + tag[len(longTagPrefix):] - } - return tag -} - -func longTag(tag string) string { - if strings.HasPrefix(tag, "!!") { - return longTagPrefix + tag[2:] - } - return tag -} - -func resolvableTag(tag string) bool { - switch tag { - case "", yaml_STR_TAG, yaml_BOOL_TAG, yaml_INT_TAG, yaml_FLOAT_TAG, yaml_NULL_TAG, yaml_TIMESTAMP_TAG: - return true - } - return false -} - -var yamlStyleFloat = regexp.MustCompile(`^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$`) - -func (d *decoder) resolve(n *node) (rtag string, out interface{}) { - tag := n.tag - in := n.value - if !resolvableTag(tag) { - return tag, in - } - - defer func() { - switch tag { - case "", rtag, yaml_STR_TAG, yaml_BINARY_TAG: - return - case yaml_FLOAT_TAG: - if rtag == yaml_INT_TAG { - switch v := out.(type) { - case int64: - rtag = yaml_FLOAT_TAG - out = float64(v) - return - case int: - rtag = yaml_FLOAT_TAG - out = float64(v) - return - } - } - } - d.p.failf(n.startPos.line, "cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag)) - }() - - // Any data is accepted as a !!str or !!binary. - // Otherwise, the prefix is enough of a hint about what it might be. - hint := byte('N') - if in != "" { - hint = resolveTable[in[0]] - } - if hint != 0 && tag != yaml_STR_TAG && tag != yaml_BINARY_TAG { - // Handle things we can lookup in a map. - if item, ok := resolveMap[in]; ok { - return item.tag, item.value - } - - // Base 60 floats are a bad idea, were dropped in YAML 1.2, and - // are purposefully unsupported here. They're still quoted on - // the way out for compatibility with other parser, though. - - switch hint { - case 'M': - // We've already checked the map above. - - case '.': - // Not in the map, so maybe a normal float. - floatv, err := strconv.ParseFloat(in, 64) - if err == nil { - return yaml_FLOAT_TAG, floatv - } - - case 'D', 'S': - // Int, float, or timestamp. - // Only try values as a timestamp if the value is unquoted or there's an explicit - // !!timestamp tag. - if tag == "" || tag == yaml_TIMESTAMP_TAG { - t, ok := parseTimestamp(in) - if ok { - return yaml_TIMESTAMP_TAG, t - } - } - - plain := strings.Replace(in, "_", "", -1) - intv, err := strconv.ParseInt(plain, 0, 64) - if err == nil { - if intv == int64(int(intv)) { - return yaml_INT_TAG, int(intv) - } else { - return yaml_INT_TAG, intv - } - } - uintv, err := strconv.ParseUint(plain, 0, 64) - if err == nil { - return yaml_INT_TAG, uintv - } - if yamlStyleFloat.MatchString(plain) { - floatv, err := strconv.ParseFloat(plain, 64) - if err == nil { - return yaml_FLOAT_TAG, floatv - } - } - if strings.HasPrefix(plain, "0b") { - intv, err := strconv.ParseInt(plain[2:], 2, 64) - if err == nil { - if intv == int64(int(intv)) { - return yaml_INT_TAG, int(intv) - } else { - return yaml_INT_TAG, intv - } - } - uintv, err := strconv.ParseUint(plain[2:], 2, 64) - if err == nil { - return yaml_INT_TAG, uintv - } - } else if strings.HasPrefix(plain, "-0b") { - intv, err := strconv.ParseInt("-"+plain[3:], 2, 64) - if err == nil { - if true || intv == int64(int(intv)) { - return yaml_INT_TAG, int(intv) - } else { - return yaml_INT_TAG, intv - } - } - } - default: - panic("resolveTable item not yet handled: " + string(rune(hint)) + " (with " + in + ")") - } - } - return yaml_STR_TAG, in -} - -// encodeBase64 encodes s as base64 that is broken up into multiple lines -// as appropriate for the resulting length. -func encodeBase64(s string) string { - const lineLen = 70 - encLen := base64.StdEncoding.EncodedLen(len(s)) - lines := encLen/lineLen + 1 - buf := make([]byte, encLen*2+lines) - in := buf[0:encLen] - out := buf[encLen:] - base64.StdEncoding.Encode(in, []byte(s)) - k := 0 - for i := 0; i < len(in); i += lineLen { - j := i + lineLen - if j > len(in) { - j = len(in) - } - k += copy(out[k:], in[i:j]) - if lines > 1 { - out[k] = '\n' - k++ - } - } - return string(out[:k]) -} - -// This is a subset of the formats allowed by the regular expression -// defined at http://yaml.org/type/timestamp.html. -var allowedTimestampFormats = []string{ - "2006-1-2T15:4:5.999999999Z07:00", // RCF3339Nano with short date fields. - "2006-1-2t15:4:5.999999999Z07:00", // RFC3339Nano with short date fields and lower-case "t". - "2006-1-2 15:4:5.999999999", // space separated with no time zone - "2006-1-2", // date only - // Notable exception: time.Parse cannot handle: "2001-12-14 21:59:43.10 -5" - // from the set of examples. -} - -// parseTimestamp parses s as a timestamp string and -// returns the timestamp and reports whether it succeeded. -// Timestamp formats are defined at http://yaml.org/type/timestamp.html -func parseTimestamp(s string) (time.Time, bool) { - // TODO write code to check all the formats supported by - // http://yaml.org/type/timestamp.html instead of using time.Parse. - - // Quick check: all date formats start with YYYY-. - i := 0 - for ; i < len(s); i++ { - if c := s[i]; c < '0' || c > '9' { - break - } - } - if i != 4 || i == len(s) || s[i] != '-' { - return time.Time{}, false - } - for _, format := range allowedTimestampFormats { - if t, err := time.Parse(format, s); err == nil { - return t, true - } - } - return time.Time{}, false -} diff --git a/vendor/cuelang.org/go/internal/third_party/yaml/scannerc.go b/vendor/cuelang.org/go/internal/third_party/yaml/scannerc.go deleted file mode 100644 index fb0d95d7f2..0000000000 --- a/vendor/cuelang.org/go/internal/third_party/yaml/scannerc.go +++ /dev/null @@ -1,2723 +0,0 @@ -package yaml - -import ( - "bytes" - "fmt" -) - -// Introduction -// ************ -// -// The following notes assume that you are familiar with the YAML specification -// (http://yaml.org/spec/1.2/spec.html). We mostly follow it, although in -// some cases we are less restrictive that it requires. -// -// The process of transforming a YAML stream into a sequence of events is -// divided on two steps: Scanning and Parsing. -// -// The Scanner transforms the input stream into a sequence of tokens, while the -// parser transform the sequence of tokens produced by the Scanner into a -// sequence of parsing events. -// -// The Scanner is rather clever and complicated. The Parser, on the contrary, -// is a straightforward implementation of a recursive-descendant parser (or, -// LL(1) parser, as it is usually called). -// -// Actually there are two issues of Scanning that might be called "clever", the -// rest is quite straightforward. The issues are "block collection start" and -// "simple keys". Both issues are explained below in details. -// -// Here the Scanning step is explained and implemented. We start with the list -// of all the tokens produced by the Scanner together with short descriptions. -// -// Now, tokens: -// -// STREAM-START(encoding) # The stream start. -// STREAM-END # The stream end. -// VERSION-DIRECTIVE(major,minor) # The '%YAML' directive. -// TAG-DIRECTIVE(handle,prefix) # The '%TAG' directive. -// DOCUMENT-START # '---' -// DOCUMENT-END # '...' -// BLOCK-SEQUENCE-START # Indentation increase denoting a block -// BLOCK-MAPPING-START # sequence or a block mapping. -// BLOCK-END # Indentation decrease. -// FLOW-SEQUENCE-START # '[' -// FLOW-SEQUENCE-END # ']' -// BLOCK-SEQUENCE-START # '{' -// BLOCK-SEQUENCE-END # '}' -// BLOCK-ENTRY # '-' -// FLOW-ENTRY # ',' -// KEY # '?' or nothing (simple keys). -// VALUE # ':' -// ALIAS(anchor) # '*anchor' -// ANCHOR(anchor) # '&anchor' -// TAG(handle,suffix) # '!handle!suffix' -// SCALAR(value,style) # A scalar. -// -// The following two tokens are "virtual" tokens denoting the beginning and the -// end of the stream: -// -// STREAM-START(encoding) -// STREAM-END -// -// We pass the information about the input stream encoding with the -// STREAM-START token. -// -// The next two tokens are responsible for tags: -// -// VERSION-DIRECTIVE(major,minor) -// TAG-DIRECTIVE(handle,prefix) -// -// Example: -// -// %YAML 1.1 -// %TAG ! !foo -// %TAG !yaml! tag:yaml.org,2002: -// --- -// -// The correspoding sequence of tokens: -// -// STREAM-START(utf-8) -// VERSION-DIRECTIVE(1,1) -// TAG-DIRECTIVE("!","!foo") -// TAG-DIRECTIVE("!yaml","tag:yaml.org,2002:") -// DOCUMENT-START -// STREAM-END -// -// Note that the VERSION-DIRECTIVE and TAG-DIRECTIVE tokens occupy a whole -// line. -// -// The document start and end indicators are represented by: -// -// DOCUMENT-START -// DOCUMENT-END -// -// Note that if a YAML stream contains an implicit document (without '---' -// and '...' indicators), no DOCUMENT-START and DOCUMENT-END tokens will be -// produced. -// -// In the following examples, we present whole documents together with the -// produced tokens. -// -// 1. An implicit document: -// -// 'a scalar' -// -// Tokens: -// -// STREAM-START(utf-8) -// SCALAR("a scalar",single-quoted) -// STREAM-END -// -// 2. An explicit document: -// -// --- -// 'a scalar' -// ... -// -// Tokens: -// -// STREAM-START(utf-8) -// DOCUMENT-START -// SCALAR("a scalar",single-quoted) -// DOCUMENT-END -// STREAM-END -// -// 3. Several documents in a stream: -// -// 'a scalar' -// --- -// 'another scalar' -// --- -// 'yet another scalar' -// -// Tokens: -// -// STREAM-START(utf-8) -// SCALAR("a scalar",single-quoted) -// DOCUMENT-START -// SCALAR("another scalar",single-quoted) -// DOCUMENT-START -// SCALAR("yet another scalar",single-quoted) -// STREAM-END -// -// We have already introduced the SCALAR token above. The following tokens are -// used to describe aliases, anchors, tag, and scalars: -// -// ALIAS(anchor) -// ANCHOR(anchor) -// TAG(handle,suffix) -// SCALAR(value,style) -// -// The following series of examples illustrate the usage of these tokens: -// -// 1. A recursive sequence: -// -// &A [ *A ] -// -// Tokens: -// -// STREAM-START(utf-8) -// ANCHOR("A") -// FLOW-SEQUENCE-START -// ALIAS("A") -// FLOW-SEQUENCE-END -// STREAM-END -// -// 2. A tagged scalar: -// -// !!float "3.14" # A good approximation. -// -// Tokens: -// -// STREAM-START(utf-8) -// TAG("!!","float") -// SCALAR("3.14",double-quoted) -// STREAM-END -// -// 3. Various scalar styles: -// -// --- # Implicit empty plain scalars do not produce tokens. -// --- a plain scalar -// --- 'a single-quoted scalar' -// --- "a double-quoted scalar" -// --- |- -// a literal scalar -// --- >- -// a folded -// scalar -// -// Tokens: -// -// STREAM-START(utf-8) -// DOCUMENT-START -// DOCUMENT-START -// SCALAR("a plain scalar",plain) -// DOCUMENT-START -// SCALAR("a single-quoted scalar",single-quoted) -// DOCUMENT-START -// SCALAR("a double-quoted scalar",double-quoted) -// DOCUMENT-START -// SCALAR("a literal scalar",literal) -// DOCUMENT-START -// SCALAR("a folded scalar",folded) -// STREAM-END -// -// Now it's time to review collection-related tokens. We will start with -// flow collections: -// -// FLOW-SEQUENCE-START -// FLOW-SEQUENCE-END -// FLOW-MAPPING-START -// FLOW-MAPPING-END -// FLOW-ENTRY -// KEY -// VALUE -// -// The tokens FLOW-SEQUENCE-START, FLOW-SEQUENCE-END, FLOW-MAPPING-START, and -// FLOW-MAPPING-END represent the indicators '[', ']', '{', and '}' -// correspondingly. FLOW-ENTRY represent the ',' indicator. Finally the -// indicators '?' and ':', which are used for denoting mapping keys and values, -// are represented by the KEY and VALUE tokens. -// -// The following examples show flow collections: -// -// 1. A flow sequence: -// -// [item 1, item 2, item 3] -// -// Tokens: -// -// STREAM-START(utf-8) -// FLOW-SEQUENCE-START -// SCALAR("item 1",plain) -// FLOW-ENTRY -// SCALAR("item 2",plain) -// FLOW-ENTRY -// SCALAR("item 3",plain) -// FLOW-SEQUENCE-END -// STREAM-END -// -// 2. A flow mapping: -// -// { -// a simple key: a value, # Note that the KEY token is produced. -// ? a complex key: another value, -// } -// -// Tokens: -// -// STREAM-START(utf-8) -// FLOW-MAPPING-START -// KEY -// SCALAR("a simple key",plain) -// VALUE -// SCALAR("a value",plain) -// FLOW-ENTRY -// KEY -// SCALAR("a complex key",plain) -// VALUE -// SCALAR("another value",plain) -// FLOW-ENTRY -// FLOW-MAPPING-END -// STREAM-END -// -// A simple key is a key which is not denoted by the '?' indicator. Note that -// the Scanner still produce the KEY token whenever it encounters a simple key. -// -// For scanning block collections, the following tokens are used (note that we -// repeat KEY and VALUE here): -// -// BLOCK-SEQUENCE-START -// BLOCK-MAPPING-START -// BLOCK-END -// BLOCK-ENTRY -// KEY -// VALUE -// -// The tokens BLOCK-SEQUENCE-START and BLOCK-MAPPING-START denote indentation -// increase that precedes a block collection (cf. the INDENT token in Python). -// The token BLOCK-END denote indentation decrease that ends a block collection -// (cf. the DEDENT token in Python). However YAML has some syntax pecularities -// that makes detections of these tokens more complex. -// -// The tokens BLOCK-ENTRY, KEY, and VALUE are used to represent the indicators -// '-', '?', and ':' correspondingly. -// -// The following examples show how the tokens BLOCK-SEQUENCE-START, -// BLOCK-MAPPING-START, and BLOCK-END are emitted by the Scanner: -// -// 1. Block sequences: -// -// - item 1 -// - item 2 -// - -// - item 3.1 -// - item 3.2 -// - -// key 1: value 1 -// key 2: value 2 -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-ENTRY -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 3.1",plain) -// BLOCK-ENTRY -// SCALAR("item 3.2",plain) -// BLOCK-END -// BLOCK-ENTRY -// BLOCK-MAPPING-START -// KEY -// SCALAR("key 1",plain) -// VALUE -// SCALAR("value 1",plain) -// KEY -// SCALAR("key 2",plain) -// VALUE -// SCALAR("value 2",plain) -// BLOCK-END -// BLOCK-END -// STREAM-END -// -// 2. Block mappings: -// -// a simple key: a value # The KEY token is produced here. -// ? a complex key -// : another value -// a mapping: -// key 1: value 1 -// key 2: value 2 -// a sequence: -// - item 1 -// - item 2 -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-MAPPING-START -// KEY -// SCALAR("a simple key",plain) -// VALUE -// SCALAR("a value",plain) -// KEY -// SCALAR("a complex key",plain) -// VALUE -// SCALAR("another value",plain) -// KEY -// SCALAR("a mapping",plain) -// BLOCK-MAPPING-START -// KEY -// SCALAR("key 1",plain) -// VALUE -// SCALAR("value 1",plain) -// KEY -// SCALAR("key 2",plain) -// VALUE -// SCALAR("value 2",plain) -// BLOCK-END -// KEY -// SCALAR("a sequence",plain) -// VALUE -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-END -// BLOCK-END -// STREAM-END -// -// YAML does not always require to start a new block collection from a new -// line. If the current line contains only '-', '?', and ':' indicators, a new -// block collection may start at the current line. The following examples -// illustrate this case: -// -// 1. Collections in a sequence: -// -// - - item 1 -// - item 2 -// - key 1: value 1 -// key 2: value 2 -// - ? complex key -// : complex value -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-END -// BLOCK-ENTRY -// BLOCK-MAPPING-START -// KEY -// SCALAR("key 1",plain) -// VALUE -// SCALAR("value 1",plain) -// KEY -// SCALAR("key 2",plain) -// VALUE -// SCALAR("value 2",plain) -// BLOCK-END -// BLOCK-ENTRY -// BLOCK-MAPPING-START -// KEY -// SCALAR("complex key") -// VALUE -// SCALAR("complex value") -// BLOCK-END -// BLOCK-END -// STREAM-END -// -// 2. Collections in a mapping: -// -// ? a sequence -// : - item 1 -// - item 2 -// ? a mapping -// : key 1: value 1 -// key 2: value 2 -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-MAPPING-START -// KEY -// SCALAR("a sequence",plain) -// VALUE -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-END -// KEY -// SCALAR("a mapping",plain) -// VALUE -// BLOCK-MAPPING-START -// KEY -// SCALAR("key 1",plain) -// VALUE -// SCALAR("value 1",plain) -// KEY -// SCALAR("key 2",plain) -// VALUE -// SCALAR("value 2",plain) -// BLOCK-END -// BLOCK-END -// STREAM-END -// -// YAML also permits non-indented sequences if they are included into a block -// mapping. In this case, the token BLOCK-SEQUENCE-START is not produced: -// -// key: -// - item 1 # BLOCK-SEQUENCE-START is NOT produced here. -// - item 2 -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-MAPPING-START -// KEY -// SCALAR("key",plain) -// VALUE -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-END -// - -// Ensure that the buffer contains the required number of characters. -// Return true on success, false on failure (reader error or memory error). -func cache(parser *yaml_parser_t, length int) bool { - // [Go] This was inlined: !cache(A, B) -> unread < B && !update(A, B) - return parser.unread >= length || yaml_parser_update_buffer(parser, length) -} - -// Advance the buffer pointer. -func skip(parser *yaml_parser_t) { - w := width(parser.buffer[parser.buffer_pos]) - parser.mark.index += w - parser.mark.column++ - parser.unread-- - parser.buffer_pos += w -} - -func skip_line(parser *yaml_parser_t) { - if is_crlf(parser.buffer, parser.buffer_pos) { - parser.mark.index += 2 - parser.mark.column = 0 - parser.mark.line++ - parser.unread -= 2 - parser.buffer_pos += 2 - } else if is_break(parser.buffer, parser.buffer_pos) { - w := width(parser.buffer[parser.buffer_pos]) - parser.mark.index += w - parser.mark.column = 0 - parser.mark.line++ - parser.unread-- - parser.buffer_pos += w - } -} - -// Copy a character to a string buffer and advance pointers. -func read(parser *yaml_parser_t, s []byte) []byte { - w := width(parser.buffer[parser.buffer_pos]) - if w == 0 { - panic("invalid character sequence") - } - if len(s) == 0 { - s = make([]byte, 0, 32) - } - if w == 1 && len(s)+w <= cap(s) { - s = s[:len(s)+1] - s[len(s)-1] = parser.buffer[parser.buffer_pos] - parser.buffer_pos++ - } else { - s = append(s, parser.buffer[parser.buffer_pos:parser.buffer_pos+w]...) - parser.buffer_pos += w - } - parser.mark.index += w - parser.mark.column++ - parser.unread-- - return s -} - -// Copy a line break character to a string buffer and advance pointers. -func read_line(parser *yaml_parser_t, s []byte) []byte { - buf := parser.buffer - pos := parser.buffer_pos - switch { - case buf[pos] == '\r' && buf[pos+1] == '\n': - // CR LF . LF - s = append(s, '\n') - parser.buffer_pos += 2 - parser.mark.index++ - parser.unread-- - case buf[pos] == '\r' || buf[pos] == '\n': - // CR|LF . LF - s = append(s, '\n') - parser.buffer_pos += 1 - case buf[pos] == '\xC2' && buf[pos+1] == '\x85': - // NEL . LF - s = append(s, '\n') - parser.buffer_pos += 2 - case buf[pos] == '\xE2' && buf[pos+1] == '\x80' && (buf[pos+2] == '\xA8' || buf[pos+2] == '\xA9'): - // LS|PS . LS|PS - s = append(s, buf[parser.buffer_pos:pos+3]...) - parser.buffer_pos += 3 - default: - return s - } - parser.mark.index++ - parser.mark.column = 0 - parser.mark.line++ - parser.unread-- - return s -} - -// Get the next token. -func yaml_parser_scan(parser *yaml_parser_t, token *yaml_token_t) bool { - // Erase the token object. - *token = yaml_token_t{} // [Go] Is this necessary? - - // No tokens after STREAM-END or error. - if parser.stream_end_produced || parser.error != yaml_NO_ERROR { - return true - } - - // Ensure that the tokens queue contains enough tokens. - if !parser.token_available { - if !yaml_parser_fetch_more_tokens(parser) { - return false - } - } - - // Fetch the next token from the queue. - *token = parser.tokens[parser.tokens_head] - parser.tokens_head++ - parser.tokens_parsed++ - parser.token_available = false - - if token.typ == yaml_STREAM_END_TOKEN { - parser.stream_end_produced = true - } - return true -} - -// Set the scanner error and return false. -func yaml_parser_set_scanner_error(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string) bool { - parser.error = yaml_SCANNER_ERROR - parser.context = context - parser.context_mark = context_mark - parser.problem = problem - parser.problem_mark = parser.mark - return false -} - -func yaml_parser_set_scanner_tag_error(parser *yaml_parser_t, directive bool, context_mark yaml_mark_t, problem string) bool { - context := "while parsing a tag" - if directive { - context = "while parsing a %TAG directive" - } - return yaml_parser_set_scanner_error(parser, context, context_mark, problem) -} - -func trace(args ...interface{}) func() { - pargs := append([]interface{}{"+++"}, args...) - fmt.Println(pargs...) - pargs = append([]interface{}{"---"}, args...) - return func() { fmt.Println(pargs...) } -} - -// Ensure that the tokens queue contains at least one token which can be -// returned to the Parser. -func yaml_parser_fetch_more_tokens(parser *yaml_parser_t) bool { - // While we need more tokens to fetch, do it. - for { - // Check if we really need to fetch more tokens. - need_more_tokens := false - - if parser.tokens_head == len(parser.tokens) { - // Queue is empty. - need_more_tokens = true - } else { - // Check if any potential simple key may occupy the head position. - if !yaml_parser_stale_simple_keys(parser) { - return false - } - - for i := range parser.simple_keys { - simple_key := &parser.simple_keys[i] - if simple_key.possible && simple_key.token_number == parser.tokens_parsed { - need_more_tokens = true - break - } - } - } - - // We are finished. - if !need_more_tokens { - break - } - // Fetch the next token. - if !yaml_parser_fetch_next_token(parser) { - return false - } - } - - parser.token_available = true - return true -} - -// The dispatcher for token fetchers. -func yaml_parser_fetch_next_token(parser *yaml_parser_t) bool { - // Ensure that the buffer is initialized. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - // Check if we just started scanning. Fetch STREAM-START then. - if !parser.stream_start_produced { - return yaml_parser_fetch_stream_start(parser) - } - - // Eat whitespaces and comments until we reach the next token. - if !yaml_parser_scan_to_next_token(parser) { - return false - } - - // Remove obsolete potential simple keys. - if !yaml_parser_stale_simple_keys(parser) { - return false - } - - // Check the indentation level against the current column. - if !yaml_parser_unroll_indent(parser, parser.mark.column) { - return false - } - - // Ensure that the buffer contains at least 4 characters. 4 is the length - // of the longest indicators ('--- ' and '... '). - if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { - return false - } - - // Is it the end of the stream? - if is_z(parser.buffer, parser.buffer_pos) { - return yaml_parser_fetch_stream_end(parser) - } - - // Is it a directive? - if parser.mark.column == 0 && parser.buffer[parser.buffer_pos] == '%' { - return yaml_parser_fetch_directive(parser) - } - - buf := parser.buffer - pos := parser.buffer_pos - - // Is it the document start indicator? - if parser.mark.column == 0 && buf[pos] == '-' && buf[pos+1] == '-' && buf[pos+2] == '-' && is_blankz(buf, pos+3) { - return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_START_TOKEN) - } - - // Is it the document end indicator? - if parser.mark.column == 0 && buf[pos] == '.' && buf[pos+1] == '.' && buf[pos+2] == '.' && is_blankz(buf, pos+3) { - return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_END_TOKEN) - } - - // Is it the flow sequence start indicator? - if buf[pos] == '[' { - return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_SEQUENCE_START_TOKEN) - } - - // Is it the flow mapping start indicator? - if parser.buffer[parser.buffer_pos] == '{' { - return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_MAPPING_START_TOKEN) - } - - // Is it the flow sequence end indicator? - if parser.buffer[parser.buffer_pos] == ']' { - return yaml_parser_fetch_flow_collection_end(parser, - yaml_FLOW_SEQUENCE_END_TOKEN) - } - - // Is it the flow mapping end indicator? - if parser.buffer[parser.buffer_pos] == '}' { - return yaml_parser_fetch_flow_collection_end(parser, - yaml_FLOW_MAPPING_END_TOKEN) - } - - // Is it the flow entry indicator? - if parser.buffer[parser.buffer_pos] == ',' { - return yaml_parser_fetch_flow_entry(parser) - } - - // Is it the block entry indicator? - if parser.buffer[parser.buffer_pos] == '-' && is_blankz(parser.buffer, parser.buffer_pos+1) { - return yaml_parser_fetch_block_entry(parser) - } - - // Is it the key indicator? - if parser.buffer[parser.buffer_pos] == '?' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { - return yaml_parser_fetch_key(parser) - } - - // Is it the value indicator? - if parser.buffer[parser.buffer_pos] == ':' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { - return yaml_parser_fetch_value(parser) - } - - // Is it an alias? - if parser.buffer[parser.buffer_pos] == '*' { - return yaml_parser_fetch_anchor(parser, yaml_ALIAS_TOKEN) - } - - // Is it an anchor? - if parser.buffer[parser.buffer_pos] == '&' { - return yaml_parser_fetch_anchor(parser, yaml_ANCHOR_TOKEN) - } - - // Is it a tag? - if parser.buffer[parser.buffer_pos] == '!' { - return yaml_parser_fetch_tag(parser) - } - - // Is it a literal scalar? - if parser.buffer[parser.buffer_pos] == '|' && parser.flow_level == 0 { - return yaml_parser_fetch_block_scalar(parser, true) - } - - // Is it a folded scalar? - if parser.buffer[parser.buffer_pos] == '>' && parser.flow_level == 0 { - return yaml_parser_fetch_block_scalar(parser, false) - } - - // Is it a single-quoted scalar? - if parser.buffer[parser.buffer_pos] == '\'' { - return yaml_parser_fetch_flow_scalar(parser, true) - } - - // Is it a double-quoted scalar? - if parser.buffer[parser.buffer_pos] == '"' { - return yaml_parser_fetch_flow_scalar(parser, false) - } - - // Is it a plain scalar? - // - // A plain scalar may start with any non-blank characters except - // - // '-', '?', ':', ',', '[', ']', '{', '}', - // '#', '&', '*', '!', '|', '>', '\'', '\"', - // '%', '@', '`'. - // - // In the block context (and, for the '-' indicator, in the flow context - // too), it may also start with the characters - // - // '-', '?', ':' - // - // if it is followed by a non-space character. - // - // The last rule is more restrictive than the specification requires. - // [Go] Make this logic more reasonable. - //switch parser.buffer[parser.buffer_pos] { - //case '-', '?', ':', ',', '?', '-', ',', ':', ']', '[', '}', '{', '&', '#', '!', '*', '>', '|', '"', '\'', '@', '%', '-', '`': - //} - if !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '-' || - parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':' || - parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '[' || - parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || - parser.buffer[parser.buffer_pos] == '}' || parser.buffer[parser.buffer_pos] == '#' || - parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '*' || - parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '|' || - parser.buffer[parser.buffer_pos] == '>' || parser.buffer[parser.buffer_pos] == '\'' || - parser.buffer[parser.buffer_pos] == '"' || parser.buffer[parser.buffer_pos] == '%' || - parser.buffer[parser.buffer_pos] == '@' || parser.buffer[parser.buffer_pos] == '`') || - (parser.buffer[parser.buffer_pos] == '-' && !is_blank(parser.buffer, parser.buffer_pos+1)) || - (parser.flow_level == 0 && - (parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':') && - !is_blankz(parser.buffer, parser.buffer_pos+1)) { - return yaml_parser_fetch_plain_scalar(parser) - } - - // If we don't determine the token type so far, it is an error. - return yaml_parser_set_scanner_error(parser, - "while scanning for the next token", parser.mark, - "found character that cannot start any token") -} - -// Check the list of potential simple keys and remove the positions that -// cannot contain simple keys anymore. -func yaml_parser_stale_simple_keys(parser *yaml_parser_t) bool { - // Check for a potential simple key for each flow level. - for i := range parser.simple_keys { - simple_key := &parser.simple_keys[i] - - // The specification requires that a simple key - // - // - is limited to a single line, - // - is shorter than 1024 characters. - if simple_key.possible && (simple_key.mark.line < parser.mark.line || simple_key.mark.index+1024 < parser.mark.index) { - - // Check if the potential simple key to be removed is required. - if simple_key.required { - return yaml_parser_set_scanner_error(parser, - "while scanning a simple key", simple_key.mark, - "could not find expected ':'") - } - simple_key.possible = false - } - } - return true -} - -// Check if a simple key may start at the current position and add it if -// needed. -func yaml_parser_save_simple_key(parser *yaml_parser_t) bool { - // A simple key is required at the current position if the scanner is in - // the block context and the current column coincides with the indentation - // level. - - required := parser.flow_level == 0 && parser.indent == parser.mark.column - - // - // If the current position may start a simple key, save it. - // - if parser.simple_key_allowed { - simple_key := yaml_simple_key_t{ - possible: true, - required: required, - token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), - } - simple_key.mark = parser.mark - - if !yaml_parser_remove_simple_key(parser) { - return false - } - parser.simple_keys[len(parser.simple_keys)-1] = simple_key - } - return true -} - -// Remove a potential simple key at the current flow level. -func yaml_parser_remove_simple_key(parser *yaml_parser_t) bool { - i := len(parser.simple_keys) - 1 - if parser.simple_keys[i].possible { - // If the key is required, it is an error. - if parser.simple_keys[i].required { - return yaml_parser_set_scanner_error(parser, - "while scanning a simple key", parser.simple_keys[i].mark, - "could not find expected ':'") - } - } - // Remove the key from the stack. - parser.simple_keys[i].possible = false - return true -} - -// Increase the flow level and resize the simple key list if needed. -func yaml_parser_increase_flow_level(parser *yaml_parser_t) bool { - // Reset the simple key on the next level. - parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) - - // Increase the flow level. - parser.flow_level++ - return true -} - -// Decrease the flow level. -func yaml_parser_decrease_flow_level(parser *yaml_parser_t) bool { - if parser.flow_level > 0 { - parser.flow_level-- - parser.simple_keys = parser.simple_keys[:len(parser.simple_keys)-1] - } - return true -} - -// Push the current indentation level to the stack and set the new level -// the current column is greater than the indentation level. In this case, -// append or insert the specified token into the token queue. -func yaml_parser_roll_indent(parser *yaml_parser_t, column, number int, typ yaml_token_type_t, mark yaml_mark_t) bool { - // In the flow context, do nothing. - if parser.flow_level > 0 { - return true - } - - if parser.indent < column { - // Push the current indentation level to the stack and set the new - // indentation level. - parser.indents = append(parser.indents, parser.indent) - parser.indent = column - - // Create a token and insert it into the queue. - token := yaml_token_t{ - typ: typ, - start_mark: mark, - end_mark: mark, - } - if number > -1 { - number -= parser.tokens_parsed - } - yaml_insert_token(parser, number, &token) - } - return true -} - -// Pop indentation levels from the indents stack until the current level -// becomes less or equal to the column. For each indentation level, append -// the BLOCK-END token. -func yaml_parser_unroll_indent(parser *yaml_parser_t, column int) bool { - // In the flow context, do nothing. - if parser.flow_level > 0 { - return true - } - - // Loop through the indentation levels in the stack. - for parser.indent > column { - // Create a token and append it to the queue. - token := yaml_token_t{ - typ: yaml_BLOCK_END_TOKEN, - start_mark: parser.mark, - end_mark: parser.mark, - } - yaml_insert_token(parser, -1, &token) - - // Pop the indentation level. - parser.indent = parser.indents[len(parser.indents)-1] - parser.indents = parser.indents[:len(parser.indents)-1] - } - return true -} - -// Initialize the scanner and produce the STREAM-START token. -func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool { - - // Set the initial indentation. - parser.indent = -1 - - // Initialize the simple key stack. - parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) - - // A simple key is allowed at the beginning of the stream. - parser.simple_key_allowed = true - - // We have started. - parser.stream_start_produced = true - - // Create the STREAM-START token and append it to the queue. - token := yaml_token_t{ - typ: yaml_STREAM_START_TOKEN, - start_mark: parser.mark, - end_mark: parser.mark, - encoding: parser.encoding, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the STREAM-END token and shut down the scanner. -func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool { - - // Force new line. - if parser.mark.column != 0 { - parser.mark.column = 0 - parser.mark.line++ - } - - // Reset the indentation level. - if !yaml_parser_unroll_indent(parser, -1) { - return false - } - - // Reset simple keys. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - parser.simple_key_allowed = false - - // Create the STREAM-END token and append it to the queue. - token := yaml_token_t{ - typ: yaml_STREAM_END_TOKEN, - start_mark: parser.mark, - end_mark: parser.mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce a VERSION-DIRECTIVE or TAG-DIRECTIVE token. -func yaml_parser_fetch_directive(parser *yaml_parser_t) bool { - // Reset the indentation level. - if !yaml_parser_unroll_indent(parser, -1) { - return false - } - - // Reset simple keys. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - parser.simple_key_allowed = false - - // Create the YAML-DIRECTIVE or TAG-DIRECTIVE token. - token := yaml_token_t{} - if !yaml_parser_scan_directive(parser, &token) { - return false - } - // Append the token to the queue. - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the DOCUMENT-START or DOCUMENT-END token. -func yaml_parser_fetch_document_indicator(parser *yaml_parser_t, typ yaml_token_type_t) bool { - // Reset the indentation level. - if !yaml_parser_unroll_indent(parser, -1) { - return false - } - - // Reset simple keys. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - parser.simple_key_allowed = false - - // Consume the token. - start_mark := parser.mark - - skip(parser) - skip(parser) - skip(parser) - - end_mark := parser.mark - - // Create the DOCUMENT-START or DOCUMENT-END token. - token := yaml_token_t{ - typ: typ, - start_mark: start_mark, - end_mark: end_mark, - } - // Append the token to the queue. - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token. -func yaml_parser_fetch_flow_collection_start(parser *yaml_parser_t, typ yaml_token_type_t) bool { - // The indicators '[' and '{' may start a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // Increase the flow level. - if !yaml_parser_increase_flow_level(parser) { - return false - } - - // A simple key may follow the indicators '[' and '{'. - parser.simple_key_allowed = true - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token. - token := yaml_token_t{ - typ: typ, - start_mark: start_mark, - end_mark: end_mark, - } - // Append the token to the queue. - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the FLOW-SEQUENCE-END or FLOW-MAPPING-END token. -func yaml_parser_fetch_flow_collection_end(parser *yaml_parser_t, typ yaml_token_type_t) bool { - // Reset any potential simple key on the current flow level. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // Decrease the flow level. - if !yaml_parser_decrease_flow_level(parser) { - return false - } - - // No simple keys after the indicators ']' and '}'. - parser.simple_key_allowed = false - - // Consume the token. - - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the FLOW-SEQUENCE-END of FLOW-MAPPING-END token. - token := yaml_token_t{ - typ: typ, - start_mark: start_mark, - end_mark: end_mark, - } - // Append the token to the queue. - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the FLOW-ENTRY token. -func yaml_parser_fetch_flow_entry(parser *yaml_parser_t) bool { - // Reset any potential simple keys on the current flow level. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // Simple keys are allowed after ','. - parser.simple_key_allowed = true - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the FLOW-ENTRY token and append it to the queue. - token := yaml_token_t{ - typ: yaml_FLOW_ENTRY_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the BLOCK-ENTRY token. -func yaml_parser_fetch_block_entry(parser *yaml_parser_t) bool { - // Check if the scanner is in the block context. - if parser.flow_level == 0 { - // Check if we are allowed to start a new entry. - if !parser.simple_key_allowed { - return yaml_parser_set_scanner_error(parser, "", parser.mark, - "block sequence entries are not allowed in this context") - } - // Add the BLOCK-SEQUENCE-START token if needed. - if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_SEQUENCE_START_TOKEN, parser.mark) { - return false - } - } else { - // It is an error for the '-' indicator to occur in the flow context, - // but we let the Parser detect and report about it because the Parser - // is able to point to the context. - } - - // Reset any potential simple keys on the current flow level. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // Simple keys are allowed after '-'. - parser.simple_key_allowed = true - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the BLOCK-ENTRY token and append it to the queue. - token := yaml_token_t{ - typ: yaml_BLOCK_ENTRY_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the KEY token. -func yaml_parser_fetch_key(parser *yaml_parser_t) bool { - - // In the block context, additional checks are required. - if parser.flow_level == 0 { - // Check if we are allowed to start a new key (not nessesary simple). - if !parser.simple_key_allowed { - return yaml_parser_set_scanner_error(parser, "", parser.mark, - "mapping keys are not allowed in this context") - } - // Add the BLOCK-MAPPING-START token if needed. - if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { - return false - } - } - - // Reset any potential simple keys on the current flow level. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // Simple keys are allowed after '?' in the block context. - parser.simple_key_allowed = parser.flow_level == 0 - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the KEY token and append it to the queue. - token := yaml_token_t{ - typ: yaml_KEY_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the VALUE token. -func yaml_parser_fetch_value(parser *yaml_parser_t) bool { - - simple_key := &parser.simple_keys[len(parser.simple_keys)-1] - - // Have we found a simple key? - if simple_key.possible { - // Create the KEY token and insert it into the queue. - token := yaml_token_t{ - typ: yaml_KEY_TOKEN, - start_mark: simple_key.mark, - end_mark: simple_key.mark, - } - yaml_insert_token(parser, simple_key.token_number-parser.tokens_parsed, &token) - - // In the block context, we may need to add the BLOCK-MAPPING-START token. - if !yaml_parser_roll_indent(parser, simple_key.mark.column, - simple_key.token_number, - yaml_BLOCK_MAPPING_START_TOKEN, simple_key.mark) { - return false - } - - // Remove the simple key. - simple_key.possible = false - - // A simple key cannot follow another simple key. - parser.simple_key_allowed = false - - } else { - // The ':' indicator follows a complex key. - - // In the block context, extra checks are required. - if parser.flow_level == 0 { - - // Check if we are allowed to start a complex value. - if !parser.simple_key_allowed { - return yaml_parser_set_scanner_error(parser, "", parser.mark, - "mapping values are not allowed in this context") - } - - // Add the BLOCK-MAPPING-START token if needed. - if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { - return false - } - } - - // Simple keys after ':' are allowed in the block context. - parser.simple_key_allowed = parser.flow_level == 0 - } - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the VALUE token and append it to the queue. - token := yaml_token_t{ - typ: yaml_VALUE_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the ALIAS or ANCHOR token. -func yaml_parser_fetch_anchor(parser *yaml_parser_t, typ yaml_token_type_t) bool { - // An anchor or an alias could be a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // A simple key cannot follow an anchor or an alias. - parser.simple_key_allowed = false - - // Create the ALIAS or ANCHOR token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_anchor(parser, &token, typ) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the TAG token. -func yaml_parser_fetch_tag(parser *yaml_parser_t) bool { - // A tag could be a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // A simple key cannot follow a tag. - parser.simple_key_allowed = false - - // Create the TAG token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_tag(parser, &token) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the SCALAR(...,literal) or SCALAR(...,folded) tokens. -func yaml_parser_fetch_block_scalar(parser *yaml_parser_t, literal bool) bool { - // Remove any potential simple keys. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // A simple key may follow a block scalar. - parser.simple_key_allowed = true - - // Create the SCALAR token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_block_scalar(parser, &token, literal) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the SCALAR(...,single-quoted) or SCALAR(...,double-quoted) tokens. -func yaml_parser_fetch_flow_scalar(parser *yaml_parser_t, single bool) bool { - // A plain scalar could be a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // A simple key cannot follow a flow scalar. - parser.simple_key_allowed = false - - // Create the SCALAR token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_flow_scalar(parser, &token, single) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the SCALAR(...,plain) token. -func yaml_parser_fetch_plain_scalar(parser *yaml_parser_t) bool { - // A plain scalar could be a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // A simple key cannot follow a flow scalar. - parser.simple_key_allowed = false - - // Create the SCALAR token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_plain_scalar(parser, &token) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Eat whitespaces and comments until the next token is found. -func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool { - - parser.linesSinceLast = 0 - parser.spacesSinceLast = 0 - - // Until the next token is not found. - for { - // Allow the BOM mark to start a line. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if parser.mark.column == 0 && is_bom(parser.buffer, parser.buffer_pos) { - skip(parser) - } - - // Eat whitespaces. - // Tabs are allowed: - // - in the flow context - // - in the block context, but not at the beginning of the line or - // after '-', '?', or ':' (complex value). - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for parser.buffer[parser.buffer_pos] == ' ' || ((parser.flow_level > 0 || !parser.simple_key_allowed) && parser.buffer[parser.buffer_pos] == '\t') { - skip(parser) - parser.spacesSinceLast++ - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Eat a comment until a line break. - if parser.buffer[parser.buffer_pos] == '#' { - m := parser.mark - parser.comment_buffer = parser.comment_buffer[:0] - for !is_breakz(parser.buffer, parser.buffer_pos) { - p := parser.buffer_pos - skip(parser) - parser.comment_buffer = append(parser.comment_buffer, - parser.buffer[p:parser.buffer_pos]...) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - add_comment(parser, m, string(parser.comment_buffer)) - } - - // If it is a line break, eat it. - if is_break(parser.buffer, parser.buffer_pos) { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - skip_line(parser) - parser.linesSinceLast++ - - // In the block context, a new line may start a simple key. - if parser.flow_level == 0 { - parser.simple_key_allowed = true - } - } else { - break // We have found a token. - } - } - - return true -} - -// Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token. -// -// Scope: -// -// %YAML 1.1 # a comment \n -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -// %TAG !yaml! tag:yaml.org,2002: \n -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool { - // Eat '%'. - start_mark := parser.mark - skip(parser) - - // Scan the directive name. - var name []byte - if !yaml_parser_scan_directive_name(parser, start_mark, &name) { - return false - } - - // Is it a YAML directive? - if bytes.Equal(name, []byte("YAML")) { - // Scan the VERSION directive value. - var major, minor int8 - if !yaml_parser_scan_version_directive_value(parser, start_mark, &major, &minor) { - return false - } - end_mark := parser.mark - - // Create a VERSION-DIRECTIVE token. - *token = yaml_token_t{ - typ: yaml_VERSION_DIRECTIVE_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - major: major, - minor: minor, - } - - // Is it a TAG directive? - } else if bytes.Equal(name, []byte("TAG")) { - // Scan the TAG directive value. - var handle, prefix []byte - if !yaml_parser_scan_tag_directive_value(parser, start_mark, &handle, &prefix) { - return false - } - end_mark := parser.mark - - // Create a TAG-DIRECTIVE token. - *token = yaml_token_t{ - typ: yaml_TAG_DIRECTIVE_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: handle, - prefix: prefix, - } - - // Unknown directive. - } else { - yaml_parser_set_scanner_error(parser, "while scanning a directive", - start_mark, "found unknown directive name") - return false - } - - // Eat the rest of the line including any comments. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - if parser.buffer[parser.buffer_pos] == '#' { - m := parser.mark - parser.comment_buffer = parser.comment_buffer[:0] - for !is_breakz(parser.buffer, parser.buffer_pos) { - p := parser.buffer_pos - skip(parser) - parser.comment_buffer = append(parser.comment_buffer, - parser.buffer[p:parser.buffer_pos]...) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - add_comment(parser, m, string(parser.comment_buffer)) - } - - // Check if we are at the end of the line. - if !is_breakz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a directive", - start_mark, "did not find expected comment or line break") - return false - } - - // Eat a line break. - if is_break(parser.buffer, parser.buffer_pos) { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - skip_line(parser) - } - - return true -} - -// Scan the directive name. -// -// Scope: -// -// %YAML 1.1 # a comment \n -// ^^^^ -// %TAG !yaml! tag:yaml.org,2002: \n -// ^^^ -func yaml_parser_scan_directive_name(parser *yaml_parser_t, start_mark yaml_mark_t, name *[]byte) bool { - // Consume the directive name. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - var s []byte - for is_alpha(parser.buffer, parser.buffer_pos) { - s = read(parser, s) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check if the name is empty. - if len(s) == 0 { - yaml_parser_set_scanner_error(parser, "while scanning a directive", - start_mark, "could not find expected directive name") - return false - } - - // Check for an blank character after the name. - if !is_blankz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a directive", - start_mark, "found unexpected non-alphabetical character") - return false - } - *name = s - return true -} - -// Scan the value of VERSION-DIRECTIVE. -// -// Scope: -// -// %YAML 1.1 # a comment \n -// ^^^^^^ -func yaml_parser_scan_version_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, major, minor *int8) bool { - // Eat whitespaces. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Consume the major version number. - if !yaml_parser_scan_version_directive_number(parser, start_mark, major) { - return false - } - - // Eat '.'. - if parser.buffer[parser.buffer_pos] != '.' { - return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", - start_mark, "did not find expected digit or '.' character") - } - - skip(parser) - - // Consume the minor version number. - if !yaml_parser_scan_version_directive_number(parser, start_mark, minor) { - return false - } - return true -} - -const max_number_length = 2 - -// Scan the version number of VERSION-DIRECTIVE. -// -// Scope: -// -// %YAML 1.1 # a comment \n -// ^ -// %YAML 1.1 # a comment \n -// ^ -func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark yaml_mark_t, number *int8) bool { - - // Repeat while the next character is digit. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - var value, length int8 - for is_digit(parser.buffer, parser.buffer_pos) { - // Check if the number is too long. - length++ - if length > max_number_length { - return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", - start_mark, "found extremely long version number") - } - value = value*10 + int8(as_digit(parser.buffer, parser.buffer_pos)) - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check if the number was present. - if length == 0 { - return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", - start_mark, "did not find expected version number") - } - *number = value - return true -} - -// Scan the value of a TAG-DIRECTIVE token. -// -// Scope: -// -// %TAG !yaml! tag:yaml.org,2002: \n -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -func yaml_parser_scan_tag_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, handle, prefix *[]byte) bool { - var handle_value, prefix_value []byte - - // Eat whitespaces. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Scan a handle. - if !yaml_parser_scan_tag_handle(parser, true, start_mark, &handle_value) { - return false - } - - // Expect a whitespace. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if !is_blank(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", - start_mark, "did not find expected whitespace") - return false - } - - // Eat whitespaces. - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Scan a prefix. - if !yaml_parser_scan_tag_uri(parser, true, nil, start_mark, &prefix_value) { - return false - } - - // Expect a whitespace or line break. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if !is_blankz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", - start_mark, "did not find expected whitespace or line break") - return false - } - - *handle = handle_value - *prefix = prefix_value - return true -} - -func yaml_parser_scan_anchor(parser *yaml_parser_t, token *yaml_token_t, typ yaml_token_type_t) bool { - var s []byte - - // Eat the indicator character. - start_mark := parser.mark - skip(parser) - - // Consume the value. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for is_alpha(parser.buffer, parser.buffer_pos) { - s = read(parser, s) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - end_mark := parser.mark - - /* - * Check if length of the anchor is greater than 0 and it is followed by - * a whitespace character or one of the indicators: - * - * '?', ':', ',', ']', '}', '%', '@', '`'. - */ - - if len(s) == 0 || - !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '?' || - parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == ',' || - parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '}' || - parser.buffer[parser.buffer_pos] == '%' || parser.buffer[parser.buffer_pos] == '@' || - parser.buffer[parser.buffer_pos] == '`') { - context := "while scanning an alias" - if typ == yaml_ANCHOR_TOKEN { - context = "while scanning an anchor" - } - yaml_parser_set_scanner_error(parser, context, start_mark, - "did not find expected alphabetic or numeric character") - return false - } - - // Create a token. - *token = yaml_token_t{ - typ: typ, - start_mark: start_mark, - end_mark: end_mark, - value: s, - } - - return true -} - -/* - * Scan a TAG token. - */ - -func yaml_parser_scan_tag(parser *yaml_parser_t, token *yaml_token_t) bool { - var handle, suffix []byte - - start_mark := parser.mark - - // Check if the tag is in the canonical form. - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - - if parser.buffer[parser.buffer_pos+1] == '<' { - // Keep the handle as '' - - // Eat '!<' - skip(parser) - skip(parser) - - // Consume the tag value. - if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { - return false - } - - // Check for '>' and eat it. - if parser.buffer[parser.buffer_pos] != '>' { - yaml_parser_set_scanner_error(parser, "while scanning a tag", - start_mark, "did not find the expected '>'") - return false - } - - skip(parser) - } else { - // The tag has either the '!suffix' or the '!handle!suffix' form. - - // First, try to scan a handle. - if !yaml_parser_scan_tag_handle(parser, false, start_mark, &handle) { - return false - } - - // Check if it is, indeed, handle. - if handle[0] == '!' && len(handle) > 1 && handle[len(handle)-1] == '!' { - // Scan the suffix now. - if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { - return false - } - } else { - // It wasn't a handle after all. Scan the rest of the tag. - if !yaml_parser_scan_tag_uri(parser, false, handle, start_mark, &suffix) { - return false - } - - // Set the handle to '!'. - handle = []byte{'!'} - - // A special case: the '!' tag. Set the handle to '' and the - // suffix to '!'. - if len(suffix) == 0 { - handle, suffix = suffix, handle - } - } - } - - // Check the character which ends the tag. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if !is_blankz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a tag", - start_mark, "did not find expected whitespace or line break") - return false - } - - end_mark := parser.mark - - // Create a token. - *token = yaml_token_t{ - typ: yaml_TAG_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: handle, - suffix: suffix, - } - return true -} - -// Scan a tag handle. -func yaml_parser_scan_tag_handle(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, handle *[]byte) bool { - // Check the initial '!' character. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if parser.buffer[parser.buffer_pos] != '!' { - yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "did not find expected '!'") - return false - } - - var s []byte - - // Copy the '!' character. - s = read(parser, s) - - // Copy all subsequent alphabetical and numerical characters. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - for is_alpha(parser.buffer, parser.buffer_pos) { - s = read(parser, s) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check if the trailing character is '!' and copy it. - if parser.buffer[parser.buffer_pos] == '!' { - s = read(parser, s) - } else { - // It's either the '!' tag or not really a tag handle. If it's a %TAG - // directive, it's an error. If it's a tag token, it must be a part of URI. - if directive && string(s) != "!" { - yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "did not find expected '!'") - return false - } - } - - *handle = s - return true -} - -// Scan a tag. -func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte, start_mark yaml_mark_t, uri *[]byte) bool { - //size_t length = head ? strlen((char *)head) : 0 - var s []byte - hasTag := len(head) > 0 - - // Copy the head if needed. - // - // Note that we don't copy the leading '!' character. - if len(head) > 1 { - s = append(s, head[1:]...) - } - - // Scan the tag. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - // The set of characters that may appear in URI is as follows: - // - // '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&', - // '=', '+', '$', ',', '.', '!', '~', '*', '\'', '(', ')', '[', ']', - // '%'. - // [Go] Convert this into more reasonable logic. - for is_alpha(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == ';' || - parser.buffer[parser.buffer_pos] == '/' || parser.buffer[parser.buffer_pos] == '?' || - parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == '@' || - parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '=' || - parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '$' || - parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '.' || - parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '~' || - parser.buffer[parser.buffer_pos] == '*' || parser.buffer[parser.buffer_pos] == '\'' || - parser.buffer[parser.buffer_pos] == '(' || parser.buffer[parser.buffer_pos] == ')' || - parser.buffer[parser.buffer_pos] == '[' || parser.buffer[parser.buffer_pos] == ']' || - parser.buffer[parser.buffer_pos] == '%' { - // Check if it is a URI-escape sequence. - if parser.buffer[parser.buffer_pos] == '%' { - if !yaml_parser_scan_uri_escapes(parser, directive, start_mark, &s) { - return false - } - } else { - s = read(parser, s) - } - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - hasTag = true - } - - if !hasTag { - yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "did not find expected tag URI") - return false - } - *uri = s - return true -} - -// Decode an URI-escape sequence corresponding to a single UTF-8 character. -func yaml_parser_scan_uri_escapes(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, s *[]byte) bool { - - // Decode the required number of characters. - w := 1024 - for w > 0 { - // Check for a URI-escaped octet. - if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { - return false - } - - if !(parser.buffer[parser.buffer_pos] == '%' && - is_hex(parser.buffer, parser.buffer_pos+1) && - is_hex(parser.buffer, parser.buffer_pos+2)) { - return yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "did not find URI escaped octet") - } - - // Get the octet. - octet := byte((as_hex(parser.buffer, parser.buffer_pos+1) << 4) + as_hex(parser.buffer, parser.buffer_pos+2)) - - // If it is the leading octet, determine the length of the UTF-8 sequence. - if w == 1024 { - w = width(octet) - if w == 0 { - return yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "found an incorrect leading UTF-8 octet") - } - } else { - // Check if the trailing octet is correct. - if octet&0xC0 != 0x80 { - return yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "found an incorrect trailing UTF-8 octet") - } - } - - // Copy the octet and move the pointers. - *s = append(*s, octet) - skip(parser) - skip(parser) - skip(parser) - w-- - } - return true -} - -// Scan a block scalar. -func yaml_parser_scan_block_scalar(parser *yaml_parser_t, token *yaml_token_t, literal bool) bool { - // Eat the indicator '|' or '>'. - start_mark := parser.mark - skip(parser) - - // Scan the additional block scalar indicators. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - // Check for a chomping indicator. - var chomping, increment int - if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { - // Set the chomping method and eat the indicator. - if parser.buffer[parser.buffer_pos] == '+' { - chomping = +1 - } else { - chomping = -1 - } - skip(parser) - - // Check for an indentation indicator. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if is_digit(parser.buffer, parser.buffer_pos) { - // Check that the indentation is greater than 0. - if parser.buffer[parser.buffer_pos] == '0' { - yaml_parser_set_scanner_error(parser, "while scanning a block scalar", - start_mark, "found an indentation indicator equal to 0") - return false - } - - // Get the indentation level and eat the indicator. - increment = as_digit(parser.buffer, parser.buffer_pos) - skip(parser) - } - - } else if is_digit(parser.buffer, parser.buffer_pos) { - // Do the same as above, but in the opposite order. - - if parser.buffer[parser.buffer_pos] == '0' { - yaml_parser_set_scanner_error(parser, "while scanning a block scalar", - start_mark, "found an indentation indicator equal to 0") - return false - } - increment = as_digit(parser.buffer, parser.buffer_pos) - skip(parser) - - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { - if parser.buffer[parser.buffer_pos] == '+' { - chomping = +1 - } else { - chomping = -1 - } - skip(parser) - } - } - - // Eat whitespaces and comments to the end of the line. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - if parser.buffer[parser.buffer_pos] == '#' { - m := parser.mark - parser.comment_buffer = parser.comment_buffer[:0] - for !is_breakz(parser.buffer, parser.buffer_pos) { - p := parser.buffer_pos - skip(parser) - parser.comment_buffer = append(parser.comment_buffer, - parser.buffer[p:parser.buffer_pos]...) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - add_comment(parser, m, string(parser.comment_buffer)) - } - - // Check if we are at the end of the line. - if !is_breakz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a block scalar", - start_mark, "did not find expected comment or line break") - return false - } - - // Eat a line break. - if is_break(parser.buffer, parser.buffer_pos) { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - skip_line(parser) - } - - end_mark := parser.mark - - // Set the indentation level if it was specified. - var indent int - if increment > 0 { - if parser.indent >= 0 { - indent = parser.indent + increment - } else { - indent = increment - } - } - - // Scan the leading line breaks and determine the indentation level if needed. - var s, leading_break, trailing_breaks []byte - if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { - return false - } - - // Scan the block scalar content. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - var leading_blank, trailing_blank bool - for parser.mark.column == indent && !is_z(parser.buffer, parser.buffer_pos) { - // We are at the beginning of a non-empty line. - - // Is it a trailing whitespace? - trailing_blank = is_blank(parser.buffer, parser.buffer_pos) - - // Check if we need to fold the leading line break. - if !literal && !leading_blank && !trailing_blank && len(leading_break) > 0 && leading_break[0] == '\n' { - // Do we need to join the lines by space? - if len(trailing_breaks) == 0 { - s = append(s, ' ') - } - } else { - s = append(s, leading_break...) - } - leading_break = leading_break[:0] - - // Append the remaining line breaks. - s = append(s, trailing_breaks...) - trailing_breaks = trailing_breaks[:0] - - // Is it a leading whitespace? - leading_blank = is_blank(parser.buffer, parser.buffer_pos) - - // Consume the current line. - for !is_breakz(parser.buffer, parser.buffer_pos) { - s = read(parser, s) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Consume the line break. - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - - leading_break = read_line(parser, leading_break) - - // Eat the following indentation spaces and line breaks. - if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { - return false - } - } - - // Chomp the tail. - if chomping != -1 { - s = append(s, leading_break...) - } - if chomping == 1 { - s = append(s, trailing_breaks...) - } - - // Create a token. - *token = yaml_token_t{ - typ: yaml_SCALAR_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: s, - style: yaml_LITERAL_SCALAR_STYLE, - } - if !literal { - token.style = yaml_FOLDED_SCALAR_STYLE - } - return true -} - -// Scan indentation spaces and line breaks for a block scalar. Determine the -// indentation level if needed. -func yaml_parser_scan_block_scalar_breaks(parser *yaml_parser_t, indent *int, breaks *[]byte, start_mark yaml_mark_t, end_mark *yaml_mark_t) bool { - *end_mark = parser.mark - - // Eat the indentation spaces and line breaks. - max_indent := 0 - for { - // Eat the indentation spaces. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - for (*indent == 0 || parser.mark.column < *indent) && is_space(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - if parser.mark.column > max_indent { - max_indent = parser.mark.column - } - - // Check for a tab character messing the indentation. - if (*indent == 0 || parser.mark.column < *indent) && is_tab(parser.buffer, parser.buffer_pos) { - return yaml_parser_set_scanner_error(parser, "while scanning a block scalar", - start_mark, "found a tab character where an indentation space is expected") - } - - // Have we found a non-empty line? - if !is_break(parser.buffer, parser.buffer_pos) { - break - } - - // Consume the line break. - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - // [Go] Should really be returning breaks instead. - *breaks = read_line(parser, *breaks) - *end_mark = parser.mark - } - - // Determine the indentation level if needed. - if *indent == 0 { - *indent = max_indent - if *indent < parser.indent+1 { - *indent = parser.indent + 1 - } - if *indent < 1 { - *indent = 1 - } - } - return true -} - -// Scan a quoted scalar. -func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, single bool) bool { - // Eat the left quote. - start_mark := parser.mark - skip(parser) - - // Consume the content of the quoted scalar. - var s, leading_break, trailing_breaks, whitespaces []byte - for { - // Check that there are no document indicators at the beginning of the line. - if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { - return false - } - - if parser.mark.column == 0 && - ((parser.buffer[parser.buffer_pos+0] == '-' && - parser.buffer[parser.buffer_pos+1] == '-' && - parser.buffer[parser.buffer_pos+2] == '-') || - (parser.buffer[parser.buffer_pos+0] == '.' && - parser.buffer[parser.buffer_pos+1] == '.' && - parser.buffer[parser.buffer_pos+2] == '.')) && - is_blankz(parser.buffer, parser.buffer_pos+3) { - yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", - start_mark, "found unexpected document indicator") - return false - } - - // Check for EOF. - if is_z(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", - start_mark, "found unexpected end of stream") - return false - } - - // Consume non-blank characters. - leading_blanks := false - for !is_blankz(parser.buffer, parser.buffer_pos) { - if single && parser.buffer[parser.buffer_pos] == '\'' && parser.buffer[parser.buffer_pos+1] == '\'' { - // Is is an escaped single quote. - s = append(s, '\'') - skip(parser) - skip(parser) - - } else if single && parser.buffer[parser.buffer_pos] == '\'' { - // It is a right single quote. - break - } else if !single && parser.buffer[parser.buffer_pos] == '"' { - // It is a right double quote. - break - - } else if !single && parser.buffer[parser.buffer_pos] == '\\' && is_break(parser.buffer, parser.buffer_pos+1) { - // It is an escaped line break. - if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { - return false - } - skip(parser) - skip_line(parser) - leading_blanks = true - break - - } else if !single && parser.buffer[parser.buffer_pos] == '\\' { - // It is an escape sequence. - code_length := 0 - - // Check the escape character. - switch parser.buffer[parser.buffer_pos+1] { - case '0': - s = append(s, 0) - case 'a': - s = append(s, '\x07') - case 'b': - s = append(s, '\x08') - case 't', '\t': - s = append(s, '\x09') - case 'n': - s = append(s, '\x0A') - case 'v': - s = append(s, '\x0B') - case 'f': - s = append(s, '\x0C') - case 'r': - s = append(s, '\x0D') - case 'e': - s = append(s, '\x1B') - case ' ': - s = append(s, '\x20') - case '"': - s = append(s, '"') - case '\'': - s = append(s, '\'') - case '\\': - s = append(s, '\\') - case 'N': // NEL (#x85) - s = append(s, '\xC2') - s = append(s, '\x85') - case '_': // #xA0 - s = append(s, '\xC2') - s = append(s, '\xA0') - case 'L': // LS (#x2028) - s = append(s, '\xE2') - s = append(s, '\x80') - s = append(s, '\xA8') - case 'P': // PS (#x2029) - s = append(s, '\xE2') - s = append(s, '\x80') - s = append(s, '\xA9') - case 'x': - code_length = 2 - case 'u': - code_length = 4 - case 'U': - code_length = 8 - default: - yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", - start_mark, "found unknown escape character") - return false - } - - skip(parser) - skip(parser) - - // Consume an arbitrary escape code. - if code_length > 0 { - var value int - - // Scan the character value. - if parser.unread < code_length && !yaml_parser_update_buffer(parser, code_length) { - return false - } - for k := 0; k < code_length; k++ { - if !is_hex(parser.buffer, parser.buffer_pos+k) { - yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", - start_mark, "did not find expected hexdecimal number") - return false - } - value = (value << 4) + as_hex(parser.buffer, parser.buffer_pos+k) - } - - // Check the value and write the character. - if (value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF { - yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", - start_mark, "found invalid Unicode character escape code") - return false - } - if value <= 0x7F { - s = append(s, byte(value)) - } else if value <= 0x7FF { - s = append(s, byte(0xC0+(value>>6))) - s = append(s, byte(0x80+(value&0x3F))) - } else if value <= 0xFFFF { - s = append(s, byte(0xE0+(value>>12))) - s = append(s, byte(0x80+((value>>6)&0x3F))) - s = append(s, byte(0x80+(value&0x3F))) - } else { - s = append(s, byte(0xF0+(value>>18))) - s = append(s, byte(0x80+((value>>12)&0x3F))) - s = append(s, byte(0x80+((value>>6)&0x3F))) - s = append(s, byte(0x80+(value&0x3F))) - } - - // Advance the pointer. - for k := 0; k < code_length; k++ { - skip(parser) - } - } - } else { - // It is a non-escaped non-blank character. - s = read(parser, s) - } - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - } - - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - // Check if we are at the end of the scalar. - if single { - if parser.buffer[parser.buffer_pos] == '\'' { - break - } - } else { - if parser.buffer[parser.buffer_pos] == '"' { - break - } - } - - // Consume blank characters. - for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { - if is_blank(parser.buffer, parser.buffer_pos) { - // Consume a space or a tab character. - if !leading_blanks { - whitespaces = read(parser, whitespaces) - } else { - skip(parser) - } - } else { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - - // Check if it is a first line break. - if !leading_blanks { - whitespaces = whitespaces[:0] - leading_break = read_line(parser, leading_break) - leading_blanks = true - } else { - trailing_breaks = read_line(parser, trailing_breaks) - } - } - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Join the whitespaces or fold line breaks. - if leading_blanks { - // Do we need to fold line breaks? - if len(leading_break) > 0 && leading_break[0] == '\n' { - if len(trailing_breaks) == 0 { - s = append(s, ' ') - } else { - s = append(s, trailing_breaks...) - } - } else { - s = append(s, leading_break...) - s = append(s, trailing_breaks...) - } - trailing_breaks = trailing_breaks[:0] - leading_break = leading_break[:0] - } else { - s = append(s, whitespaces...) - whitespaces = whitespaces[:0] - } - } - - // Eat the right quote. - skip(parser) - end_mark := parser.mark - - // Create a token. - *token = yaml_token_t{ - typ: yaml_SCALAR_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: s, - style: yaml_SINGLE_QUOTED_SCALAR_STYLE, - } - if !single { - token.style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - return true -} - -// Scan a plain scalar. -func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) bool { - - var s, leading_break, trailing_breaks, whitespaces []byte - var leading_blanks bool - var indent = parser.indent + 1 - - start_mark := parser.mark - end_mark := parser.mark - - // Consume the content of the plain scalar. - for { - // Check for a document indicator. - if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { - return false - } - if parser.mark.column == 0 && - ((parser.buffer[parser.buffer_pos+0] == '-' && - parser.buffer[parser.buffer_pos+1] == '-' && - parser.buffer[parser.buffer_pos+2] == '-') || - (parser.buffer[parser.buffer_pos+0] == '.' && - parser.buffer[parser.buffer_pos+1] == '.' && - parser.buffer[parser.buffer_pos+2] == '.')) && - is_blankz(parser.buffer, parser.buffer_pos+3) { - break - } - - // Check for a comment. - if parser.buffer[parser.buffer_pos] == '#' { - break - } - - // Consume non-blank characters. - for !is_blankz(parser.buffer, parser.buffer_pos) { - - // Check for indicators that may end a plain scalar. - if (parser.buffer[parser.buffer_pos] == ':' && is_blankz(parser.buffer, parser.buffer_pos+1)) || - (parser.flow_level > 0 && - (parser.buffer[parser.buffer_pos] == ',' || - parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == '[' || - parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || - parser.buffer[parser.buffer_pos] == '}')) { - break - } - - // Check if we need to join whitespaces and breaks. - if leading_blanks || len(whitespaces) > 0 { - if leading_blanks { - // Do we need to fold line breaks? - if leading_break[0] == '\n' { - if len(trailing_breaks) == 0 { - s = append(s, ' ') - } else { - s = append(s, trailing_breaks...) - } - } else { - s = append(s, leading_break...) - s = append(s, trailing_breaks...) - } - trailing_breaks = trailing_breaks[:0] - leading_break = leading_break[:0] - leading_blanks = false - } else { - s = append(s, whitespaces...) - whitespaces = whitespaces[:0] - } - } - - // Copy the character. - s = read(parser, s) - - end_mark = parser.mark - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - } - - // Is it the end? - if !(is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos)) { - break - } - - // Consume blank characters. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { - if is_blank(parser.buffer, parser.buffer_pos) { - - // Check for tab characters that abuse indentation. - if leading_blanks && parser.mark.column < indent && is_tab(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a plain scalar", - start_mark, "found a tab character that violates indentation") - return false - } - - // Consume a space or a tab character. - if !leading_blanks { - whitespaces = read(parser, whitespaces) - } else { - skip(parser) - } - } else { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - - // Check if it is a first line break. - if !leading_blanks { - whitespaces = whitespaces[:0] - leading_break = read_line(parser, leading_break) - leading_blanks = true - } else { - trailing_breaks = read_line(parser, trailing_breaks) - } - } - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check indentation level. - if parser.flow_level == 0 && parser.mark.column < indent { - break - } - } - - // Create a token. - *token = yaml_token_t{ - typ: yaml_SCALAR_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: s, - style: yaml_PLAIN_SCALAR_STYLE, - } - - // Note that we change the 'simple_key_allowed' flag. - if leading_blanks { - parser.simple_key_allowed = true - } - return true -} diff --git a/vendor/cuelang.org/go/internal/third_party/yaml/yaml.go b/vendor/cuelang.org/go/internal/third_party/yaml/yaml.go deleted file mode 100644 index fa1caccdda..0000000000 --- a/vendor/cuelang.org/go/internal/third_party/yaml/yaml.go +++ /dev/null @@ -1,112 +0,0 @@ -// Package yaml implements YAML support for the Go language. -// -// Source code and other details for the project are available at GitHub: -// -// https://github.com/go-yaml/yaml -package yaml - -import ( - "fmt" - "io" - "strconv" - "strings" - - "cuelang.org/go/cue/ast" -) - -// Unmarshal decodes the first document found within the in byte slice -// and returns it as a CUE syntax AST. -func Unmarshal(filename string, in []byte) (expr ast.Expr, err error) { - return unmarshal(filename, in) -} - -// A Decoder reads and decodes YAML values from an input stream. -type Decoder struct { - strict bool - firstDone bool - parser *parser -} - -// NewDecoder returns a new decoder that reads from r. -// -// The decoder introduces its own buffering and may read -// data from r beyond the YAML values requested. -func NewDecoder(filename string, src interface{}) (*Decoder, error) { - d, err := newParser(filename, src) - if err != nil { - return nil, err - } - return &Decoder{parser: d}, nil -} - -// Decode reads the next YAML-encoded value from its input and returns -// it as CUE syntax. It returns io.EOF if there are no more value in the -// stream. -func (dec *Decoder) Decode() (expr ast.Expr, err error) { - d := newDecoder(dec.parser) - defer handleErr(&err) - node := dec.parser.parse() - if node == nil { - if !dec.firstDone { - expr = ast.NewNull() - } - return expr, io.EOF - } - dec.firstDone = true - expr = d.unmarshal(node) - if len(d.terrors) > 0 { - return nil, &TypeError{d.terrors} - } - return expr, nil -} - -func unmarshal(filename string, in []byte) (expr ast.Expr, err error) { - defer handleErr(&err) - p, err := newParser(filename, in) - if err != nil { - return nil, err - } - defer p.destroy() - node := p.parse() - d := newDecoder(p) - if node != nil { - expr = d.unmarshal(node) - } - if len(d.terrors) > 0 { - return nil, &TypeError{d.terrors} - } - return expr, nil -} - -func handleErr(err *error) { - if v := recover(); v != nil { - if e, ok := v.(yamlError); ok { - *err = e.err - } else { - panic(v) - } - } -} - -type yamlError struct { - err error -} - -func (p *parser) failf(line int, format string, args ...interface{}) { - where := p.parser.filename + ":" - line++ - where += strconv.Itoa(line) + ": " - panic(yamlError{fmt.Errorf(where+format, args...)}) -} - -// A TypeError is returned by Unmarshal when one or more fields in -// the YAML document cannot be properly decoded into the requested -// types. When this error is returned, the value is still -// unmarshaled partially. -type TypeError struct { - Errors []string -} - -func (e *TypeError) Error() string { - return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n ")) -} diff --git a/vendor/cuelang.org/go/internal/third_party/yaml/yamlh.go b/vendor/cuelang.org/go/internal/third_party/yaml/yamlh.go deleted file mode 100644 index 3d4367bb09..0000000000 --- a/vendor/cuelang.org/go/internal/third_party/yaml/yamlh.go +++ /dev/null @@ -1,755 +0,0 @@ -package yaml - -import ( - "fmt" - "io" -) - -// The version directive data. -type yaml_version_directive_t struct { - major int8 // The major version number. - minor int8 // The minor version number. -} - -// The tag directive data. -type yaml_tag_directive_t struct { - handle []byte // The tag handle. - prefix []byte // The tag prefix. -} - -type yaml_encoding_t int - -// The stream encoding. -const ( - // Let the parser choose the encoding. - yaml_ANY_ENCODING yaml_encoding_t = iota - - yaml_UTF8_ENCODING // The default UTF-8 encoding. - yaml_UTF16LE_ENCODING // The UTF-16-LE encoding with BOM. - yaml_UTF16BE_ENCODING // The UTF-16-BE encoding with BOM. -) - -type yaml_break_t int - -// Line break types. -const ( - // Let the parser choose the break type. - yaml_ANY_BREAK yaml_break_t = iota - - yaml_CR_BREAK // Use CR for line breaks (Mac style). - yaml_LN_BREAK // Use LN for line breaks (Unix style). - yaml_CRLN_BREAK // Use CR LN for line breaks (DOS style). -) - -type yaml_error_type_t int - -// Many bad things could happen with the parser and emitter. -const ( - // No error is produced. - yaml_NO_ERROR yaml_error_type_t = iota - - yaml_MEMORY_ERROR // Cannot allocate or reallocate a block of memory. - yaml_READER_ERROR // Cannot read or decode the input stream. - yaml_SCANNER_ERROR // Cannot scan the input stream. - yaml_PARSER_ERROR // Cannot parse the input stream. - yaml_COMPOSER_ERROR // Cannot compose a YAML document. - yaml_WRITER_ERROR // Cannot write to the output stream. - yaml_EMITTER_ERROR // Cannot emit a YAML stream. -) - -// The pointer position. -type yaml_mark_t struct { - index int // The position index. - line int // The position line. - column int // The position column. -} - -// Node Styles - -type yaml_style_t int8 - -type yaml_scalar_style_t yaml_style_t - -// Scalar styles. -const ( - // Let the emitter choose the style. - yaml_ANY_SCALAR_STYLE yaml_scalar_style_t = iota - - yaml_PLAIN_SCALAR_STYLE // The plain scalar style. - yaml_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style. - yaml_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style. - yaml_LITERAL_SCALAR_STYLE // The literal scalar style. - yaml_FOLDED_SCALAR_STYLE // The folded scalar style. -) - -type yaml_sequence_style_t yaml_style_t - -// Sequence styles. -const ( - // Let the emitter choose the style. - yaml_ANY_SEQUENCE_STYLE yaml_sequence_style_t = iota - - yaml_BLOCK_SEQUENCE_STYLE // The block sequence style. - yaml_FLOW_SEQUENCE_STYLE // The flow sequence style. -) - -type yaml_mapping_style_t yaml_style_t - -// Mapping styles. -const ( - // Let the emitter choose the style. - yaml_ANY_MAPPING_STYLE yaml_mapping_style_t = iota - - yaml_BLOCK_MAPPING_STYLE // The block mapping style. - yaml_FLOW_MAPPING_STYLE // The flow mapping style. -) - -// Tokens - -type yaml_token_type_t int - -// Token types. -const ( - // An empty token. - yaml_NO_TOKEN yaml_token_type_t = iota - - yaml_STREAM_START_TOKEN // A STREAM-START token. - yaml_STREAM_END_TOKEN // A STREAM-END token. - - yaml_VERSION_DIRECTIVE_TOKEN // A VERSION-DIRECTIVE token. - yaml_TAG_DIRECTIVE_TOKEN // A TAG-DIRECTIVE token. - yaml_DOCUMENT_START_TOKEN // A DOCUMENT-START token. - yaml_DOCUMENT_END_TOKEN // A DOCUMENT-END token. - - yaml_BLOCK_SEQUENCE_START_TOKEN // A BLOCK-SEQUENCE-START token. - yaml_BLOCK_MAPPING_START_TOKEN // A BLOCK-SEQUENCE-END token. - yaml_BLOCK_END_TOKEN // A BLOCK-END token. - - yaml_FLOW_SEQUENCE_START_TOKEN // A FLOW-SEQUENCE-START token. - yaml_FLOW_SEQUENCE_END_TOKEN // A FLOW-SEQUENCE-END token. - yaml_FLOW_MAPPING_START_TOKEN // A FLOW-MAPPING-START token. - yaml_FLOW_MAPPING_END_TOKEN // A FLOW-MAPPING-END token. - - yaml_BLOCK_ENTRY_TOKEN // A BLOCK-ENTRY token. - yaml_FLOW_ENTRY_TOKEN // A FLOW-ENTRY token. - yaml_KEY_TOKEN // A KEY token. - yaml_VALUE_TOKEN // A VALUE token. - - yaml_ALIAS_TOKEN // An ALIAS token. - yaml_ANCHOR_TOKEN // An ANCHOR token. - yaml_TAG_TOKEN // A TAG token. - yaml_SCALAR_TOKEN // A SCALAR token. -) - -func (tt yaml_token_type_t) String() string { - switch tt { - case yaml_NO_TOKEN: - return "yaml_NO_TOKEN" - case yaml_STREAM_START_TOKEN: - return "yaml_STREAM_START_TOKEN" - case yaml_STREAM_END_TOKEN: - return "yaml_STREAM_END_TOKEN" - case yaml_VERSION_DIRECTIVE_TOKEN: - return "yaml_VERSION_DIRECTIVE_TOKEN" - case yaml_TAG_DIRECTIVE_TOKEN: - return "yaml_TAG_DIRECTIVE_TOKEN" - case yaml_DOCUMENT_START_TOKEN: - return "yaml_DOCUMENT_START_TOKEN" - case yaml_DOCUMENT_END_TOKEN: - return "yaml_DOCUMENT_END_TOKEN" - case yaml_BLOCK_SEQUENCE_START_TOKEN: - return "yaml_BLOCK_SEQUENCE_START_TOKEN" - case yaml_BLOCK_MAPPING_START_TOKEN: - return "yaml_BLOCK_MAPPING_START_TOKEN" - case yaml_BLOCK_END_TOKEN: - return "yaml_BLOCK_END_TOKEN" - case yaml_FLOW_SEQUENCE_START_TOKEN: - return "yaml_FLOW_SEQUENCE_START_TOKEN" - case yaml_FLOW_SEQUENCE_END_TOKEN: - return "yaml_FLOW_SEQUENCE_END_TOKEN" - case yaml_FLOW_MAPPING_START_TOKEN: - return "yaml_FLOW_MAPPING_START_TOKEN" - case yaml_FLOW_MAPPING_END_TOKEN: - return "yaml_FLOW_MAPPING_END_TOKEN" - case yaml_BLOCK_ENTRY_TOKEN: - return "yaml_BLOCK_ENTRY_TOKEN" - case yaml_FLOW_ENTRY_TOKEN: - return "yaml_FLOW_ENTRY_TOKEN" - case yaml_KEY_TOKEN: - return "yaml_KEY_TOKEN" - case yaml_VALUE_TOKEN: - return "yaml_VALUE_TOKEN" - case yaml_ALIAS_TOKEN: - return "yaml_ALIAS_TOKEN" - case yaml_ANCHOR_TOKEN: - return "yaml_ANCHOR_TOKEN" - case yaml_TAG_TOKEN: - return "yaml_TAG_TOKEN" - case yaml_SCALAR_TOKEN: - return "yaml_SCALAR_TOKEN" - } - return "" -} - -// The token structure. -type yaml_token_t struct { - // The token type. - typ yaml_token_type_t - - // The start/end of the token. - start_mark, end_mark yaml_mark_t - - // The stream encoding (for yaml_STREAM_START_TOKEN). - encoding yaml_encoding_t - - // The alias/anchor/scalar value or tag/tag directive handle - // (for yaml_ALIAS_TOKEN, yaml_ANCHOR_TOKEN, yaml_SCALAR_TOKEN, yaml_TAG_TOKEN, yaml_TAG_DIRECTIVE_TOKEN). - value []byte - - // The tag suffix (for yaml_TAG_TOKEN). - suffix []byte - - // The tag directive prefix (for yaml_TAG_DIRECTIVE_TOKEN). - prefix []byte - - // The scalar style (for yaml_SCALAR_TOKEN). - style yaml_scalar_style_t - - // The version directive major/minor (for yaml_VERSION_DIRECTIVE_TOKEN). - major, minor int8 -} - -// Events - -type yaml_event_type_t int8 - -// Event types. -const ( - // An empty event. - yaml_NO_EVENT yaml_event_type_t = iota - - yaml_STREAM_START_EVENT // A STREAM-START event. - yaml_STREAM_END_EVENT // A STREAM-END event. - yaml_DOCUMENT_START_EVENT // A DOCUMENT-START event. - yaml_DOCUMENT_END_EVENT // A DOCUMENT-END event. - yaml_ALIAS_EVENT // An ALIAS event. - yaml_SCALAR_EVENT // A SCALAR event. - yaml_SEQUENCE_START_EVENT // A SEQUENCE-START event. - yaml_SEQUENCE_END_EVENT // A SEQUENCE-END event. - yaml_MAPPING_START_EVENT // A MAPPING-START event. - yaml_MAPPING_END_EVENT // A MAPPING-END event. -) - -var eventStrings = []string{ - yaml_NO_EVENT: "none", - yaml_STREAM_START_EVENT: "stream start", - yaml_STREAM_END_EVENT: "stream end", - yaml_DOCUMENT_START_EVENT: "document start", - yaml_DOCUMENT_END_EVENT: "document end", - yaml_ALIAS_EVENT: "alias", - yaml_SCALAR_EVENT: "scalar", - yaml_SEQUENCE_START_EVENT: "sequence start", - yaml_SEQUENCE_END_EVENT: "sequence end", - yaml_MAPPING_START_EVENT: "mapping start", - yaml_MAPPING_END_EVENT: "mapping end", -} - -func (e yaml_event_type_t) String() string { - if e < 0 || int(e) >= len(eventStrings) { - return fmt.Sprintf("unknown event %d", e) - } - return eventStrings[e] -} - -// The event structure. -type yaml_event_t struct { - - // The event type. - typ yaml_event_type_t - - // The start and end of the event. - start_mark, end_mark yaml_mark_t - - // The document encoding (for yaml_STREAM_START_EVENT). - encoding yaml_encoding_t - - // The version directive (for yaml_DOCUMENT_START_EVENT). - version_directive *yaml_version_directive_t - - // The list of tag directives (for yaml_DOCUMENT_START_EVENT). - tag_directives []yaml_tag_directive_t - - // The anchor (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_ALIAS_EVENT). - anchor []byte - - // The tag (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). - tag []byte - - // The scalar value (for yaml_SCALAR_EVENT). - value []byte - - // Is the document start/end indicator implicit, or the tag optional? - // (for yaml_DOCUMENT_START_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_SCALAR_EVENT). - implicit bool - - // Is the tag optional for any non-plain style? (for yaml_SCALAR_EVENT). - quoted_implicit bool - - // The style (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). - style yaml_style_t -} - -func (e *yaml_event_t) scalar_style() yaml_scalar_style_t { return yaml_scalar_style_t(e.style) } -func (e *yaml_event_t) sequence_style() yaml_sequence_style_t { return yaml_sequence_style_t(e.style) } -func (e *yaml_event_t) mapping_style() yaml_mapping_style_t { return yaml_mapping_style_t(e.style) } - -// Nodes - -const ( - yaml_NULL_TAG = "tag:yaml.org,2002:null" // The tag !!null with the only possible value: null. - yaml_BOOL_TAG = "tag:yaml.org,2002:bool" // The tag !!bool with the values: true and false. - yaml_STR_TAG = "tag:yaml.org,2002:str" // The tag !!str for string values. - yaml_INT_TAG = "tag:yaml.org,2002:int" // The tag !!int for integer values. - yaml_FLOAT_TAG = "tag:yaml.org,2002:float" // The tag !!float for float values. - yaml_TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp" // The tag !!timestamp for date and time values. - - yaml_SEQ_TAG = "tag:yaml.org,2002:seq" // The tag !!seq is used to denote sequences. - yaml_MAP_TAG = "tag:yaml.org,2002:map" // The tag !!map is used to denote mapping. - - // Not in original libyaml. - yaml_BINARY_TAG = "tag:yaml.org,2002:binary" - yaml_MERGE_TAG = "tag:yaml.org,2002:merge" - - yaml_DEFAULT_SCALAR_TAG = yaml_STR_TAG // The default scalar tag is !!str. - yaml_DEFAULT_SEQUENCE_TAG = yaml_SEQ_TAG // The default sequence tag is !!seq. - yaml_DEFAULT_MAPPING_TAG = yaml_MAP_TAG // The default mapping tag is !!map. -) - -type yaml_node_type_t int - -// Node types. -const ( - // An empty node. - yaml_NO_NODE yaml_node_type_t = iota - - yaml_SCALAR_NODE // A scalar node. - yaml_SEQUENCE_NODE // A sequence node. - yaml_MAPPING_NODE // A mapping node. -) - -// An element of a sequence node. -type yaml_node_item_t int - -// An element of a mapping node. -type yaml_node_pair_t struct { - key int // The key of the element. - value int // The value of the element. -} - -// The node structure. -type yaml_node_t struct { - typ yaml_node_type_t // The node type. - tag []byte // The node tag. - - // The node data. - - // The scalar parameters (for yaml_SCALAR_NODE). - scalar struct { - value []byte // The scalar value. - length int // The length of the scalar value. - style yaml_scalar_style_t // The scalar style. - } - - // The sequence parameters (for YAML_SEQUENCE_NODE). - sequence struct { - items_data []yaml_node_item_t // The stack of sequence items. - style yaml_sequence_style_t // The sequence style. - } - - // The mapping parameters (for yaml_MAPPING_NODE). - mapping struct { - pairs_data []yaml_node_pair_t // The stack of mapping pairs (key, value). - pairs_start *yaml_node_pair_t // The beginning of the stack. - pairs_end *yaml_node_pair_t // The end of the stack. - pairs_top *yaml_node_pair_t // The top of the stack. - style yaml_mapping_style_t // The mapping style. - } - - start_mark yaml_mark_t // The beginning of the node. - end_mark yaml_mark_t // The end of the node. - -} - -// The document structure. -type yaml_document_t struct { - - // The document nodes. - nodes []yaml_node_t - - // The version directive. - version_directive *yaml_version_directive_t - - // The list of tag directives. - tag_directives_data []yaml_tag_directive_t - tag_directives_start int // The beginning of the tag directives list. - tag_directives_end int // The end of the tag directives list. - - start_implicit int // Is the document start indicator implicit? - end_implicit int // Is the document end indicator implicit? - - // The start/end of the document. - start_mark, end_mark yaml_mark_t -} - -// The prototype of a read handler. -// -// The read handler is called when the parser needs to read more bytes from the -// source. The handler should write not more than size bytes to the buffer. -// The number of written bytes should be set to the size_read variable. -// -// [in,out] data A pointer to an application data specified by -// -// yaml_parser_set_input(). -// -// [out] buffer The buffer to write the data from the source. -// [in] size The size of the buffer. -// [out] size_read The actual number of bytes read from the source. -// -// On success, the handler should return 1. If the handler failed, -// the returned value should be 0. On EOF, the handler should set the -// size_read to 0 and return 1. -type yaml_read_handler_t func(parser *yaml_parser_t, buffer []byte) (n int, err error) - -// This structure holds information about a potential simple key. -type yaml_simple_key_t struct { - possible bool // Is a simple key possible? - required bool // Is a simple key required? - token_number int // The number of the token. - mark yaml_mark_t // The position mark. -} - -// The states of the parser. -type yaml_parser_state_t int - -const ( - yaml_PARSE_STREAM_START_STATE yaml_parser_state_t = iota - - yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE // Expect the beginning of an implicit document. - yaml_PARSE_DOCUMENT_START_STATE // Expect DOCUMENT-START. - yaml_PARSE_DOCUMENT_CONTENT_STATE // Expect the content of a document. - yaml_PARSE_DOCUMENT_END_STATE // Expect DOCUMENT-END. - yaml_PARSE_BLOCK_NODE_STATE // Expect a block node. - yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE // Expect a block node or indentless sequence. - yaml_PARSE_FLOW_NODE_STATE // Expect a flow node. - yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a block sequence. - yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE // Expect an entry of a block sequence. - yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE // Expect an entry of an indentless sequence. - yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. - yaml_PARSE_BLOCK_MAPPING_KEY_STATE // Expect a block mapping key. - yaml_PARSE_BLOCK_MAPPING_VALUE_STATE // Expect a block mapping value. - yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a flow sequence. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE // Expect an entry of a flow sequence. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE // Expect a key of an ordered mapping. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE // Expect a value of an ordered mapping. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE // Expect the and of an ordered mapping entry. - yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. - yaml_PARSE_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. - yaml_PARSE_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. - yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE // Expect an empty value of a flow mapping. - yaml_PARSE_END_STATE // Expect nothing. -) - -func (ps yaml_parser_state_t) String() string { - switch ps { - case yaml_PARSE_STREAM_START_STATE: - return "yaml_PARSE_STREAM_START_STATE" - case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: - return "yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE" - case yaml_PARSE_DOCUMENT_START_STATE: - return "yaml_PARSE_DOCUMENT_START_STATE" - case yaml_PARSE_DOCUMENT_CONTENT_STATE: - return "yaml_PARSE_DOCUMENT_CONTENT_STATE" - case yaml_PARSE_DOCUMENT_END_STATE: - return "yaml_PARSE_DOCUMENT_END_STATE" - case yaml_PARSE_BLOCK_NODE_STATE: - return "yaml_PARSE_BLOCK_NODE_STATE" - case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: - return "yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE" - case yaml_PARSE_FLOW_NODE_STATE: - return "yaml_PARSE_FLOW_NODE_STATE" - case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: - return "yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE" - case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: - return "yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE" - case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: - return "yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE" - case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: - return "yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE" - case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: - return "yaml_PARSE_BLOCK_MAPPING_KEY_STATE" - case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: - return "yaml_PARSE_BLOCK_MAPPING_VALUE_STATE" - case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE" - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE" - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE" - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE" - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE" - case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: - return "yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE" - case yaml_PARSE_FLOW_MAPPING_KEY_STATE: - return "yaml_PARSE_FLOW_MAPPING_KEY_STATE" - case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: - return "yaml_PARSE_FLOW_MAPPING_VALUE_STATE" - case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: - return "yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE" - case yaml_PARSE_END_STATE: - return "yaml_PARSE_END_STATE" - } - return "" -} - -// This structure holds aliases data. -type yaml_alias_data_t struct { - anchor []byte // The anchor. - index int // The node id. - mark yaml_mark_t // The anchor mark. -} - -type yaml_comment_t struct { - mark yaml_mark_t - text string -} - -// The parser structure. -// -// All members are internal. Manage the structure using the -// yaml_parser_ family of functions. -type yaml_parser_t struct { - - // Error handling - - filename string - - error yaml_error_type_t // Error type. - - problem string // Error description. - - // The byte about which the problem occurred. - problem_offset int - problem_value int - problem_mark yaml_mark_t - - // The error context. - context string - context_mark yaml_mark_t - - // Reader stuff - - read_handler yaml_read_handler_t // Read handler. - - input_reader io.Reader // File input data. - input []byte // String input data. - input_pos int - - eof bool // EOF flag - - buffer []byte // The working buffer. - buffer_pos int // The current position of the buffer. - - unread int // The number of unread characters in the buffer. - - raw_buffer []byte // The raw buffer. - raw_buffer_pos int // The current position of the buffer. - - comment_buffer []byte - - encoding yaml_encoding_t // The input encoding. - - offset int // The offset of the current position (in bytes). - mark yaml_mark_t // The mark of the current position. - - linesSinceLast int - spacesSinceLast int - - // Scanner stuff - - stream_start_produced bool // Have we started to scan the input stream? - stream_end_produced bool // Have we reached the end of the input stream? - - flow_level int // The number of unclosed '[' and '{' indicators. - - tokens []yaml_token_t // The tokens queue. - tokens_head int // The head of the tokens queue. - tokens_parsed int // The number of tokens fetched from the queue. - token_available bool // Does the tokens queue contain a token ready for dequeueing. - - comments []yaml_comment_t - - indent int // The current indentation level. - indents []int // The indentation levels stack. - - simple_key_allowed bool // May a simple key occur at the current position? - simple_keys []yaml_simple_key_t // The stack of simple keys. - - // Parser stuff - - state yaml_parser_state_t // The current parser state. - states []yaml_parser_state_t // The parser states stack. - marks []yaml_mark_t // The stack of marks. - tag_directives []yaml_tag_directive_t // The list of TAG directives. - - // Dumper stuff - - aliases []yaml_alias_data_t // The alias data. - - document *yaml_document_t // The currently parsed document. -} - -// Emitter Definitions - -// The prototype of a write handler. -// -// The write handler is called when the emitter needs to flush the accumulated -// characters to the output. The handler should write @a size bytes of the -// @a buffer to the output. -// -// @param[in,out] data A pointer to an application data specified by -// -// yaml_emitter_set_output(). -// -// @param[in] buffer The buffer with bytes to be written. -// @param[in] size The size of the buffer. -// -// @returns On success, the handler should return @c 1. If the handler failed, -// the returned value should be @c 0. -type yaml_write_handler_t func(emitter *yaml_emitter_t, buffer []byte) error - -type yaml_emitter_state_t int - -// The emitter states. -const ( - // Expect STREAM-START. - yaml_EMIT_STREAM_START_STATE yaml_emitter_state_t = iota - - yaml_EMIT_FIRST_DOCUMENT_START_STATE // Expect the first DOCUMENT-START or STREAM-END. - yaml_EMIT_DOCUMENT_START_STATE // Expect DOCUMENT-START or STREAM-END. - yaml_EMIT_DOCUMENT_CONTENT_STATE // Expect the content of a document. - yaml_EMIT_DOCUMENT_END_STATE // Expect DOCUMENT-END. - yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a flow sequence. - yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE // Expect an item of a flow sequence. - yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. - yaml_EMIT_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. - yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a flow mapping. - yaml_EMIT_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. - yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a block sequence. - yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE // Expect an item of a block sequence. - yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. - yaml_EMIT_BLOCK_MAPPING_KEY_STATE // Expect the key of a block mapping. - yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a block mapping. - yaml_EMIT_BLOCK_MAPPING_VALUE_STATE // Expect a value of a block mapping. - yaml_EMIT_END_STATE // Expect nothing. -) - -// The emitter structure. -// -// All members are internal. Manage the structure using the @c yaml_emitter_ -// family of functions. -type yaml_emitter_t struct { - - // Error handling - - error yaml_error_type_t // Error type. - problem string // Error description. - - // Writer stuff - - write_handler yaml_write_handler_t // Write handler. - - output_buffer *[]byte // String output data. - output_writer io.Writer // File output data. - - buffer []byte // The working buffer. - buffer_pos int // The current position of the buffer. - - raw_buffer []byte // The raw buffer. - raw_buffer_pos int // The current position of the buffer. - - encoding yaml_encoding_t // The stream encoding. - - // Emitter stuff - - canonical bool // If the output is in the canonical style? - best_indent int // The number of indentation spaces. - best_width int // The preferred width of the output lines. - unicode bool // Allow unescaped non-ASCII characters? - line_break yaml_break_t // The preferred line break. - - state yaml_emitter_state_t // The current emitter state. - states []yaml_emitter_state_t // The stack of states. - - events []yaml_event_t // The event queue. - events_head int // The head of the event queue. - - indents []int // The stack of indentation levels. - - tag_directives []yaml_tag_directive_t // The list of tag directives. - - indent int // The current indentation level. - - flow_level int // The current flow level. - - root_context bool // Is it the document root context? - sequence_context bool // Is it a sequence context? - mapping_context bool // Is it a mapping context? - simple_key_context bool // Is it a simple mapping key context? - - line int // The current line. - column int // The current column. - whitespace bool // If the last character was a whitespace? - indention bool // If the last character was an indentation character (' ', '-', '?', ':')? - open_ended bool // If an explicit document end is required? - - // Anchor analysis. - anchor_data struct { - anchor []byte // The anchor value. - alias bool // Is it an alias? - } - - // Tag analysis. - tag_data struct { - handle []byte // The tag handle. - suffix []byte // The tag suffix. - } - - // Scalar analysis. - scalar_data struct { - value []byte // The scalar value. - multiline bool // Does the scalar contain line breaks? - flow_plain_allowed bool // Can the scalar be expessed in the flow plain style? - block_plain_allowed bool // Can the scalar be expressed in the block plain style? - single_quoted_allowed bool // Can the scalar be expressed in the single quoted style? - block_allowed bool // Can the scalar be expressed in the literal or folded styles? - style yaml_scalar_style_t // The output style. - } - - // Dumper stuff - - opened bool // If the stream was already opened? - closed bool // If the stream was already closed? - - // The information associated with the document nodes. - anchors *struct { - references int // The number of references. - anchor int // The anchor id. - serialized bool // If the node has been emitted? - } - - last_anchor_id int // The last assigned anchor id. - - document *yaml_document_t // The currently emitted document. -} diff --git a/vendor/cuelang.org/go/internal/third_party/yaml/yamlprivateh.go b/vendor/cuelang.org/go/internal/third_party/yaml/yamlprivateh.go deleted file mode 100644 index 8110ce3c37..0000000000 --- a/vendor/cuelang.org/go/internal/third_party/yaml/yamlprivateh.go +++ /dev/null @@ -1,173 +0,0 @@ -package yaml - -const ( - // The size of the input raw buffer. - input_raw_buffer_size = 512 - - // The size of the input buffer. - // It should be possible to decode the whole raw buffer. - input_buffer_size = input_raw_buffer_size * 3 - - // The size of the output buffer. - output_buffer_size = 128 - - // The size of the output raw buffer. - // It should be possible to encode the whole output buffer. - output_raw_buffer_size = (output_buffer_size*2 + 2) - - // The size of other stacks and queues. - initial_stack_size = 16 - initial_queue_size = 16 - initial_string_size = 16 -) - -// Check if the character at the specified position is an alphabetical -// character, a digit, '_', or '-'. -func is_alpha(b []byte, i int) bool { - return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'Z' || b[i] >= 'a' && b[i] <= 'z' || b[i] == '_' || b[i] == '-' -} - -// Check if the character at the specified position is a digit. -func is_digit(b []byte, i int) bool { - return b[i] >= '0' && b[i] <= '9' -} - -// Get the value of a digit. -func as_digit(b []byte, i int) int { - return int(b[i]) - '0' -} - -// Check if the character at the specified position is a hex-digit. -func is_hex(b []byte, i int) bool { - return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'F' || b[i] >= 'a' && b[i] <= 'f' -} - -// Get the value of a hex-digit. -func as_hex(b []byte, i int) int { - bi := b[i] - if bi >= 'A' && bi <= 'F' { - return int(bi) - 'A' + 10 - } - if bi >= 'a' && bi <= 'f' { - return int(bi) - 'a' + 10 - } - return int(bi) - '0' -} - -// Check if the character is ASCII. -func is_ascii(b []byte, i int) bool { - return b[i] <= 0x7F -} - -// Check if the character at the start of the buffer can be printed unescaped. -func is_printable(b []byte, i int) bool { - return ((b[i] == 0x0A) || // . == #x0A - (b[i] >= 0x20 && b[i] <= 0x7E) || // #x20 <= . <= #x7E - (b[i] == 0xC2 && b[i+1] >= 0xA0) || // #0xA0 <= . <= #xD7FF - (b[i] > 0xC2 && b[i] < 0xED) || - (b[i] == 0xED && b[i+1] < 0xA0) || - (b[i] == 0xEE) || - (b[i] == 0xEF && // #xE000 <= . <= #xFFFD - !(b[i+1] == 0xBB && b[i+2] == 0xBF) && // && . != #xFEFF - !(b[i+1] == 0xBF && (b[i+2] == 0xBE || b[i+2] == 0xBF)))) -} - -// Check if the character at the specified position is NUL. -func is_z(b []byte, i int) bool { - return b[i] == 0x00 -} - -// Check if the beginning of the buffer is a BOM. -func is_bom(b []byte, i int) bool { - return b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF -} - -// Check if the character at the specified position is space. -func is_space(b []byte, i int) bool { - return b[i] == ' ' -} - -// Check if the character at the specified position is tab. -func is_tab(b []byte, i int) bool { - return b[i] == '\t' -} - -// Check if the character at the specified position is blank (space or tab). -func is_blank(b []byte, i int) bool { - //return is_space(b, i) || is_tab(b, i) - return b[i] == ' ' || b[i] == '\t' -} - -// Check if the character at the specified position is a line break. -func is_break(b []byte, i int) bool { - return (b[i] == '\r' || // CR (#xD) - b[i] == '\n' || // LF (#xA) - b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9) // PS (#x2029) -} - -func is_crlf(b []byte, i int) bool { - return b[i] == '\r' && b[i+1] == '\n' -} - -// Check if the character is a line break or NUL. -func is_breakz(b []byte, i int) bool { - //return is_break(b, i) || is_z(b, i) - return ( // is_break: - b[i] == '\r' || // CR (#xD) - b[i] == '\n' || // LF (#xA) - b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) - // is_z: - b[i] == 0) -} - -// Check if the character is a line break, space, or NUL. -func is_spacez(b []byte, i int) bool { - //return is_space(b, i) || is_breakz(b, i) - return ( // is_space: - b[i] == ' ' || - // is_breakz: - b[i] == '\r' || // CR (#xD) - b[i] == '\n' || // LF (#xA) - b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) - b[i] == 0) -} - -// Check if the character is a line break, space, tab, or NUL. -func is_blankz(b []byte, i int) bool { - //return is_blank(b, i) || is_breakz(b, i) - return ( // is_blank: - b[i] == ' ' || b[i] == '\t' || - // is_breakz: - b[i] == '\r' || // CR (#xD) - b[i] == '\n' || // LF (#xA) - b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) - b[i] == 0) -} - -// Determine the width of the character. -func width(b byte) int { - // Don't replace these by a switch without first - // confirming that it is being inlined. - if b&0x80 == 0x00 { - return 1 - } - if b&0xE0 == 0xC0 { - return 2 - } - if b&0xF0 == 0xE0 { - return 3 - } - if b&0xF8 == 0xF0 { - return 4 - } - return 0 - -} diff --git a/vendor/cuelang.org/go/internal/value/value.go b/vendor/cuelang.org/go/internal/value/value.go index 7f5e0bf627..4757b32e96 100644 --- a/vendor/cuelang.org/go/internal/value/value.go +++ b/vendor/cuelang.org/go/internal/value/value.go @@ -27,10 +27,6 @@ import ( "cuelang.org/go/internal/types" ) -func ConvertToRuntime(c *cue.Context) *cue.Runtime { - return (*cue.Runtime)(c) -} - func ConvertToContext[Ctx *cue.Runtime | *cue.Context](ctx Ctx) *cue.Context { if ctx, ok := any(ctx).(*cue.Runtime); ok { (*runtime.Runtime)(ctx).Init() @@ -52,7 +48,7 @@ func Make(ctx *adt.OpContext, v adt.Value) cue.Value { // UnifyBuiltin returns the given Value unified with the given builtin template. func UnifyBuiltin(v cue.Value, kind string) cue.Value { pkg, name, _ := strings.Cut(kind, ".") - s := runtime.SharedRuntime.LoadImport(pkg) + s := runtime.SharedRuntime().LoadImport(pkg) if s == nil { return v } diff --git a/vendor/cuelang.org/go/mod/modcache/cache.go b/vendor/cuelang.org/go/mod/modcache/cache.go index c6dd1178e2..1723418da4 100644 --- a/vendor/cuelang.org/go/mod/modcache/cache.go +++ b/vendor/cuelang.org/go/mod/modcache/cache.go @@ -92,7 +92,7 @@ func (c *cache) writeDiskCache(ctx context.Context, file string, data []byte) er // downloadDir returns the directory for storing. // An error will be returned if the module path or version cannot be escaped. -// An error satisfying errors.Is(err, fs.ErrNotExist) will be returned +// An error satisfying [errors.Is](err, [fs.ErrNotExist]) will be returned // along with the directory if the directory does not exist or if the directory // is not completely populated. func (c *cache) downloadDir(m module.Version) (string, error) { diff --git a/vendor/cuelang.org/go/mod/modfile/modfile.go b/vendor/cuelang.org/go/mod/modfile/modfile.go index a1e9529682..3f1a5dff65 100644 --- a/vendor/cuelang.org/go/mod/modfile/modfile.go +++ b/vendor/cuelang.org/go/mod/modfile/modfile.go @@ -156,7 +156,7 @@ func (f *File) Format() ([]byte, error) { // before formatting the output. f1, err := ParseNonStrict(data, "-") if err != nil { - return nil, fmt.Errorf("cannot round-trip module file: %v", strings.TrimSuffix(errors.Details(err, nil), "\n")) + return nil, fmt.Errorf("cannot parse result: %v", strings.TrimSuffix(errors.Details(err, nil), "\n")) } if f.Language != nil && f1.actualSchemaVersion == "v0.0.0" { // It's not a legacy module file (because the language field is present) @@ -232,30 +232,20 @@ func lookup(v cue.Value, sels ...cue.Selector) cue.Value { // should be at least this, because that's when we added the language.version // field itself. func EarliestClosedSchemaVersion() string { - return schemaVersionLimits()[0] + return earliestClosedSchemaVersion() } -// LatestKnownSchemaVersion returns the language version -// associated with the most recent known schema. -func LatestKnownSchemaVersion() string { - return schemaVersionLimits()[1] -} - -var schemaVersionLimits = sync.OnceValue(func() [2]string { - limits, _ := moduleSchemaDo(func(info *schemaInfo) ([2]string, error) { +var earliestClosedSchemaVersion = sync.OnceValue(func() string { + earliest, _ := moduleSchemaDo(func(info *schemaInfo) (string, error) { earliest := "" - latest := "" for v := range info.Versions { if earliest == "" || semver.Compare(v, earliest) < 0 { earliest = v } - if latest == "" || semver.Compare(v, latest) > 0 { - latest = v - } } - return [2]string{earliest, latest}, nil + return earliest, nil }) - return limits + return earliest }) // Parse verifies that the module file has correct syntax @@ -351,7 +341,12 @@ func FixLegacy(modfile []byte, filename string) (*File, error) { f = &File{ Module: mpath, Language: &Language{ - Version: cueversion.LanguageVersion(), + // If there's a legacy module file, the CUE code + // is unlikely to be using new language features, + // so keep the language version fixed rather than + // using [cueversion.LanguageVersion]. + // See https://cuelang.org/issue/3222. + Version: "v0.9.0", }, Custom: custom, } @@ -364,7 +359,7 @@ func FixLegacy(modfile []byte, filename string) (*File, error) { } f, err = ParseNonStrict(data, "fixed-"+filename) if err != nil { - return nil, fmt.Errorf("cannot round-trip fixed module file %q: %v", data, err) + return nil, fmt.Errorf("cannot parse resulting module file %q: %v", data, err) } return f, nil } diff --git a/vendor/cuelang.org/go/mod/modregistry/client.go b/vendor/cuelang.org/go/mod/modregistry/client.go index c3cc9e153f..e34fc03d8e 100644 --- a/vendor/cuelang.org/go/mod/modregistry/client.go +++ b/vendor/cuelang.org/go/mod/modregistry/client.go @@ -31,6 +31,7 @@ import ( "strings" "cuelabs.dev/go/oci/ociregistry" + "cuelabs.dev/go/oci/ociregistry/ociref" "cuelang.org/go/internal/mod/semver" digest "github.com/opencontainers/go-digest" specs "github.com/opencontainers/image-spec/specs-go" @@ -106,7 +107,7 @@ func NewClientWithResolver(resolver Resolver) *Client { } // GetModule returns the module instance for the given version. -// It returns an error that satisfies errors.Is(ErrNotFound) if the +// It returns an error that satisfies [errors.Is]([ErrNotFound]) if the // module is not present in the store at this version. func (c *Client) GetModule(ctx context.Context, m module.Version) (*Module, error) { loc, err := c.resolve(m) @@ -173,7 +174,7 @@ func (c *Client) GetModuleWithManifest(m module.Version, contents []byte, mediaT // sorted in semver order. // If m has a major version suffix, only versions with that major version will // be returned. -func (c *Client) ModuleVersions(ctx context.Context, m string) ([]string, error) { +func (c *Client) ModuleVersions(ctx context.Context, m string) (_req []string, _err0 error) { mpath, major, hasMajor := module.SplitPathVersion(m) if !hasMajor { mpath = m @@ -186,6 +187,12 @@ func (c *Client) ModuleVersions(ctx context.Context, m string) ([]string, error) return nil, err } versions := []string{} + if !ociref.IsValidRepository(loc.Repository) { + // If it's not a valid repository, it can't be used in an OCI + // request, so return an empty slice rather than the + // "invalid OCI request" error that a registry can return. + return nil, nil + } // Note: do not use c.repoName because that always expects // a module path with a major version. iter := loc.Registry.Tags(ctx, loc.Repository, "") diff --git a/vendor/cuelang.org/go/mod/module/dirfs.go b/vendor/cuelang.org/go/mod/module/dirfs.go index 42cbbbd139..bcc3127e2d 100644 --- a/vendor/cuelang.org/go/mod/module/dirfs.go +++ b/vendor/cuelang.org/go/mod/module/dirfs.go @@ -3,6 +3,8 @@ package module import ( "io/fs" "os" + + "cuelang.org/go/cue/ast" ) // SourceLoc represents the location of some CUE source code. @@ -13,6 +15,20 @@ type SourceLoc struct { Dir string } +// ReadCUE can be implemented by an [fs.FS] +// to provide an optimized (cached) way of +// reading and parsing CUE syntax. +type ReadCUEFS interface { + fs.FS + + // ReadCUEFile reads CUE syntax from the given path. + // + // If this method is implemented, but the implementation + // does not support reading CUE files, + // it should return [errors.ErrUnsupported]. + ReadCUEFile(path string) (*ast.File, error) +} + // OSRootFS can be implemented by an [fs.FS] // implementation to return its root directory as // an OS file path. diff --git a/vendor/cuelang.org/go/mod/module/path.go b/vendor/cuelang.org/go/mod/module/path.go index d6e6865231..65eae6cf58 100644 --- a/vendor/cuelang.org/go/mod/module/path.go +++ b/vendor/cuelang.org/go/mod/module/path.go @@ -5,6 +5,7 @@ import ( "fmt" "regexp" "strings" + "sync" "unicode" "unicode/utf8" @@ -15,8 +16,12 @@ import ( // The following regular expressions come from https://github.com/opencontainers/distribution-spec/blob/main/spec.md#pulling-manifests // and ensure that we can store modules inside OCI registries. var ( - basePathPat = regexp.MustCompile(`^[a-z0-9]+((\.|_|__|-+)[a-z0-9]+)*(/[a-z0-9]+((\.|_|__|-+)[a-z0-9]+)*)*$`) - tagPat = regexp.MustCompile(`^[a-zA-Z0-9_][a-zA-Z0-9._-]{0,127}$`) + basePathPat = sync.OnceValue(func() *regexp.Regexp { + return regexp.MustCompile(`^[a-z0-9]+((\.|_|__|-+)[a-z0-9]+)*(/[a-z0-9]+((\.|_|__|-+)[a-z0-9]+)*)*$`) + }) + tagPat = sync.OnceValue(func() *regexp.Regexp { + return regexp.MustCompile(`^[a-zA-Z0-9_][a-zA-Z0-9._-]{0,127}$`) + }) ) // Check checks that a given module path, version pair is valid. @@ -53,18 +58,10 @@ func firstPathOK(r rune) bool { // modPathOK reports whether r can appear in a module path element. // Paths can be ASCII letters, ASCII digits, and limited ASCII punctuation: - . _ and ~. -// -// This matches what "go get" has historically recognized in import paths, -// and avoids confusing sequences like '%20' or '+' that would change meaning -// if used in a URL. -// -// TODO(rsc): We would like to allow Unicode letters, but that requires additional -// care in the safe encoding (see "escaped paths" above). func modPathOK(r rune) bool { if r < utf8.RuneSelf { - return r == '-' || r == '.' || r == '_' || r == '~' || + return r == '-' || r == '.' || r == '_' || '0' <= r && r <= '9' || - 'A' <= r && r <= 'Z' || 'a' <= r && r <= 'z' } return false @@ -78,7 +75,10 @@ func modPathOK(r rune) bool { // otherwise-unambiguous on the command line and historically used for some // binary names (such as '++' as a suffix for compiler binaries and wrappers). func importPathOK(r rune) bool { - return modPathOK(r) || r == '+' + return modPathOK(r) || + r == '+' || + r == '~' || + 'A' <= r && r <= 'Z' } // fileNameOK reports whether r can appear in a file name. @@ -133,8 +133,8 @@ func CheckPathWithoutVersion(basePath string) (err error) { } } // Sanity check agreement with OCI specs. - if !basePathPat.MatchString(basePath) { - return fmt.Errorf("non-conforming path %q", basePath) + if !basePathPat().MatchString(basePath) { + return fmt.Errorf("path does not conform to OCI repository name restrictions; see https://github.com/opencontainers/distribution-spec/blob/HEAD/spec.md#pulling-manifests") } return nil } @@ -148,9 +148,11 @@ func CheckPathWithoutVersion(basePath string) (err error) { // ASCII digits, dots (U+002E), and dashes (U+002D); // it must contain at least one dot and cannot start with a dash. // -// Second, there must be a final major version of the form +// Second, there may be a final major version of the form // @vN where N looks numeric // (ASCII digits) and must not begin with a leading zero. +// Without such a major version, the major version is assumed +// to be v0. // // Third, no path element may begin with a dot. func CheckPath(mpath string) (err error) { @@ -164,18 +166,19 @@ func CheckPath(mpath string) (err error) { }() basePath, vers, ok := SplitPathVersion(mpath) - if !ok { - return fmt.Errorf("no major version found in module path") - } - if semver.Major(vers) != vers { - return fmt.Errorf("path can contain major version only") + if ok { + if semver.Major(vers) != vers { + return fmt.Errorf("path can contain major version only") + } + if !tagPat().MatchString(vers) { + return fmt.Errorf("non-conforming version %q", vers) + } + } else { + basePath = mpath } if err := CheckPathWithoutVersion(basePath); err != nil { return err } - if !tagPat.MatchString(vers) { - return fmt.Errorf("non-conforming version %q", vers) - } return nil } @@ -264,10 +267,16 @@ func checkElem(elem string, kind pathKind) error { if strings.Count(elem, ".") == len(elem) { return fmt.Errorf("invalid path element %q", elem) } - if elem[0] == '.' && kind == modulePath { - return fmt.Errorf("leading dot in path element") - } - if elem[len(elem)-1] == '.' { + + if kind == modulePath { + + if r := rune(elem[0]); r == '.' || r == '_' || r == '-' { + return fmt.Errorf("leading %q in path element", r) + } + if r := rune(elem[len(elem)-1]); r == '.' || r == '_' || r == '-' { + return fmt.Errorf("trailing %q in path element", r) + } + } else if elem[len(elem)-1] == '.' { return fmt.Errorf("trailing dot in path element") } for _, r := range elem { @@ -482,7 +491,7 @@ func ParseImportPath(p string) ImportPath { } else { parts.Qualifier = parts.Path } - if !ast.IsValidIdent(parts.Qualifier) || strings.HasPrefix(parts.Qualifier, "#") { + if !ast.IsValidIdent(parts.Qualifier) || strings.HasPrefix(parts.Qualifier, "#") || parts.Qualifier == "_" { parts.Qualifier = "" } } diff --git a/vendor/cuelang.org/go/mod/modzip/zip.go b/vendor/cuelang.org/go/mod/modzip/zip.go index 4736a6310f..0ee2f18be2 100644 --- a/vendor/cuelang.org/go/mod/modzip/zip.go +++ b/vendor/cuelang.org/go/mod/modzip/zip.go @@ -841,7 +841,7 @@ func (e *zipError) Unwrap() error { func strToFold(s string) string { // Fast path: all ASCII, no upper case. // Most paths look like this already. - for i := 0; i < len(s); i++ { + for i := range len(s) { c := s[i] if c >= utf8.RuneSelf || 'A' <= c && c <= 'Z' { goto Slow diff --git a/vendor/cuelang.org/go/pkg/encoding/json/manual.go b/vendor/cuelang.org/go/pkg/encoding/json/manual.go index b78b3dd41b..b0440831b9 100644 --- a/vendor/cuelang.org/go/pkg/encoding/json/manual.go +++ b/vendor/cuelang.org/go/pkg/encoding/json/manual.go @@ -28,6 +28,7 @@ import ( "cuelang.org/go/cue/token" cuejson "cuelang.org/go/encoding/json" internaljson "cuelang.org/go/internal/encoding/json" + "cuelang.org/go/internal/pkg" ) // Compact generates the JSON-encoded src with insignificant space characters @@ -97,8 +98,7 @@ func MarshalStream(v cue.Value) (string, error) { // UnmarshalStream parses the JSON to a CUE instance. func UnmarshalStream(data []byte) (ast.Expr, error) { - var r cue.Runtime - d := cuejson.NewDecoder(&r, "", bytes.NewReader(data)) + d := cuejson.NewDecoder(nil, "", bytes.NewReader(data)) a := []ast.Expr{} for { @@ -130,7 +130,7 @@ func Unmarshal(b []byte) (ast.Expr, error) { // Validate validates JSON and confirms it matches the constraints // specified by v. -func Validate(b []byte, v cue.Value) (bool, error) { +func Validate(b []byte, v pkg.Schema) (bool, error) { err := cuejson.Validate(b, v) if err != nil { return false, err diff --git a/vendor/cuelang.org/go/pkg/encoding/json/pkg.go b/vendor/cuelang.org/go/pkg/encoding/json/pkg.go index dce3ef731c..189709db18 100644 --- a/vendor/cuelang.org/go/pkg/encoding/json/pkg.go +++ b/vendor/cuelang.org/go/pkg/encoding/json/pkg.go @@ -118,9 +118,10 @@ var p = &pkg.Package{ {Kind: adt.BytesKind | adt.StringKind}, {Kind: adt.TopKind}, }, - Result: adt.BoolKind, + Result: adt.BoolKind, + NonConcrete: true, Func: func(c *pkg.CallCtxt) { - b, v := c.Bytes(0), c.Value(1) + b, v := c.Bytes(0), c.Schema(1) if c.Do() { c.Ret, c.Err = Validate(b, v) } diff --git a/vendor/cuelang.org/go/pkg/encoding/toml/manual.go b/vendor/cuelang.org/go/pkg/encoding/toml/manual.go new file mode 100644 index 0000000000..1dda44a3db --- /dev/null +++ b/vendor/cuelang.org/go/pkg/encoding/toml/manual.go @@ -0,0 +1,43 @@ +// Copyright 2024 The CUE Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package toml + +import ( + "bytes" + "strings" + + "cuelang.org/go/cue" + "cuelang.org/go/cue/ast" + "cuelang.org/go/encoding/toml" +) + +// Marshal returns the TOML encoding of v. +func Marshal(v cue.Value) (string, error) { + if err := v.Validate(cue.Concrete(true)); err != nil { + return "", err + } + var b strings.Builder + if err := toml.NewEncoder(&b).Encode(v); err != nil { + return "", err + } + return b.String(), nil +} + +// Unmarshal parses the TOML to a CUE expression. +func Unmarshal(data []byte) (ast.Expr, error) { + return toml.NewDecoder("", bytes.NewReader(data)).Decode() +} + +// TODO(mvdan): add Validate too, but which semantics? encoding/json and encoding/yaml do not seem to agree. diff --git a/vendor/cuelang.org/go/pkg/encoding/toml/pkg.go b/vendor/cuelang.org/go/pkg/encoding/toml/pkg.go new file mode 100644 index 0000000000..93a2fdfddf --- /dev/null +++ b/vendor/cuelang.org/go/pkg/encoding/toml/pkg.go @@ -0,0 +1,42 @@ +// Code generated by cuelang.org/go/pkg/gen. DO NOT EDIT. + +package toml + +import ( + "cuelang.org/go/internal/core/adt" + "cuelang.org/go/internal/pkg" +) + +func init() { + pkg.Register("encoding/toml", p) +} + +var _ = adt.TopKind // in case the adt package isn't used + +var p = &pkg.Package{ + Native: []*pkg.Builtin{{ + Name: "Marshal", + Params: []pkg.Param{ + {Kind: adt.TopKind}, + }, + Result: adt.StringKind, + Func: func(c *pkg.CallCtxt) { + v := c.Value(0) + if c.Do() { + c.Ret, c.Err = Marshal(v) + } + }, + }, { + Name: "Unmarshal", + Params: []pkg.Param{ + {Kind: adt.BytesKind | adt.StringKind}, + }, + Result: adt.TopKind, + Func: func(c *pkg.CallCtxt) { + data := c.Bytes(0) + if c.Do() { + c.Ret, c.Err = Unmarshal(data) + } + }, + }}, +} diff --git a/vendor/cuelang.org/go/pkg/encoding/yaml/manual.go b/vendor/cuelang.org/go/pkg/encoding/yaml/manual.go index c65c3621eb..b8744c3e4a 100644 --- a/vendor/cuelang.org/go/pkg/encoding/yaml/manual.go +++ b/vendor/cuelang.org/go/pkg/encoding/yaml/manual.go @@ -84,9 +84,9 @@ func UnmarshalStream(data []byte) (ast.Expr, error) { return ast.NewList(a...), nil } -// Validate validates YAML and confirms it is an instance of the schema -// specified by v. If the YAML source is a stream, every object must match v. -func Validate(b []byte, v cue.Value) (bool, error) { +// Validate validates YAML and confirms it is an instance of schema. +// If the YAML source is a stream, every object must match v. +func Validate(b []byte, v pkg.Schema) (bool, error) { d := cueyaml.NewDecoder("yaml.Validate", b) r := v.Context() for { @@ -132,7 +132,7 @@ func Validate(b []byte, v cue.Value) (bool, error) { // specified by v using unification. This means that b must be consistent with, // but does not have to be an instance of v. If the YAML source is a stream, // every object must match v. -func ValidatePartial(b []byte, v cue.Value) (bool, error) { +func ValidatePartial(b []byte, v pkg.Schema) (bool, error) { d := cueyaml.NewDecoder("yaml.ValidatePartial", b) r := v.Context() for { diff --git a/vendor/cuelang.org/go/pkg/encoding/yaml/pkg.go b/vendor/cuelang.org/go/pkg/encoding/yaml/pkg.go index 94ed4d5a04..d1a31f150f 100644 --- a/vendor/cuelang.org/go/pkg/encoding/yaml/pkg.go +++ b/vendor/cuelang.org/go/pkg/encoding/yaml/pkg.go @@ -68,9 +68,10 @@ var p = &pkg.Package{ {Kind: adt.BytesKind | adt.StringKind}, {Kind: adt.TopKind}, }, - Result: adt.BoolKind, + Result: adt.BoolKind, + NonConcrete: true, Func: func(c *pkg.CallCtxt) { - b, v := c.Bytes(0), c.Value(1) + b, v := c.Bytes(0), c.Schema(1) if c.Do() { c.Ret, c.Err = Validate(b, v) } @@ -81,9 +82,10 @@ var p = &pkg.Package{ {Kind: adt.BytesKind | adt.StringKind}, {Kind: adt.TopKind}, }, - Result: adt.BoolKind, + Result: adt.BoolKind, + NonConcrete: true, Func: func(c *pkg.CallCtxt) { - b, v := c.Bytes(0), c.Value(1) + b, v := c.Bytes(0), c.Schema(1) if c.Do() { c.Ret, c.Err = ValidatePartial(b, v) } diff --git a/vendor/cuelang.org/go/pkg/list/list.go b/vendor/cuelang.org/go/pkg/list/list.go index 5bf55fbafc..cf59be33c4 100644 --- a/vendor/cuelang.org/go/pkg/list/list.go +++ b/vendor/cuelang.org/go/pkg/list/list.go @@ -17,13 +17,15 @@ package list import ( "fmt" - "sort" + "slices" "cuelang.org/go/cue" "cuelang.org/go/cue/errors" "cuelang.org/go/cue/token" "cuelang.org/go/internal/core/adt" "cuelang.org/go/internal/pkg" + "cuelang.org/go/internal/types" + "cuelang.org/go/internal/value" ) // Drop reports the suffix of list x after the first n elements, @@ -139,7 +141,7 @@ func Repeat(x []cue.Value, count int) ([]cue.Value, error) { return nil, fmt.Errorf("negative count") } var a []cue.Value - for i := 0; i < count; i++ { + for range count { a = append(a, x...) } return a, nil @@ -215,6 +217,20 @@ func Slice(x []cue.Value, i, j int) ([]cue.Value, error) { return x[i:j], nil } +// Reverse reverses a list. +// +// For instance: +// +// Reverse([1, 2, 3, 4]) +// +// results in +// +// [4, 3, 2, 1] +func Reverse(x []cue.Value) []cue.Value { + slices.Reverse(x) + return x +} + // MinItems reports whether a has at least n items. func MinItems(list pkg.List, n int) (bool, error) { count := len(list.Elems()) @@ -245,18 +261,58 @@ func MaxItems(list pkg.List, n int) (bool, error) { } // UniqueItems reports whether all elements in the list are unique. -func UniqueItems(a []cue.Value) bool { - b := []string{} - for _, v := range a { - b = append(b, fmt.Sprintf("%+v", v)) +func UniqueItems(a []cue.Value) (bool, error) { + if len(a) <= 1 { + return true, nil } - sort.Strings(b) - for i := 1; i < len(b); i++ { - if b[i-1] == b[i] { - return false + + // TODO(perf): this is an O(n^2) algorithm. We should make it O(n log n). + // This could be done as follows: + // - Create a list with some hash value for each element x in a as well + // alongside the value of x itself. + // - Sort the elements based on the hash value. + // - Compare subsequent elements to see if they are equal. + + var tv types.Value + a[0].Core(&tv) + ctx := adt.NewContext(tv.R, tv.V) + + posX, posY := 0, 0 + code := adt.IncompleteError + +outer: + for i, x := range a { + _, vx := value.ToInternal(x) + + for j := i + 1; j < len(a); j++ { + _, vy := value.ToInternal(a[j]) + + if adt.Equal(ctx, vx, vy, adt.RegularOnly) { + posX, posY = i, j + if adt.IsFinal(vy) { + code = adt.EvalError + break outer + } + } } } - return true + + if posX == posY { + return true, nil + } + + var err errors.Error + switch x := a[posX].Value(); x.Kind() { + case cue.BoolKind, cue.NullKind, cue.IntKind, cue.FloatKind, cue.StringKind, cue.BytesKind: + err = errors.Newf(token.NoPos, "equal value (%v) at position %d and %d", x, posX, posY) + default: + err = errors.Newf(token.NoPos, "equal values at position %d and %d", posX, posY) + } + + return false, pkg.ValidationError{B: &adt.Bottom{ + Code: code, + Err: err, + }} } // Contains reports whether v is contained in a. The value must be a @@ -269,3 +325,33 @@ func Contains(a []cue.Value, v cue.Value) bool { } return false } + +// MatchN is a validator that checks that the number of elements in the given +// list that unifies with the schema "matchValue" matches "n". +// "n" may be a number constraint and does not have to be a concrete number. +// Likewise, "matchValue" will usually be a non-concrete value. +func MatchN(list []cue.Value, n pkg.Schema, matchValue pkg.Schema) (bool, error) { + var nmatch int64 + for _, w := range list { + if matchValue.Unify(w).Validate(cue.Final()) == nil { + nmatch++ + } + } + + r, _ := value.ToInternal(n) + ctx := (*cue.Context)(r) + + if err := n.Unify(ctx.Encode(nmatch)).Err(); err != nil { + return false, pkg.ValidationError{B: &adt.Bottom{ + Code: adt.EvalError, + Err: errors.Newf( + token.NoPos, + "number of matched elements is %d: does not satisfy %v", + nmatch, + n, + ), + }} + } + + return true, nil +} diff --git a/vendor/cuelang.org/go/pkg/list/pkg.go b/vendor/cuelang.org/go/pkg/list/pkg.go index 3001cc8e85..b58dc3a487 100644 --- a/vendor/cuelang.org/go/pkg/list/pkg.go +++ b/vendor/cuelang.org/go/pkg/list/pkg.go @@ -92,6 +92,18 @@ var p = &pkg.Package{ c.Ret, c.Err = Slice(x, i, j) } }, + }, { + Name: "Reverse", + Params: []pkg.Param{ + {Kind: adt.ListKind}, + }, + Result: adt.ListKind, + Func: func(c *pkg.CallCtxt) { + x := c.List(0) + if c.Do() { + c.Ret = Reverse(x) + } + }, }, { Name: "MinItems", Params: []pkg.Param{ @@ -127,7 +139,7 @@ var p = &pkg.Package{ Func: func(c *pkg.CallCtxt) { a := c.List(0) if c.Do() { - c.Ret = UniqueItems(a) + c.Ret, c.Err = UniqueItems(a) } }, }, { @@ -143,12 +155,27 @@ var p = &pkg.Package{ c.Ret = Contains(a, v) } }, + }, { + Name: "MatchN", + Params: []pkg.Param{ + {Kind: adt.ListKind}, + {Kind: adt.TopKind}, + {Kind: adt.TopKind}, + }, + Result: adt.BoolKind, + NonConcrete: true, + Func: func(c *pkg.CallCtxt) { + list, n, matchValue := c.List(0), c.Schema(1), c.Schema(2) + if c.Do() { + c.Ret, c.Err = MatchN(list, n, matchValue) + } + }, }, { Name: "Avg", Params: []pkg.Param{ {Kind: adt.ListKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { xs := c.DecimalList(0) if c.Do() { @@ -160,7 +187,7 @@ var p = &pkg.Package{ Params: []pkg.Param{ {Kind: adt.ListKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { xs := c.DecimalList(0) if c.Do() { @@ -172,7 +199,7 @@ var p = &pkg.Package{ Params: []pkg.Param{ {Kind: adt.ListKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { xs := c.DecimalList(0) if c.Do() { @@ -184,7 +211,7 @@ var p = &pkg.Package{ Params: []pkg.Param{ {Kind: adt.ListKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { xs := c.DecimalList(0) if c.Do() { @@ -194,9 +221,9 @@ var p = &pkg.Package{ }, { Name: "Range", Params: []pkg.Param{ - {Kind: adt.NumKind}, - {Kind: adt.NumKind}, - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, + {Kind: adt.NumberKind}, + {Kind: adt.NumberKind}, }, Result: adt.ListKind, Func: func(c *pkg.CallCtxt) { @@ -210,7 +237,7 @@ var p = &pkg.Package{ Params: []pkg.Param{ {Kind: adt.ListKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { xs := c.DecimalList(0) if c.Do() { diff --git a/vendor/cuelang.org/go/pkg/list/sort.go b/vendor/cuelang.org/go/pkg/list/sort.go index d47c4985ad..6c5e5310ce 100644 --- a/vendor/cuelang.org/go/pkg/list/sort.go +++ b/vendor/cuelang.org/go/pkg/list/sort.go @@ -19,6 +19,7 @@ package list import ( + "slices" "sort" "cuelang.org/go/cue" @@ -69,12 +70,8 @@ func (s *valueSorter) Less(i, j int) bool { saveX := *s.x saveY := *s.y - for _, c := range x.V.Conjuncts { - s.x.AddConjunct(c) - } - for _, c := range y.V.Conjuncts { - s.y.AddConjunct(c) - } + s.x.InsertConjunctsFrom(x.V) + s.y.InsertConjunctsFrom(y.V) // TODO(perf): if we can determine that the comparator values for // x and y are idempotent (no arcs and a basevalue being top or @@ -121,12 +118,8 @@ func (s *valueSorter) lessNew(i, j int) bool { s.a[i].Core(&x) s.a[j].Core(&y) - for _, c := range x.V.Conjuncts { - xa.AddConjunct(c) - } - for _, c := range y.V.Conjuncts { - ya.AddConjunct(c) - } + xa.InsertConjunctsFrom(x.V) + ya.InsertConjunctsFrom(y.V) // TODO(perf): if we can determine that the comparator values for // x and y are idempotent (no arcs and a basevalue being top or @@ -218,9 +211,9 @@ func SortStable(list []cue.Value, cmp cue.Value) (sorted []cue.Value, err error) return s.ret() } -// Strings sorts a list of strings in increasing order. +// SortStrings sorts a list of strings in increasing order. func SortStrings(a []string) []string { - sort.Strings(a) + slices.Sort(a) return a } @@ -234,5 +227,5 @@ func IsSorted(list []cue.Value, cmp cue.Value) bool { // IsSortedStrings tests whether a list is a sorted lists of strings. func IsSortedStrings(a []string) bool { - return sort.StringsAreSorted(a) + return slices.IsSorted(a) } diff --git a/vendor/cuelang.org/go/pkg/math/pkg.go b/vendor/cuelang.org/go/pkg/math/pkg.go index da6b452088..0eca592139 100644 --- a/vendor/cuelang.org/go/pkg/math/pkg.go +++ b/vendor/cuelang.org/go/pkg/math/pkg.go @@ -69,7 +69,7 @@ var p = &pkg.Package{ }, { Name: "Floor", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, Result: adt.IntKind, Func: func(c *pkg.CallCtxt) { @@ -81,7 +81,7 @@ var p = &pkg.Package{ }, { Name: "Ceil", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, Result: adt.IntKind, Func: func(c *pkg.CallCtxt) { @@ -93,7 +93,7 @@ var p = &pkg.Package{ }, { Name: "Trunc", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, Result: adt.IntKind, Func: func(c *pkg.CallCtxt) { @@ -105,7 +105,7 @@ var p = &pkg.Package{ }, { Name: "Round", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, Result: adt.IntKind, Func: func(c *pkg.CallCtxt) { @@ -117,7 +117,7 @@ var p = &pkg.Package{ }, { Name: "RoundToEven", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, Result: adt.IntKind, Func: func(c *pkg.CallCtxt) { @@ -129,8 +129,8 @@ var p = &pkg.Package{ }, { Name: "MultipleOf", Params: []pkg.Param{ - {Kind: adt.NumKind}, - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, + {Kind: adt.NumberKind}, }, Result: adt.BoolKind, Func: func(c *pkg.CallCtxt) { @@ -142,9 +142,9 @@ var p = &pkg.Package{ }, { Name: "Abs", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Decimal(0) if c.Do() { @@ -154,9 +154,9 @@ var p = &pkg.Package{ }, { Name: "Acosh", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -166,9 +166,9 @@ var p = &pkg.Package{ }, { Name: "Asin", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -178,9 +178,9 @@ var p = &pkg.Package{ }, { Name: "Acos", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -190,9 +190,9 @@ var p = &pkg.Package{ }, { Name: "Asinh", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -202,9 +202,9 @@ var p = &pkg.Package{ }, { Name: "Atan", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -214,10 +214,10 @@ var p = &pkg.Package{ }, { Name: "Atan2", Params: []pkg.Param{ - {Kind: adt.NumKind}, - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { y, x := c.Float64(0), c.Float64(1) if c.Do() { @@ -227,9 +227,9 @@ var p = &pkg.Package{ }, { Name: "Atanh", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -239,9 +239,9 @@ var p = &pkg.Package{ }, { Name: "Cbrt", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Decimal(0) if c.Do() { @@ -284,10 +284,10 @@ var p = &pkg.Package{ }, { Name: "Copysign", Params: []pkg.Param{ - {Kind: adt.NumKind}, - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x, y := c.Decimal(0), c.Decimal(1) if c.Do() { @@ -297,10 +297,10 @@ var p = &pkg.Package{ }, { Name: "Dim", Params: []pkg.Param{ - {Kind: adt.NumKind}, - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x, y := c.Decimal(0), c.Decimal(1) if c.Do() { @@ -310,9 +310,9 @@ var p = &pkg.Package{ }, { Name: "Erf", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -322,9 +322,9 @@ var p = &pkg.Package{ }, { Name: "Erfc", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -334,9 +334,9 @@ var p = &pkg.Package{ }, { Name: "Erfinv", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -346,9 +346,9 @@ var p = &pkg.Package{ }, { Name: "Erfcinv", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -358,9 +358,9 @@ var p = &pkg.Package{ }, { Name: "Exp", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Decimal(0) if c.Do() { @@ -370,9 +370,9 @@ var p = &pkg.Package{ }, { Name: "Exp2", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Decimal(0) if c.Do() { @@ -382,9 +382,9 @@ var p = &pkg.Package{ }, { Name: "Expm1", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -394,9 +394,9 @@ var p = &pkg.Package{ }, { Name: "Gamma", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -406,10 +406,10 @@ var p = &pkg.Package{ }, { Name: "Hypot", Params: []pkg.Param{ - {Kind: adt.NumKind}, - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { p, q := c.Float64(0), c.Float64(1) if c.Do() { @@ -419,9 +419,9 @@ var p = &pkg.Package{ }, { Name: "J0", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -431,9 +431,9 @@ var p = &pkg.Package{ }, { Name: "Y0", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -443,9 +443,9 @@ var p = &pkg.Package{ }, { Name: "J1", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -455,9 +455,9 @@ var p = &pkg.Package{ }, { Name: "Y1", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -468,9 +468,9 @@ var p = &pkg.Package{ Name: "Jn", Params: []pkg.Param{ {Kind: adt.IntKind}, - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { n, x := c.Int(0), c.Float64(1) if c.Do() { @@ -481,9 +481,9 @@ var p = &pkg.Package{ Name: "Yn", Params: []pkg.Param{ {Kind: adt.IntKind}, - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { n, x := c.Int(0), c.Float64(1) if c.Do() { @@ -493,10 +493,10 @@ var p = &pkg.Package{ }, { Name: "Ldexp", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, {Kind: adt.IntKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { frac, exp := c.Float64(0), c.Int(1) if c.Do() { @@ -506,9 +506,9 @@ var p = &pkg.Package{ }, { Name: "Log", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Decimal(0) if c.Do() { @@ -518,9 +518,9 @@ var p = &pkg.Package{ }, { Name: "Log10", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Decimal(0) if c.Do() { @@ -530,9 +530,9 @@ var p = &pkg.Package{ }, { Name: "Log2", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Decimal(0) if c.Do() { @@ -542,9 +542,9 @@ var p = &pkg.Package{ }, { Name: "Log1p", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -554,9 +554,9 @@ var p = &pkg.Package{ }, { Name: "Logb", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -566,7 +566,7 @@ var p = &pkg.Package{ }, { Name: "Ilogb", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, Result: adt.IntKind, Func: func(c *pkg.CallCtxt) { @@ -578,10 +578,10 @@ var p = &pkg.Package{ }, { Name: "Mod", Params: []pkg.Param{ - {Kind: adt.NumKind}, - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x, y := c.Float64(0), c.Float64(1) if c.Do() { @@ -591,10 +591,10 @@ var p = &pkg.Package{ }, { Name: "Pow", Params: []pkg.Param{ - {Kind: adt.NumKind}, - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x, y := c.Decimal(0), c.Decimal(1) if c.Do() { @@ -606,7 +606,7 @@ var p = &pkg.Package{ Params: []pkg.Param{ {Kind: adt.IntKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { n := c.Int32(0) if c.Do() { @@ -616,10 +616,10 @@ var p = &pkg.Package{ }, { Name: "Remainder", Params: []pkg.Param{ - {Kind: adt.NumKind}, - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x, y := c.Float64(0), c.Float64(1) if c.Do() { @@ -629,7 +629,7 @@ var p = &pkg.Package{ }, { Name: "Signbit", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, Result: adt.BoolKind, Func: func(c *pkg.CallCtxt) { @@ -641,9 +641,9 @@ var p = &pkg.Package{ }, { Name: "Cos", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -653,9 +653,9 @@ var p = &pkg.Package{ }, { Name: "Sin", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -665,9 +665,9 @@ var p = &pkg.Package{ }, { Name: "Sinh", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -677,9 +677,9 @@ var p = &pkg.Package{ }, { Name: "Cosh", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -689,9 +689,9 @@ var p = &pkg.Package{ }, { Name: "Sqrt", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -701,9 +701,9 @@ var p = &pkg.Package{ }, { Name: "Tan", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { @@ -713,9 +713,9 @@ var p = &pkg.Package{ }, { Name: "Tanh", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { x := c.Float64(0) if c.Do() { diff --git a/vendor/cuelang.org/go/pkg/net/pkg.go b/vendor/cuelang.org/go/pkg/net/pkg.go index a1371998b9..568236636b 100644 --- a/vendor/cuelang.org/go/pkg/net/pkg.go +++ b/vendor/cuelang.org/go/pkg/net/pkg.go @@ -285,5 +285,29 @@ var p = &pkg.Package{ c.Ret, c.Err = QueryUnescape(s) } }, + }, { + Name: "URL", + Params: []pkg.Param{ + {Kind: adt.StringKind}, + }, + Result: adt.BoolKind, + Func: func(c *pkg.CallCtxt) { + s := c.String(0) + if c.Do() { + c.Ret, c.Err = URL(s) + } + }, + }, { + Name: "AbsURL", + Params: []pkg.Param{ + {Kind: adt.StringKind}, + }, + Result: adt.BoolKind, + Func: func(c *pkg.CallCtxt) { + s := c.String(0) + if c.Do() { + c.Ret, c.Err = AbsURL(s) + } + }, }}, } diff --git a/vendor/cuelang.org/go/pkg/net/url.go b/vendor/cuelang.org/go/pkg/net/url.go index da701b079a..5981a54d02 100644 --- a/vendor/cuelang.org/go/pkg/net/url.go +++ b/vendor/cuelang.org/go/pkg/net/url.go @@ -15,6 +15,7 @@ package net import ( + "errors" "net/url" ) @@ -48,3 +49,23 @@ func QueryEscape(s string) string { func QueryUnescape(s string) (string, error) { return url.QueryUnescape(s) } + +// URL validates that s is a valid relative or absolute URL. +// Note: this does also allow non-ASCII characters. +func URL(s string) (bool, error) { + _, err := url.Parse(s) + return err == nil, err +} + +// URL validates that s is an absolute URL. +// Note: this does also allow non-ASCII characters. +func AbsURL(s string) (bool, error) { + u, err := url.Parse(s) + if err != nil { + return false, err + } + if !u.IsAbs() { + return false, errors.New("URL is not absolute") + } + return true, nil +} diff --git a/vendor/cuelang.org/go/pkg/packages.txt b/vendor/cuelang.org/go/pkg/packages.txt deleted file mode 100644 index e46a4404e7..0000000000 --- a/vendor/cuelang.org/go/pkg/packages.txt +++ /dev/null @@ -1,31 +0,0 @@ -regexp -encoding/json -encoding/base64 -encoding/yaml -encoding/hex -encoding/csv -uuid -time -list -strings -path -math/bits -math -crypto/sha256 -crypto/ed25519 -crypto/sha512 -crypto/md5 -crypto/sha1 -crypto/hmac -tool -tool/os -tool/cli -tool/exec -tool/file -tool/http -struct -net -html -strconv -text/template -text/tabwriter diff --git a/vendor/cuelang.org/go/pkg/path/match.go b/vendor/cuelang.org/go/pkg/path/match.go index 7f371f7551..fe1a5d0a65 100644 --- a/vendor/cuelang.org/go/pkg/path/match.go +++ b/vendor/cuelang.org/go/pkg/path/match.go @@ -27,6 +27,8 @@ import ( // ErrBadPattern indicates a pattern was malformed. var ErrBadPattern = errors.New("syntax error in pattern") +var errStarStarDisallowed = errors.New("'**' is not supported in patterns as of yet") + // Match reports whether name matches the shell file name pattern. // The pattern syntax is: // @@ -51,13 +53,19 @@ var ErrBadPattern = errors.New("syntax error in pattern") // // On Windows, escaping is disabled. Instead, '\\' is treated as // path separator. +// +// A pattern may not contain '**', as a wildcard matching separator characters +// is not supported at this time. func Match(pattern, name string, o OS) (matched bool, err error) { os := getOS(o) Pattern: for len(pattern) > 0 { var star bool var chunk string - star, chunk, pattern = scanChunk(pattern, os) + star, chunk, pattern, err = scanChunk(pattern, os) + if err != nil { + return false, err + } if star && chunk == "" { // Trailing * matches rest of string unless it has a /. return !strings.Contains(name, string(os.Separator)), nil @@ -92,6 +100,14 @@ Pattern: } } } + // Before returning false with no error, + // check that the remainder of the pattern is syntactically valid. + for len(pattern) > 0 { + _, _, pattern, err = scanChunk(pattern, os) + if err != nil { + return false, err + } + } return false, nil } return len(name) == 0, nil @@ -99,10 +115,14 @@ Pattern: // scanChunk gets the next segment of pattern, which is a non-star string // possibly preceded by a star. -func scanChunk(pattern string, os os) (star bool, chunk, rest string) { - for len(pattern) > 0 && pattern[0] == '*' { +func scanChunk(pattern string, os os) (star bool, chunk, rest string, _ error) { + if len(pattern) > 0 && pattern[0] == '*' { pattern = pattern[1:] star = true + if len(pattern) > 0 && pattern[0] == '*' { + // ** is disallowed to allow for future functionality. + return false, "", "", errStarStarDisallowed + } } inrange := false var i int @@ -126,7 +146,7 @@ Scan: } } } - return star, pattern[0:i], pattern[i:] + return star, pattern[0:i], pattern[i:], nil } // matchChunk checks whether chunk matches the beginning of s. diff --git a/vendor/cuelang.org/go/pkg/path/os.go b/vendor/cuelang.org/go/pkg/path/os.go index 08592c3df3..f55193977d 100644 --- a/vendor/cuelang.org/go/pkg/path/os.go +++ b/vendor/cuelang.org/go/pkg/path/os.go @@ -14,7 +14,7 @@ package path -// OS must be a valid runtime.GOOS value or "unix". +// OS must be a valid [runtime.GOOS] value or "unix". type OS string const ( diff --git a/vendor/cuelang.org/go/pkg/register.go b/vendor/cuelang.org/go/pkg/register.go index e55734acf6..484507b58a 100644 --- a/vendor/cuelang.org/go/pkg/register.go +++ b/vendor/cuelang.org/go/pkg/register.go @@ -1,16 +1,4 @@ -// Copyright 2020 CUE Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Code generated by cuelang.org/go/pkg/gen. DO NOT EDIT. package pkg @@ -25,9 +13,9 @@ import ( _ "cuelang.org/go/pkg/encoding/csv" _ "cuelang.org/go/pkg/encoding/hex" _ "cuelang.org/go/pkg/encoding/json" + _ "cuelang.org/go/pkg/encoding/toml" _ "cuelang.org/go/pkg/encoding/yaml" _ "cuelang.org/go/pkg/html" - _ "cuelang.org/go/pkg/list" _ "cuelang.org/go/pkg/math" _ "cuelang.org/go/pkg/math/bits" diff --git a/vendor/cuelang.org/go/pkg/strconv/pkg.go b/vendor/cuelang.org/go/pkg/strconv/pkg.go index bdf4091f79..b698ead629 100644 --- a/vendor/cuelang.org/go/pkg/strconv/pkg.go +++ b/vendor/cuelang.org/go/pkg/strconv/pkg.go @@ -50,26 +50,13 @@ var p = &pkg.Package{ c.Ret = FormatBool(b) } }, - }, { - Name: "ParseComplex", - Params: []pkg.Param{ - {Kind: adt.StringKind}, - {Kind: adt.IntKind}, - }, - Result: adt.TopKind, - Func: func(c *pkg.CallCtxt) { - s, bitSize := c.String(0), c.Int(1) - if c.Do() { - c.Ret, c.Err = ParseComplex(s, bitSize) - } - }, }, { Name: "ParseFloat", Params: []pkg.Param{ {Kind: adt.StringKind}, {Kind: adt.IntKind}, }, - Result: adt.NumKind, + Result: adt.NumberKind, Func: func(c *pkg.CallCtxt) { s, bitSize := c.String(0), c.Int(1) if c.Do() { @@ -122,7 +109,7 @@ var p = &pkg.Package{ }, { Name: "FormatFloat", Params: []pkg.Param{ - {Kind: adt.NumKind}, + {Kind: adt.NumberKind}, {Kind: adt.IntKind}, {Kind: adt.IntKind}, {Kind: adt.IntKind}, diff --git a/vendor/cuelang.org/go/pkg/strconv/strconv.go b/vendor/cuelang.org/go/pkg/strconv/strconv.go index be2fe5bd3f..3ebb68e492 100644 --- a/vendor/cuelang.org/go/pkg/strconv/strconv.go +++ b/vendor/cuelang.org/go/pkg/strconv/strconv.go @@ -37,30 +37,6 @@ func FormatBool(b bool) string { return strconv.FormatBool(b) } -// ParseComplex converts the string s to a complex number -// with the precision specified by bitSize: 64 for complex64, or 128 for complex128. -// When bitSize=64, the result still has type complex128, but it will be -// convertible to complex64 without changing its value. -// -// The number represented by s must be of the form N, Ni, or N±Ni, where N stands -// for a floating-point number as recognized by ParseFloat, and i is the imaginary -// component. If the second N is unsigned, a + sign is required between the two components -// as indicated by the ±. If the second N is NaN, only a + sign is accepted. -// The form may be parenthesized and cannot contain any spaces. -// The resulting complex number consists of the two components converted by ParseFloat. -// -// The errors that ParseComplex returns have concrete type *NumError -// and include err.Num = s. -// -// If s is not syntactically well-formed, ParseComplex returns err.Err = ErrSyntax. -// -// If s is syntactically well-formed but either component is more than 1/2 ULP -// away from the largest floating point number of the given component's size, -// ParseComplex returns err.Err = ErrRange and c = ±Inf for the respective component. -func ParseComplex(s string, bitSize int) (complex128, error) { - return strconv.ParseComplex(s, bitSize) -} - // ParseFloat converts the string s to a floating-point number // with the precision specified by bitSize: 32 for float32, or 64 for float64. // When bitSize=32, the result still has type float64, but it will be diff --git a/vendor/cuelang.org/go/pkg/struct/struct.go b/vendor/cuelang.org/go/pkg/struct/struct.go index 39e2cda405..a568488860 100644 --- a/vendor/cuelang.org/go/pkg/struct/struct.go +++ b/vendor/cuelang.org/go/pkg/struct/struct.go @@ -30,7 +30,7 @@ import ( func MinFields(object pkg.Struct, n int) (bool, error) { count := object.Len() code := adt.EvalError - if object.IsOpen() { + if object.IsOpen() || count+object.NumConstraintFields() >= n { code = adt.IncompleteError } if count < n { diff --git a/vendor/cuelang.org/go/pkg/time/pkg.go b/vendor/cuelang.org/go/pkg/time/pkg.go index 80a3a17eff..6ed8ff7aa5 100644 --- a/vendor/cuelang.org/go/pkg/time/pkg.go +++ b/vendor/cuelang.org/go/pkg/time/pkg.go @@ -233,7 +233,7 @@ var p = &pkg.Package{ Params: []pkg.Param{ {Kind: adt.StringKind}, }, - Result: adt.TopKind, + Result: adt.StructKind, Func: func(c *pkg.CallCtxt) { t := c.String(0) if c.Do() { diff --git a/vendor/cuelang.org/go/pkg/tool/cli/cli.go b/vendor/cuelang.org/go/pkg/tool/cli/cli.go index 3efd7ab172..32f80bc962 100644 --- a/vendor/cuelang.org/go/pkg/tool/cli/cli.go +++ b/vendor/cuelang.org/go/pkg/tool/cli/cli.go @@ -94,12 +94,7 @@ func (c *askCmd) Run(ctx *task.Context) (res interface{}, err error) { switch v := ctx.Lookup("response"); v.IncompleteKind() { case cue.BoolKind: - switch strings.ToLower(response) { - case "yes": - update["response"] = true - default: - update["response"] = false - } + update["response"] = strings.ToLower(response) == "yes" case cue.StringKind: // already set above } diff --git a/vendor/cuelang.org/go/pkg/tool/exec/exec.cue b/vendor/cuelang.org/go/pkg/tool/exec/exec.cue index c98008371b..a4485c8ba2 100644 --- a/vendor/cuelang.org/go/pkg/tool/exec/exec.cue +++ b/vendor/cuelang.org/go/pkg/tool/exec/exec.cue @@ -14,11 +14,15 @@ package exec -// Run executes the given shell command. +// Run executes a program with the given arguments. Run: { $id: *"tool/exec.Run" | "exec" // exec for backwards compatibility - // cmd is the command to run. + // cmd is a non-empty list holding the program name to run + // and the arguments to be passed to it. + // + // Simple commands can use a string, which is split by white space characters. + // If any arguments include white space, or for clarity, use the list form. cmd: string | [string, ...string] // dir specifies the working directory of the command. diff --git a/vendor/cuelang.org/go/pkg/tool/exec/exec.go b/vendor/cuelang.org/go/pkg/tool/exec/exec.go index a596a8caa6..e8a0d743fd 100644 --- a/vendor/cuelang.org/go/pkg/tool/exec/exec.go +++ b/vendor/cuelang.org/go/pkg/tool/exec/exec.go @@ -101,45 +101,43 @@ func (c *execCmd) Run(ctx *task.Context) (res interface{}, err error) { return nil, fmt.Errorf("command %q failed: %v", doc, err) } -func mkCommand(ctx *task.Context) (c *exec.Cmd, doc string, err error) { - var bin string - var args []string - +// mkCommand builds an [exec.Cmd] from a CUE task value, +// also returning the full list of arguments as a string slice +// so that it can be used in error messages. +func mkCommand(ctx *task.Context) (c *exec.Cmd, doc []string, err error) { v := ctx.Lookup("cmd") if ctx.Err != nil { - return nil, "", ctx.Err + return nil, nil, ctx.Err } + var bin string + var args []string switch v.Kind() { case cue.StringKind: - str := ctx.String("cmd") - doc = str + str, _ := v.String() list := strings.Fields(str) - bin = list[0] - args = append(args, list[1:]...) + bin, args = list[0], list[1:] case cue.ListKind: list, _ := v.List() if !list.Next() { - return nil, "", errors.New("empty command list") + return nil, nil, errors.New("empty command list") } bin, err = list.Value().String() if err != nil { - return nil, "", err + return nil, nil, err } - doc += bin for list.Next() { str, err := list.Value().String() if err != nil { - return nil, "", err + return nil, nil, err } args = append(args, str) - doc += " " + str } } if bin == "" { - return nil, "", errors.New("empty command") + return nil, nil, errors.New("empty command") } cmd := exec.CommandContext(ctx.Context, bin, args...) @@ -153,7 +151,7 @@ func mkCommand(ctx *task.Context) (c *exec.Cmd, doc string, err error) { v, _ := iter.Value().Default() str, err := v.String() if err != nil { - return nil, "", errors.Wrapf(err, v.Pos(), + return nil, nil, errors.Wrapf(err, v.Pos(), "invalid environment variable value %q", v) } cmd.Env = append(cmd.Env, str) @@ -161,7 +159,7 @@ func mkCommand(ctx *task.Context) (c *exec.Cmd, doc string, err error) { // Struct case. for iter, _ := env.Fields(); iter.Next(); { - label := iter.Label() + label := iter.Selector().Unquoted() v, _ := iter.Value().Default() var str string switch v.Kind() { @@ -170,11 +168,11 @@ func mkCommand(ctx *task.Context) (c *exec.Cmd, doc string, err error) { case cue.IntKind, cue.FloatKind, cue.NumberKind: str = fmt.Sprint(v) default: - return nil, "", errors.Newf(v.Pos(), + return nil, nil, errors.Newf(v.Pos(), "invalid environment variable value %q", v) } cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", label, str)) } - return cmd, doc, nil + return cmd, append([]string{bin}, args...), nil } diff --git a/vendor/cuelang.org/go/pkg/tool/exec/pkg.go b/vendor/cuelang.org/go/pkg/tool/exec/pkg.go index c20f7299ab..0eb9fe9e95 100644 --- a/vendor/cuelang.org/go/pkg/tool/exec/pkg.go +++ b/vendor/cuelang.org/go/pkg/tool/exec/pkg.go @@ -4,11 +4,15 @@ // // These are the supported tasks: // -// // Run executes the given shell command. +// // Run executes a program with the given arguments. // Run: { // $id: *"tool/exec.Run" | "exec" // exec for backwards compatibility // -// // cmd is the command to run. +// // cmd is a non-empty list holding the program name to run +// // and the arguments to be passed to it. +// // +// // Simple commands can use a string, which is split by white space characters. +// // If any arguments include white space, or for clarity, use the list form. // cmd: string | [string, ...string] // // // dir specifies the working directory of the command. @@ -63,9 +67,7 @@ var p = &pkg.Package{ $id: *"tool/exec.Run" | "exec" cmd: string | [string, ...string] dir?: string - env: { - [string]: string - } | [...=~"="] + env: {[string]: string} | [...=~"="] stdout: *null | string | bytes stderr: *null | string | bytes stdin: *null | string | bytes diff --git a/vendor/cuelang.org/go/pkg/tool/file/file.cue b/vendor/cuelang.org/go/pkg/tool/file/file.cue index 7a00d9ff9b..9fe490faeb 100644 --- a/vendor/cuelang.org/go/pkg/tool/file/file.cue +++ b/vendor/cuelang.org/go/pkg/tool/file/file.cue @@ -89,7 +89,7 @@ Mkdir: { createParents: bool | *false // Directory mode and permission bits (before umask). - permissions: int | *0o755 + permissions: int | *0o777 } // MkdirAll creates a directory at the specified path along with any necessary diff --git a/vendor/cuelang.org/go/pkg/tool/file/file.go b/vendor/cuelang.org/go/pkg/tool/file/file.go index 3dbed397ab..a6b62689bb 100644 --- a/vendor/cuelang.org/go/pkg/tool/file/file.go +++ b/vendor/cuelang.org/go/pkg/tool/file/file.go @@ -17,10 +17,12 @@ package file import ( "os" "path/filepath" + "runtime" "cuelang.org/go/cue" "cuelang.org/go/cue/errors" "cuelang.org/go/internal/task" + pkgpath "cuelang.org/go/pkg/path" ) func init() { @@ -110,6 +112,16 @@ func (c *cmdGlob) Run(ctx *task.Context) (res interface{}, err error) { if ctx.Err != nil { return nil, ctx.Err } + // Validate that the glob pattern is valid per [pkgpath.Match]. + // Note that we use the current OS to match the semantics of [filepath.Glob], + // and since the APIs in this package are meant to support native paths. + os := pkgpath.Unix + if runtime.GOOS == "windows" { + os = pkgpath.Windows + } + if _, err := pkgpath.Match(glob, "", os); err != nil { + return nil, err + } m, err := filepath.Glob(glob) for i, s := range m { m[i] = filepath.ToSlash(s) diff --git a/vendor/cuelang.org/go/pkg/tool/file/pkg.go b/vendor/cuelang.org/go/pkg/tool/file/pkg.go index bc1b9f8364..2f522c57ff 100644 --- a/vendor/cuelang.org/go/pkg/tool/file/pkg.go +++ b/vendor/cuelang.org/go/pkg/tool/file/pkg.go @@ -79,7 +79,7 @@ // createParents: bool | *false // // // Directory mode and permission bits (before umask). -// permissions: int | *0o755 +// permissions: int | *0o777 // } // // // MkdirAll creates a directory at the specified path along with any necessary @@ -148,13 +148,13 @@ var p = &pkg.Package{ Append: { $id: "tool/file.Append" filename: !="" - permissions: int | *438 + permissions: int | *0o666 contents: bytes | string } Create: { $id: "tool/file.Create" filename: !="" - permissions: int | *438 + permissions: int | *0o666 contents: bytes | string } Glob: { @@ -166,7 +166,7 @@ var p = &pkg.Package{ $id: "tool/file.Mkdir" path: string createParents: bool | *false - permissions: int | *493 + permissions: int | *0o777 } MkdirAll: Mkdir & { createParents: true diff --git a/vendor/cuelang.org/go/pkg/tool/http/http.go b/vendor/cuelang.org/go/pkg/tool/http/http.go index 83e381e16c..192db32ae6 100644 --- a/vendor/cuelang.org/go/pkg/tool/http/http.go +++ b/vendor/cuelang.org/go/pkg/tool/http/http.go @@ -157,7 +157,7 @@ func parseHeaders(obj cue.Value, label string) (http.Header, error) { if err != nil { return nil, err } - h.Add(iter.Label(), str) + h.Add(iter.Selector().Unquoted(), str) } return h, nil } diff --git a/vendor/cuelang.org/go/pkg/tool/http/pkg.go b/vendor/cuelang.org/go/pkg/tool/http/pkg.go index dd231746b4..071b2e8917 100644 --- a/vendor/cuelang.org/go/pkg/tool/http/pkg.go +++ b/vendor/cuelang.org/go/pkg/tool/http/pkg.go @@ -65,18 +65,10 @@ var _ = adt.TopKind // in case the adt package isn't used var p = &pkg.Package{ Native: []*pkg.Builtin{}, CUE: `{ - Get: Do & { - method: "GET" - } - Post: Do & { - method: "POST" - } - Put: Do & { - method: "PUT" - } - Delete: Do & { - method: "DELETE" - } + Get: Do & {method: "GET"} + Post: Do & {method: "POST"} + Put: Do & {method: "PUT"} + Delete: Do & {method: "DELETE"} Do: { $id: *"tool/http.Do" | "http" method: string @@ -87,23 +79,15 @@ var p = &pkg.Package{ } request: { body?: bytes | string - header: { - [string]: string | [...string] - } - trailer: { - [string]: string | [...string] - } + header: [string]: string | [...string] + trailer: [string]: string | [...string] } response: { status: string statusCode: int body: *bytes | string - header: { - [string]: string | [...string] - } - trailer: { - [string]: string | [...string] - } + header: [string]: string | [...string] + trailer: [string]: string | [...string] } } }`, diff --git a/vendor/cuelang.org/go/pkg/tool/os/env.go b/vendor/cuelang.org/go/pkg/tool/os/env.go index 270ae3dc2a..12c72a5ce1 100644 --- a/vendor/cuelang.org/go/pkg/tool/os/env.go +++ b/vendor/cuelang.org/go/pkg/tool/os/env.go @@ -54,7 +54,7 @@ func (c *getenvCmd) Run(ctx *task.Context) (res interface{}, err error) { update := map[string]interface{}{} for iter.Next() { - name := iter.Label() + name := iter.Selector().Unquoted() if strings.HasPrefix(name, "$") { continue } @@ -110,7 +110,7 @@ func (c *environCmd) Run(ctx *task.Context) (res interface{}, err error) { } for iter.Next() { - name := iter.Label() + name := iter.Selector().Unquoted() if strings.HasPrefix(name, "$") { continue } diff --git a/vendor/cuelang.org/go/pkg/tool/os/pkg.go b/vendor/cuelang.org/go/pkg/tool/os/pkg.go index 268757ffdc..c38daadace 100644 --- a/vendor/cuelang.org/go/pkg/tool/os/pkg.go +++ b/vendor/cuelang.org/go/pkg/tool/os/pkg.go @@ -63,22 +63,16 @@ var p = &pkg.Package{ Value: bool | number | *string | null Name: !="" & !~"^[$]" Setenv: { - { - [Name]: Value - } $id: "tool/os.Setenv" + {[Name]: Value} } Getenv: { - { - [Name]: Value - } $id: "tool/os.Getenv" + {[Name]: Value} } Environ: { - { - [Name]: Value - } $id: "tool/os.Environ" + {[Name]: Value} } Clearenv: { $id: "tool/os.Clearenv" diff --git a/vendor/cuelang.org/go/pkg/uuid/pkg.go b/vendor/cuelang.org/go/pkg/uuid/pkg.go index e177ede4c2..70d1b23039 100644 --- a/vendor/cuelang.org/go/pkg/uuid/pkg.go +++ b/vendor/cuelang.org/go/pkg/uuid/pkg.go @@ -145,12 +145,10 @@ var p = &pkg.Package{ X500: "6ba7b814-9dad-11d1-80b4-00c04fd430c8" Nil: "00000000-0000-0000-0000-000000000000" } - variants: { - Invalid: 0 - RFC4122: 1 - Reserved: 2 - Microsoft: 3 - Future: 4 - } + variants: Invalid: 0 + variants: RFC4122: 1 + variants: Reserved: 2 + variants: Microsoft: 3 + variants: Future: 4 }`, } diff --git a/vendor/cuelang.org/go/pkg/uuid/uuid.go b/vendor/cuelang.org/go/pkg/uuid/uuid.go index 0adce9dc94..d164a5259c 100644 --- a/vendor/cuelang.org/go/pkg/uuid/uuid.go +++ b/vendor/cuelang.org/go/pkg/uuid/uuid.go @@ -18,22 +18,14 @@ package uuid import ( - "fmt" "math/big" - "regexp" "github.com/google/uuid" ) -var valid = regexp.MustCompile( - "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$") - -// Valid can be used to define a valid Valid. +// Valid ensures that s is a valid UUID which would be accepted by Parse. func Valid(s string) error { - if !valid.MatchString(string(s)) { - return fmt.Errorf("invalid UUID %q", s) - } - return nil + return uuid.Validate(s) } // Parse decodes s into a UUID or returns an error. Both the standard UUID forms @@ -46,6 +38,8 @@ func Parse(s string) (string, error) { return string(x.String()), err } +// TODO(mvdan): what is ToString meant to do? it appears like a no-op? + // String represents a 128-bit UUID value as a string. func ToString(x string) string { return string(x) diff --git a/vendor/filippo.io/edwards25519/README.md b/vendor/filippo.io/edwards25519/README.md deleted file mode 100644 index 24e2457d87..0000000000 --- a/vendor/filippo.io/edwards25519/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# filippo.io/edwards25519 - -``` -import "filippo.io/edwards25519" -``` - -This library implements the edwards25519 elliptic curve, exposing the necessary APIs to build a wide array of higher-level primitives. -Read the docs at [pkg.go.dev/filippo.io/edwards25519](https://pkg.go.dev/filippo.io/edwards25519). - -The code is originally derived from Adam Langley's internal implementation in the Go standard library, and includes George Tankersley's [performance improvements](https://golang.org/cl/71950). It was then further developed by Henry de Valence for use in ristretto255, and was finally [merged back into the Go standard library](https://golang.org/cl/276272) as of Go 1.17. It now tracks the upstream codebase and extends it with additional functionality. - -Most users don't need this package, and should instead use `crypto/ed25519` for signatures, `golang.org/x/crypto/curve25519` for Diffie-Hellman, or `github.com/gtank/ristretto255` for prime order group logic. However, for anyone currently using a fork of `crypto/internal/edwards25519`/`crypto/ed25519/internal/edwards25519` or `github.com/agl/edwards25519`, this package should be a safer, faster, and more powerful alternative. - -Since this package is meant to curb proliferation of edwards25519 implementations in the Go ecosystem, it welcomes requests for new APIs or reviewable performance improvements. diff --git a/vendor/filippo.io/edwards25519/doc.go b/vendor/filippo.io/edwards25519/doc.go deleted file mode 100644 index ab6aaebc0f..0000000000 --- a/vendor/filippo.io/edwards25519/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) 2021 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package edwards25519 implements group logic for the twisted Edwards curve -// -// -x^2 + y^2 = 1 + -(121665/121666)*x^2*y^2 -// -// This is better known as the Edwards curve equivalent to Curve25519, and is -// the curve used by the Ed25519 signature scheme. -// -// Most users don't need this package, and should instead use crypto/ed25519 for -// signatures, golang.org/x/crypto/curve25519 for Diffie-Hellman, or -// github.com/gtank/ristretto255 for prime order group logic. -// -// However, developers who do need to interact with low-level edwards25519 -// operations can use this package, which is an extended version of -// crypto/internal/edwards25519 from the standard library repackaged as -// an importable module. -package edwards25519 diff --git a/vendor/filippo.io/edwards25519/edwards25519.go b/vendor/filippo.io/edwards25519/edwards25519.go deleted file mode 100644 index a744da2c6d..0000000000 --- a/vendor/filippo.io/edwards25519/edwards25519.go +++ /dev/null @@ -1,427 +0,0 @@ -// Copyright (c) 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package edwards25519 - -import ( - "errors" - - "filippo.io/edwards25519/field" -) - -// Point types. - -type projP1xP1 struct { - X, Y, Z, T field.Element -} - -type projP2 struct { - X, Y, Z field.Element -} - -// Point represents a point on the edwards25519 curve. -// -// This type works similarly to math/big.Int, and all arguments and receivers -// are allowed to alias. -// -// The zero value is NOT valid, and it may be used only as a receiver. -type Point struct { - // Make the type not comparable (i.e. used with == or as a map key), as - // equivalent points can be represented by different Go values. - _ incomparable - - // The point is internally represented in extended coordinates (X, Y, Z, T) - // where x = X/Z, y = Y/Z, and xy = T/Z per https://eprint.iacr.org/2008/522. - x, y, z, t field.Element -} - -type incomparable [0]func() - -func checkInitialized(points ...*Point) { - for _, p := range points { - if p.x == (field.Element{}) && p.y == (field.Element{}) { - panic("edwards25519: use of uninitialized Point") - } - } -} - -type projCached struct { - YplusX, YminusX, Z, T2d field.Element -} - -type affineCached struct { - YplusX, YminusX, T2d field.Element -} - -// Constructors. - -func (v *projP2) Zero() *projP2 { - v.X.Zero() - v.Y.One() - v.Z.One() - return v -} - -// identity is the point at infinity. -var identity, _ = new(Point).SetBytes([]byte{ - 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) - -// NewIdentityPoint returns a new Point set to the identity. -func NewIdentityPoint() *Point { - return new(Point).Set(identity) -} - -// generator is the canonical curve basepoint. See TestGenerator for the -// correspondence of this encoding with the values in RFC 8032. -var generator, _ = new(Point).SetBytes([]byte{ - 0x58, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, - 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, - 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, - 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66}) - -// NewGeneratorPoint returns a new Point set to the canonical generator. -func NewGeneratorPoint() *Point { - return new(Point).Set(generator) -} - -func (v *projCached) Zero() *projCached { - v.YplusX.One() - v.YminusX.One() - v.Z.One() - v.T2d.Zero() - return v -} - -func (v *affineCached) Zero() *affineCached { - v.YplusX.One() - v.YminusX.One() - v.T2d.Zero() - return v -} - -// Assignments. - -// Set sets v = u, and returns v. -func (v *Point) Set(u *Point) *Point { - *v = *u - return v -} - -// Encoding. - -// Bytes returns the canonical 32-byte encoding of v, according to RFC 8032, -// Section 5.1.2. -func (v *Point) Bytes() []byte { - // This function is outlined to make the allocations inline in the caller - // rather than happen on the heap. - var buf [32]byte - return v.bytes(&buf) -} - -func (v *Point) bytes(buf *[32]byte) []byte { - checkInitialized(v) - - var zInv, x, y field.Element - zInv.Invert(&v.z) // zInv = 1 / Z - x.Multiply(&v.x, &zInv) // x = X / Z - y.Multiply(&v.y, &zInv) // y = Y / Z - - out := copyFieldElement(buf, &y) - out[31] |= byte(x.IsNegative() << 7) - return out -} - -var feOne = new(field.Element).One() - -// SetBytes sets v = x, where x is a 32-byte encoding of v. If x does not -// represent a valid point on the curve, SetBytes returns nil and an error and -// the receiver is unchanged. Otherwise, SetBytes returns v. -// -// Note that SetBytes accepts all non-canonical encodings of valid points. -// That is, it follows decoding rules that match most implementations in -// the ecosystem rather than RFC 8032. -func (v *Point) SetBytes(x []byte) (*Point, error) { - // Specifically, the non-canonical encodings that are accepted are - // 1) the ones where the field element is not reduced (see the - // (*field.Element).SetBytes docs) and - // 2) the ones where the x-coordinate is zero and the sign bit is set. - // - // Read more at https://hdevalence.ca/blog/2020-10-04-its-25519am, - // specifically the "Canonical A, R" section. - - y, err := new(field.Element).SetBytes(x) - if err != nil { - return nil, errors.New("edwards25519: invalid point encoding length") - } - - // -x² + y² = 1 + dx²y² - // x² + dx²y² = x²(dy² + 1) = y² - 1 - // x² = (y² - 1) / (dy² + 1) - - // u = y² - 1 - y2 := new(field.Element).Square(y) - u := new(field.Element).Subtract(y2, feOne) - - // v = dy² + 1 - vv := new(field.Element).Multiply(y2, d) - vv = vv.Add(vv, feOne) - - // x = +√(u/v) - xx, wasSquare := new(field.Element).SqrtRatio(u, vv) - if wasSquare == 0 { - return nil, errors.New("edwards25519: invalid point encoding") - } - - // Select the negative square root if the sign bit is set. - xxNeg := new(field.Element).Negate(xx) - xx = xx.Select(xxNeg, xx, int(x[31]>>7)) - - v.x.Set(xx) - v.y.Set(y) - v.z.One() - v.t.Multiply(xx, y) // xy = T / Z - - return v, nil -} - -func copyFieldElement(buf *[32]byte, v *field.Element) []byte { - copy(buf[:], v.Bytes()) - return buf[:] -} - -// Conversions. - -func (v *projP2) FromP1xP1(p *projP1xP1) *projP2 { - v.X.Multiply(&p.X, &p.T) - v.Y.Multiply(&p.Y, &p.Z) - v.Z.Multiply(&p.Z, &p.T) - return v -} - -func (v *projP2) FromP3(p *Point) *projP2 { - v.X.Set(&p.x) - v.Y.Set(&p.y) - v.Z.Set(&p.z) - return v -} - -func (v *Point) fromP1xP1(p *projP1xP1) *Point { - v.x.Multiply(&p.X, &p.T) - v.y.Multiply(&p.Y, &p.Z) - v.z.Multiply(&p.Z, &p.T) - v.t.Multiply(&p.X, &p.Y) - return v -} - -func (v *Point) fromP2(p *projP2) *Point { - v.x.Multiply(&p.X, &p.Z) - v.y.Multiply(&p.Y, &p.Z) - v.z.Square(&p.Z) - v.t.Multiply(&p.X, &p.Y) - return v -} - -// d is a constant in the curve equation. -var d, _ = new(field.Element).SetBytes([]byte{ - 0xa3, 0x78, 0x59, 0x13, 0xca, 0x4d, 0xeb, 0x75, - 0xab, 0xd8, 0x41, 0x41, 0x4d, 0x0a, 0x70, 0x00, - 0x98, 0xe8, 0x79, 0x77, 0x79, 0x40, 0xc7, 0x8c, - 0x73, 0xfe, 0x6f, 0x2b, 0xee, 0x6c, 0x03, 0x52}) -var d2 = new(field.Element).Add(d, d) - -func (v *projCached) FromP3(p *Point) *projCached { - v.YplusX.Add(&p.y, &p.x) - v.YminusX.Subtract(&p.y, &p.x) - v.Z.Set(&p.z) - v.T2d.Multiply(&p.t, d2) - return v -} - -func (v *affineCached) FromP3(p *Point) *affineCached { - v.YplusX.Add(&p.y, &p.x) - v.YminusX.Subtract(&p.y, &p.x) - v.T2d.Multiply(&p.t, d2) - - var invZ field.Element - invZ.Invert(&p.z) - v.YplusX.Multiply(&v.YplusX, &invZ) - v.YminusX.Multiply(&v.YminusX, &invZ) - v.T2d.Multiply(&v.T2d, &invZ) - return v -} - -// (Re)addition and subtraction. - -// Add sets v = p + q, and returns v. -func (v *Point) Add(p, q *Point) *Point { - checkInitialized(p, q) - qCached := new(projCached).FromP3(q) - result := new(projP1xP1).Add(p, qCached) - return v.fromP1xP1(result) -} - -// Subtract sets v = p - q, and returns v. -func (v *Point) Subtract(p, q *Point) *Point { - checkInitialized(p, q) - qCached := new(projCached).FromP3(q) - result := new(projP1xP1).Sub(p, qCached) - return v.fromP1xP1(result) -} - -func (v *projP1xP1) Add(p *Point, q *projCached) *projP1xP1 { - var YplusX, YminusX, PP, MM, TT2d, ZZ2 field.Element - - YplusX.Add(&p.y, &p.x) - YminusX.Subtract(&p.y, &p.x) - - PP.Multiply(&YplusX, &q.YplusX) - MM.Multiply(&YminusX, &q.YminusX) - TT2d.Multiply(&p.t, &q.T2d) - ZZ2.Multiply(&p.z, &q.Z) - - ZZ2.Add(&ZZ2, &ZZ2) - - v.X.Subtract(&PP, &MM) - v.Y.Add(&PP, &MM) - v.Z.Add(&ZZ2, &TT2d) - v.T.Subtract(&ZZ2, &TT2d) - return v -} - -func (v *projP1xP1) Sub(p *Point, q *projCached) *projP1xP1 { - var YplusX, YminusX, PP, MM, TT2d, ZZ2 field.Element - - YplusX.Add(&p.y, &p.x) - YminusX.Subtract(&p.y, &p.x) - - PP.Multiply(&YplusX, &q.YminusX) // flipped sign - MM.Multiply(&YminusX, &q.YplusX) // flipped sign - TT2d.Multiply(&p.t, &q.T2d) - ZZ2.Multiply(&p.z, &q.Z) - - ZZ2.Add(&ZZ2, &ZZ2) - - v.X.Subtract(&PP, &MM) - v.Y.Add(&PP, &MM) - v.Z.Subtract(&ZZ2, &TT2d) // flipped sign - v.T.Add(&ZZ2, &TT2d) // flipped sign - return v -} - -func (v *projP1xP1) AddAffine(p *Point, q *affineCached) *projP1xP1 { - var YplusX, YminusX, PP, MM, TT2d, Z2 field.Element - - YplusX.Add(&p.y, &p.x) - YminusX.Subtract(&p.y, &p.x) - - PP.Multiply(&YplusX, &q.YplusX) - MM.Multiply(&YminusX, &q.YminusX) - TT2d.Multiply(&p.t, &q.T2d) - - Z2.Add(&p.z, &p.z) - - v.X.Subtract(&PP, &MM) - v.Y.Add(&PP, &MM) - v.Z.Add(&Z2, &TT2d) - v.T.Subtract(&Z2, &TT2d) - return v -} - -func (v *projP1xP1) SubAffine(p *Point, q *affineCached) *projP1xP1 { - var YplusX, YminusX, PP, MM, TT2d, Z2 field.Element - - YplusX.Add(&p.y, &p.x) - YminusX.Subtract(&p.y, &p.x) - - PP.Multiply(&YplusX, &q.YminusX) // flipped sign - MM.Multiply(&YminusX, &q.YplusX) // flipped sign - TT2d.Multiply(&p.t, &q.T2d) - - Z2.Add(&p.z, &p.z) - - v.X.Subtract(&PP, &MM) - v.Y.Add(&PP, &MM) - v.Z.Subtract(&Z2, &TT2d) // flipped sign - v.T.Add(&Z2, &TT2d) // flipped sign - return v -} - -// Doubling. - -func (v *projP1xP1) Double(p *projP2) *projP1xP1 { - var XX, YY, ZZ2, XplusYsq field.Element - - XX.Square(&p.X) - YY.Square(&p.Y) - ZZ2.Square(&p.Z) - ZZ2.Add(&ZZ2, &ZZ2) - XplusYsq.Add(&p.X, &p.Y) - XplusYsq.Square(&XplusYsq) - - v.Y.Add(&YY, &XX) - v.Z.Subtract(&YY, &XX) - - v.X.Subtract(&XplusYsq, &v.Y) - v.T.Subtract(&ZZ2, &v.Z) - return v -} - -// Negation. - -// Negate sets v = -p, and returns v. -func (v *Point) Negate(p *Point) *Point { - checkInitialized(p) - v.x.Negate(&p.x) - v.y.Set(&p.y) - v.z.Set(&p.z) - v.t.Negate(&p.t) - return v -} - -// Equal returns 1 if v is equivalent to u, and 0 otherwise. -func (v *Point) Equal(u *Point) int { - checkInitialized(v, u) - - var t1, t2, t3, t4 field.Element - t1.Multiply(&v.x, &u.z) - t2.Multiply(&u.x, &v.z) - t3.Multiply(&v.y, &u.z) - t4.Multiply(&u.y, &v.z) - - return t1.Equal(&t2) & t3.Equal(&t4) -} - -// Constant-time operations - -// Select sets v to a if cond == 1 and to b if cond == 0. -func (v *projCached) Select(a, b *projCached, cond int) *projCached { - v.YplusX.Select(&a.YplusX, &b.YplusX, cond) - v.YminusX.Select(&a.YminusX, &b.YminusX, cond) - v.Z.Select(&a.Z, &b.Z, cond) - v.T2d.Select(&a.T2d, &b.T2d, cond) - return v -} - -// Select sets v to a if cond == 1 and to b if cond == 0. -func (v *affineCached) Select(a, b *affineCached, cond int) *affineCached { - v.YplusX.Select(&a.YplusX, &b.YplusX, cond) - v.YminusX.Select(&a.YminusX, &b.YminusX, cond) - v.T2d.Select(&a.T2d, &b.T2d, cond) - return v -} - -// CondNeg negates v if cond == 1 and leaves it unchanged if cond == 0. -func (v *projCached) CondNeg(cond int) *projCached { - v.YplusX.Swap(&v.YminusX, cond) - v.T2d.Select(new(field.Element).Negate(&v.T2d), &v.T2d, cond) - return v -} - -// CondNeg negates v if cond == 1 and leaves it unchanged if cond == 0. -func (v *affineCached) CondNeg(cond int) *affineCached { - v.YplusX.Swap(&v.YminusX, cond) - v.T2d.Select(new(field.Element).Negate(&v.T2d), &v.T2d, cond) - return v -} diff --git a/vendor/filippo.io/edwards25519/extra.go b/vendor/filippo.io/edwards25519/extra.go deleted file mode 100644 index d152d68ff4..0000000000 --- a/vendor/filippo.io/edwards25519/extra.go +++ /dev/null @@ -1,349 +0,0 @@ -// Copyright (c) 2021 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package edwards25519 - -// This file contains additional functionality that is not included in the -// upstream crypto/internal/edwards25519 package. - -import ( - "errors" - - "filippo.io/edwards25519/field" -) - -// ExtendedCoordinates returns v in extended coordinates (X:Y:Z:T) where -// x = X/Z, y = Y/Z, and xy = T/Z as in https://eprint.iacr.org/2008/522. -func (v *Point) ExtendedCoordinates() (X, Y, Z, T *field.Element) { - // This function is outlined to make the allocations inline in the caller - // rather than happen on the heap. Don't change the style without making - // sure it doesn't increase the inliner cost. - var e [4]field.Element - X, Y, Z, T = v.extendedCoordinates(&e) - return -} - -func (v *Point) extendedCoordinates(e *[4]field.Element) (X, Y, Z, T *field.Element) { - checkInitialized(v) - X = e[0].Set(&v.x) - Y = e[1].Set(&v.y) - Z = e[2].Set(&v.z) - T = e[3].Set(&v.t) - return -} - -// SetExtendedCoordinates sets v = (X:Y:Z:T) in extended coordinates where -// x = X/Z, y = Y/Z, and xy = T/Z as in https://eprint.iacr.org/2008/522. -// -// If the coordinates are invalid or don't represent a valid point on the curve, -// SetExtendedCoordinates returns nil and an error and the receiver is -// unchanged. Otherwise, SetExtendedCoordinates returns v. -func (v *Point) SetExtendedCoordinates(X, Y, Z, T *field.Element) (*Point, error) { - if !isOnCurve(X, Y, Z, T) { - return nil, errors.New("edwards25519: invalid point coordinates") - } - v.x.Set(X) - v.y.Set(Y) - v.z.Set(Z) - v.t.Set(T) - return v, nil -} - -func isOnCurve(X, Y, Z, T *field.Element) bool { - var lhs, rhs field.Element - XX := new(field.Element).Square(X) - YY := new(field.Element).Square(Y) - ZZ := new(field.Element).Square(Z) - TT := new(field.Element).Square(T) - // -x² + y² = 1 + dx²y² - // -(X/Z)² + (Y/Z)² = 1 + d(T/Z)² - // -X² + Y² = Z² + dT² - lhs.Subtract(YY, XX) - rhs.Multiply(d, TT).Add(&rhs, ZZ) - if lhs.Equal(&rhs) != 1 { - return false - } - // xy = T/Z - // XY/Z² = T/Z - // XY = TZ - lhs.Multiply(X, Y) - rhs.Multiply(T, Z) - return lhs.Equal(&rhs) == 1 -} - -// BytesMontgomery converts v to a point on the birationally-equivalent -// Curve25519 Montgomery curve, and returns its canonical 32 bytes encoding -// according to RFC 7748. -// -// Note that BytesMontgomery only encodes the u-coordinate, so v and -v encode -// to the same value. If v is the identity point, BytesMontgomery returns 32 -// zero bytes, analogously to the X25519 function. -// -// The lack of an inverse operation (such as SetMontgomeryBytes) is deliberate: -// while every valid edwards25519 point has a unique u-coordinate Montgomery -// encoding, X25519 accepts inputs on the quadratic twist, which don't correspond -// to any edwards25519 point, and every other X25519 input corresponds to two -// edwards25519 points. -func (v *Point) BytesMontgomery() []byte { - // This function is outlined to make the allocations inline in the caller - // rather than happen on the heap. - var buf [32]byte - return v.bytesMontgomery(&buf) -} - -func (v *Point) bytesMontgomery(buf *[32]byte) []byte { - checkInitialized(v) - - // RFC 7748, Section 4.1 provides the bilinear map to calculate the - // Montgomery u-coordinate - // - // u = (1 + y) / (1 - y) - // - // where y = Y / Z. - - var y, recip, u field.Element - - y.Multiply(&v.y, y.Invert(&v.z)) // y = Y / Z - recip.Invert(recip.Subtract(feOne, &y)) // r = 1/(1 - y) - u.Multiply(u.Add(feOne, &y), &recip) // u = (1 + y)*r - - return copyFieldElement(buf, &u) -} - -// MultByCofactor sets v = 8 * p, and returns v. -func (v *Point) MultByCofactor(p *Point) *Point { - checkInitialized(p) - result := projP1xP1{} - pp := (&projP2{}).FromP3(p) - result.Double(pp) - pp.FromP1xP1(&result) - result.Double(pp) - pp.FromP1xP1(&result) - result.Double(pp) - return v.fromP1xP1(&result) -} - -// Given k > 0, set s = s**(2*i). -func (s *Scalar) pow2k(k int) { - for i := 0; i < k; i++ { - s.Multiply(s, s) - } -} - -// Invert sets s to the inverse of a nonzero scalar v, and returns s. -// -// If t is zero, Invert returns zero. -func (s *Scalar) Invert(t *Scalar) *Scalar { - // Uses a hardcoded sliding window of width 4. - var table [8]Scalar - var tt Scalar - tt.Multiply(t, t) - table[0] = *t - for i := 0; i < 7; i++ { - table[i+1].Multiply(&table[i], &tt) - } - // Now table = [t**1, t**3, t**5, t**7, t**9, t**11, t**13, t**15] - // so t**k = t[k/2] for odd k - - // To compute the sliding window digits, use the following Sage script: - - // sage: import itertools - // sage: def sliding_window(w,k): - // ....: digits = [] - // ....: while k > 0: - // ....: if k % 2 == 1: - // ....: kmod = k % (2**w) - // ....: digits.append(kmod) - // ....: k = k - kmod - // ....: else: - // ....: digits.append(0) - // ....: k = k // 2 - // ....: return digits - - // Now we can compute s roughly as follows: - - // sage: s = 1 - // sage: for coeff in reversed(sliding_window(4,l-2)): - // ....: s = s*s - // ....: if coeff > 0 : - // ....: s = s*t**coeff - - // This works on one bit at a time, with many runs of zeros. - // The digits can be collapsed into [(count, coeff)] as follows: - - // sage: [(len(list(group)),d) for d,group in itertools.groupby(sliding_window(4,l-2))] - - // Entries of the form (k, 0) turn into pow2k(k) - // Entries of the form (1, coeff) turn into a squaring and then a table lookup. - // We can fold the squaring into the previous pow2k(k) as pow2k(k+1). - - *s = table[1/2] - s.pow2k(127 + 1) - s.Multiply(s, &table[1/2]) - s.pow2k(4 + 1) - s.Multiply(s, &table[9/2]) - s.pow2k(3 + 1) - s.Multiply(s, &table[11/2]) - s.pow2k(3 + 1) - s.Multiply(s, &table[13/2]) - s.pow2k(3 + 1) - s.Multiply(s, &table[15/2]) - s.pow2k(4 + 1) - s.Multiply(s, &table[7/2]) - s.pow2k(4 + 1) - s.Multiply(s, &table[15/2]) - s.pow2k(3 + 1) - s.Multiply(s, &table[5/2]) - s.pow2k(3 + 1) - s.Multiply(s, &table[1/2]) - s.pow2k(4 + 1) - s.Multiply(s, &table[15/2]) - s.pow2k(4 + 1) - s.Multiply(s, &table[15/2]) - s.pow2k(4 + 1) - s.Multiply(s, &table[7/2]) - s.pow2k(3 + 1) - s.Multiply(s, &table[3/2]) - s.pow2k(4 + 1) - s.Multiply(s, &table[11/2]) - s.pow2k(5 + 1) - s.Multiply(s, &table[11/2]) - s.pow2k(9 + 1) - s.Multiply(s, &table[9/2]) - s.pow2k(3 + 1) - s.Multiply(s, &table[3/2]) - s.pow2k(4 + 1) - s.Multiply(s, &table[3/2]) - s.pow2k(4 + 1) - s.Multiply(s, &table[3/2]) - s.pow2k(4 + 1) - s.Multiply(s, &table[9/2]) - s.pow2k(3 + 1) - s.Multiply(s, &table[7/2]) - s.pow2k(3 + 1) - s.Multiply(s, &table[3/2]) - s.pow2k(3 + 1) - s.Multiply(s, &table[13/2]) - s.pow2k(3 + 1) - s.Multiply(s, &table[7/2]) - s.pow2k(4 + 1) - s.Multiply(s, &table[9/2]) - s.pow2k(3 + 1) - s.Multiply(s, &table[15/2]) - s.pow2k(4 + 1) - s.Multiply(s, &table[11/2]) - - return s -} - -// MultiScalarMult sets v = sum(scalars[i] * points[i]), and returns v. -// -// Execution time depends only on the lengths of the two slices, which must match. -func (v *Point) MultiScalarMult(scalars []*Scalar, points []*Point) *Point { - if len(scalars) != len(points) { - panic("edwards25519: called MultiScalarMult with different size inputs") - } - checkInitialized(points...) - - // Proceed as in the single-base case, but share doublings - // between each point in the multiscalar equation. - - // Build lookup tables for each point - tables := make([]projLookupTable, len(points)) - for i := range tables { - tables[i].FromP3(points[i]) - } - // Compute signed radix-16 digits for each scalar - digits := make([][64]int8, len(scalars)) - for i := range digits { - digits[i] = scalars[i].signedRadix16() - } - - // Unwrap first loop iteration to save computing 16*identity - multiple := &projCached{} - tmp1 := &projP1xP1{} - tmp2 := &projP2{} - // Lookup-and-add the appropriate multiple of each input point - for j := range tables { - tables[j].SelectInto(multiple, digits[j][63]) - tmp1.Add(v, multiple) // tmp1 = v + x_(j,63)*Q in P1xP1 coords - v.fromP1xP1(tmp1) // update v - } - tmp2.FromP3(v) // set up tmp2 = v in P2 coords for next iteration - for i := 62; i >= 0; i-- { - tmp1.Double(tmp2) // tmp1 = 2*(prev) in P1xP1 coords - tmp2.FromP1xP1(tmp1) // tmp2 = 2*(prev) in P2 coords - tmp1.Double(tmp2) // tmp1 = 4*(prev) in P1xP1 coords - tmp2.FromP1xP1(tmp1) // tmp2 = 4*(prev) in P2 coords - tmp1.Double(tmp2) // tmp1 = 8*(prev) in P1xP1 coords - tmp2.FromP1xP1(tmp1) // tmp2 = 8*(prev) in P2 coords - tmp1.Double(tmp2) // tmp1 = 16*(prev) in P1xP1 coords - v.fromP1xP1(tmp1) // v = 16*(prev) in P3 coords - // Lookup-and-add the appropriate multiple of each input point - for j := range tables { - tables[j].SelectInto(multiple, digits[j][i]) - tmp1.Add(v, multiple) // tmp1 = v + x_(j,i)*Q in P1xP1 coords - v.fromP1xP1(tmp1) // update v - } - tmp2.FromP3(v) // set up tmp2 = v in P2 coords for next iteration - } - return v -} - -// VarTimeMultiScalarMult sets v = sum(scalars[i] * points[i]), and returns v. -// -// Execution time depends on the inputs. -func (v *Point) VarTimeMultiScalarMult(scalars []*Scalar, points []*Point) *Point { - if len(scalars) != len(points) { - panic("edwards25519: called VarTimeMultiScalarMult with different size inputs") - } - checkInitialized(points...) - - // Generalize double-base NAF computation to arbitrary sizes. - // Here all the points are dynamic, so we only use the smaller - // tables. - - // Build lookup tables for each point - tables := make([]nafLookupTable5, len(points)) - for i := range tables { - tables[i].FromP3(points[i]) - } - // Compute a NAF for each scalar - nafs := make([][256]int8, len(scalars)) - for i := range nafs { - nafs[i] = scalars[i].nonAdjacentForm(5) - } - - multiple := &projCached{} - tmp1 := &projP1xP1{} - tmp2 := &projP2{} - tmp2.Zero() - - // Move from high to low bits, doubling the accumulator - // at each iteration and checking whether there is a nonzero - // coefficient to look up a multiple of. - // - // Skip trying to find the first nonzero coefficent, because - // searching might be more work than a few extra doublings. - for i := 255; i >= 0; i-- { - tmp1.Double(tmp2) - - for j := range nafs { - if nafs[j][i] > 0 { - v.fromP1xP1(tmp1) - tables[j].SelectInto(multiple, nafs[j][i]) - tmp1.Add(v, multiple) - } else if nafs[j][i] < 0 { - v.fromP1xP1(tmp1) - tables[j].SelectInto(multiple, -nafs[j][i]) - tmp1.Sub(v, multiple) - } - } - - tmp2.FromP1xP1(tmp1) - } - - v.fromP2(tmp2) - return v -} diff --git a/vendor/filippo.io/edwards25519/field/fe.go b/vendor/filippo.io/edwards25519/field/fe.go deleted file mode 100644 index 5518ef2b90..0000000000 --- a/vendor/filippo.io/edwards25519/field/fe.go +++ /dev/null @@ -1,420 +0,0 @@ -// Copyright (c) 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package field implements fast arithmetic modulo 2^255-19. -package field - -import ( - "crypto/subtle" - "encoding/binary" - "errors" - "math/bits" -) - -// Element represents an element of the field GF(2^255-19). Note that this -// is not a cryptographically secure group, and should only be used to interact -// with edwards25519.Point coordinates. -// -// This type works similarly to math/big.Int, and all arguments and receivers -// are allowed to alias. -// -// The zero value is a valid zero element. -type Element struct { - // An element t represents the integer - // t.l0 + t.l1*2^51 + t.l2*2^102 + t.l3*2^153 + t.l4*2^204 - // - // Between operations, all limbs are expected to be lower than 2^52. - l0 uint64 - l1 uint64 - l2 uint64 - l3 uint64 - l4 uint64 -} - -const maskLow51Bits uint64 = (1 << 51) - 1 - -var feZero = &Element{0, 0, 0, 0, 0} - -// Zero sets v = 0, and returns v. -func (v *Element) Zero() *Element { - *v = *feZero - return v -} - -var feOne = &Element{1, 0, 0, 0, 0} - -// One sets v = 1, and returns v. -func (v *Element) One() *Element { - *v = *feOne - return v -} - -// reduce reduces v modulo 2^255 - 19 and returns it. -func (v *Element) reduce() *Element { - v.carryPropagate() - - // After the light reduction we now have a field element representation - // v < 2^255 + 2^13 * 19, but need v < 2^255 - 19. - - // If v >= 2^255 - 19, then v + 19 >= 2^255, which would overflow 2^255 - 1, - // generating a carry. That is, c will be 0 if v < 2^255 - 19, and 1 otherwise. - c := (v.l0 + 19) >> 51 - c = (v.l1 + c) >> 51 - c = (v.l2 + c) >> 51 - c = (v.l3 + c) >> 51 - c = (v.l4 + c) >> 51 - - // If v < 2^255 - 19 and c = 0, this will be a no-op. Otherwise, it's - // effectively applying the reduction identity to the carry. - v.l0 += 19 * c - - v.l1 += v.l0 >> 51 - v.l0 = v.l0 & maskLow51Bits - v.l2 += v.l1 >> 51 - v.l1 = v.l1 & maskLow51Bits - v.l3 += v.l2 >> 51 - v.l2 = v.l2 & maskLow51Bits - v.l4 += v.l3 >> 51 - v.l3 = v.l3 & maskLow51Bits - // no additional carry - v.l4 = v.l4 & maskLow51Bits - - return v -} - -// Add sets v = a + b, and returns v. -func (v *Element) Add(a, b *Element) *Element { - v.l0 = a.l0 + b.l0 - v.l1 = a.l1 + b.l1 - v.l2 = a.l2 + b.l2 - v.l3 = a.l3 + b.l3 - v.l4 = a.l4 + b.l4 - // Using the generic implementation here is actually faster than the - // assembly. Probably because the body of this function is so simple that - // the compiler can figure out better optimizations by inlining the carry - // propagation. - return v.carryPropagateGeneric() -} - -// Subtract sets v = a - b, and returns v. -func (v *Element) Subtract(a, b *Element) *Element { - // We first add 2 * p, to guarantee the subtraction won't underflow, and - // then subtract b (which can be up to 2^255 + 2^13 * 19). - v.l0 = (a.l0 + 0xFFFFFFFFFFFDA) - b.l0 - v.l1 = (a.l1 + 0xFFFFFFFFFFFFE) - b.l1 - v.l2 = (a.l2 + 0xFFFFFFFFFFFFE) - b.l2 - v.l3 = (a.l3 + 0xFFFFFFFFFFFFE) - b.l3 - v.l4 = (a.l4 + 0xFFFFFFFFFFFFE) - b.l4 - return v.carryPropagate() -} - -// Negate sets v = -a, and returns v. -func (v *Element) Negate(a *Element) *Element { - return v.Subtract(feZero, a) -} - -// Invert sets v = 1/z mod p, and returns v. -// -// If z == 0, Invert returns v = 0. -func (v *Element) Invert(z *Element) *Element { - // Inversion is implemented as exponentiation with exponent p − 2. It uses the - // same sequence of 255 squarings and 11 multiplications as [Curve25519]. - var z2, z9, z11, z2_5_0, z2_10_0, z2_20_0, z2_50_0, z2_100_0, t Element - - z2.Square(z) // 2 - t.Square(&z2) // 4 - t.Square(&t) // 8 - z9.Multiply(&t, z) // 9 - z11.Multiply(&z9, &z2) // 11 - t.Square(&z11) // 22 - z2_5_0.Multiply(&t, &z9) // 31 = 2^5 - 2^0 - - t.Square(&z2_5_0) // 2^6 - 2^1 - for i := 0; i < 4; i++ { - t.Square(&t) // 2^10 - 2^5 - } - z2_10_0.Multiply(&t, &z2_5_0) // 2^10 - 2^0 - - t.Square(&z2_10_0) // 2^11 - 2^1 - for i := 0; i < 9; i++ { - t.Square(&t) // 2^20 - 2^10 - } - z2_20_0.Multiply(&t, &z2_10_0) // 2^20 - 2^0 - - t.Square(&z2_20_0) // 2^21 - 2^1 - for i := 0; i < 19; i++ { - t.Square(&t) // 2^40 - 2^20 - } - t.Multiply(&t, &z2_20_0) // 2^40 - 2^0 - - t.Square(&t) // 2^41 - 2^1 - for i := 0; i < 9; i++ { - t.Square(&t) // 2^50 - 2^10 - } - z2_50_0.Multiply(&t, &z2_10_0) // 2^50 - 2^0 - - t.Square(&z2_50_0) // 2^51 - 2^1 - for i := 0; i < 49; i++ { - t.Square(&t) // 2^100 - 2^50 - } - z2_100_0.Multiply(&t, &z2_50_0) // 2^100 - 2^0 - - t.Square(&z2_100_0) // 2^101 - 2^1 - for i := 0; i < 99; i++ { - t.Square(&t) // 2^200 - 2^100 - } - t.Multiply(&t, &z2_100_0) // 2^200 - 2^0 - - t.Square(&t) // 2^201 - 2^1 - for i := 0; i < 49; i++ { - t.Square(&t) // 2^250 - 2^50 - } - t.Multiply(&t, &z2_50_0) // 2^250 - 2^0 - - t.Square(&t) // 2^251 - 2^1 - t.Square(&t) // 2^252 - 2^2 - t.Square(&t) // 2^253 - 2^3 - t.Square(&t) // 2^254 - 2^4 - t.Square(&t) // 2^255 - 2^5 - - return v.Multiply(&t, &z11) // 2^255 - 21 -} - -// Set sets v = a, and returns v. -func (v *Element) Set(a *Element) *Element { - *v = *a - return v -} - -// SetBytes sets v to x, where x is a 32-byte little-endian encoding. If x is -// not of the right length, SetBytes returns nil and an error, and the -// receiver is unchanged. -// -// Consistent with RFC 7748, the most significant bit (the high bit of the -// last byte) is ignored, and non-canonical values (2^255-19 through 2^255-1) -// are accepted. Note that this is laxer than specified by RFC 8032, but -// consistent with most Ed25519 implementations. -func (v *Element) SetBytes(x []byte) (*Element, error) { - if len(x) != 32 { - return nil, errors.New("edwards25519: invalid field element input size") - } - - // Bits 0:51 (bytes 0:8, bits 0:64, shift 0, mask 51). - v.l0 = binary.LittleEndian.Uint64(x[0:8]) - v.l0 &= maskLow51Bits - // Bits 51:102 (bytes 6:14, bits 48:112, shift 3, mask 51). - v.l1 = binary.LittleEndian.Uint64(x[6:14]) >> 3 - v.l1 &= maskLow51Bits - // Bits 102:153 (bytes 12:20, bits 96:160, shift 6, mask 51). - v.l2 = binary.LittleEndian.Uint64(x[12:20]) >> 6 - v.l2 &= maskLow51Bits - // Bits 153:204 (bytes 19:27, bits 152:216, shift 1, mask 51). - v.l3 = binary.LittleEndian.Uint64(x[19:27]) >> 1 - v.l3 &= maskLow51Bits - // Bits 204:255 (bytes 24:32, bits 192:256, shift 12, mask 51). - // Note: not bytes 25:33, shift 4, to avoid overread. - v.l4 = binary.LittleEndian.Uint64(x[24:32]) >> 12 - v.l4 &= maskLow51Bits - - return v, nil -} - -// Bytes returns the canonical 32-byte little-endian encoding of v. -func (v *Element) Bytes() []byte { - // This function is outlined to make the allocations inline in the caller - // rather than happen on the heap. - var out [32]byte - return v.bytes(&out) -} - -func (v *Element) bytes(out *[32]byte) []byte { - t := *v - t.reduce() - - var buf [8]byte - for i, l := range [5]uint64{t.l0, t.l1, t.l2, t.l3, t.l4} { - bitsOffset := i * 51 - binary.LittleEndian.PutUint64(buf[:], l<= len(out) { - break - } - out[off] |= bb - } - } - - return out[:] -} - -// Equal returns 1 if v and u are equal, and 0 otherwise. -func (v *Element) Equal(u *Element) int { - sa, sv := u.Bytes(), v.Bytes() - return subtle.ConstantTimeCompare(sa, sv) -} - -// mask64Bits returns 0xffffffff if cond is 1, and 0 otherwise. -func mask64Bits(cond int) uint64 { return ^(uint64(cond) - 1) } - -// Select sets v to a if cond == 1, and to b if cond == 0. -func (v *Element) Select(a, b *Element, cond int) *Element { - m := mask64Bits(cond) - v.l0 = (m & a.l0) | (^m & b.l0) - v.l1 = (m & a.l1) | (^m & b.l1) - v.l2 = (m & a.l2) | (^m & b.l2) - v.l3 = (m & a.l3) | (^m & b.l3) - v.l4 = (m & a.l4) | (^m & b.l4) - return v -} - -// Swap swaps v and u if cond == 1 or leaves them unchanged if cond == 0, and returns v. -func (v *Element) Swap(u *Element, cond int) { - m := mask64Bits(cond) - t := m & (v.l0 ^ u.l0) - v.l0 ^= t - u.l0 ^= t - t = m & (v.l1 ^ u.l1) - v.l1 ^= t - u.l1 ^= t - t = m & (v.l2 ^ u.l2) - v.l2 ^= t - u.l2 ^= t - t = m & (v.l3 ^ u.l3) - v.l3 ^= t - u.l3 ^= t - t = m & (v.l4 ^ u.l4) - v.l4 ^= t - u.l4 ^= t -} - -// IsNegative returns 1 if v is negative, and 0 otherwise. -func (v *Element) IsNegative() int { - return int(v.Bytes()[0] & 1) -} - -// Absolute sets v to |u|, and returns v. -func (v *Element) Absolute(u *Element) *Element { - return v.Select(new(Element).Negate(u), u, u.IsNegative()) -} - -// Multiply sets v = x * y, and returns v. -func (v *Element) Multiply(x, y *Element) *Element { - feMul(v, x, y) - return v -} - -// Square sets v = x * x, and returns v. -func (v *Element) Square(x *Element) *Element { - feSquare(v, x) - return v -} - -// Mult32 sets v = x * y, and returns v. -func (v *Element) Mult32(x *Element, y uint32) *Element { - x0lo, x0hi := mul51(x.l0, y) - x1lo, x1hi := mul51(x.l1, y) - x2lo, x2hi := mul51(x.l2, y) - x3lo, x3hi := mul51(x.l3, y) - x4lo, x4hi := mul51(x.l4, y) - v.l0 = x0lo + 19*x4hi // carried over per the reduction identity - v.l1 = x1lo + x0hi - v.l2 = x2lo + x1hi - v.l3 = x3lo + x2hi - v.l4 = x4lo + x3hi - // The hi portions are going to be only 32 bits, plus any previous excess, - // so we can skip the carry propagation. - return v -} - -// mul51 returns lo + hi * 2⁵¹ = a * b. -func mul51(a uint64, b uint32) (lo uint64, hi uint64) { - mh, ml := bits.Mul64(a, uint64(b)) - lo = ml & maskLow51Bits - hi = (mh << 13) | (ml >> 51) - return -} - -// Pow22523 set v = x^((p-5)/8), and returns v. (p-5)/8 is 2^252-3. -func (v *Element) Pow22523(x *Element) *Element { - var t0, t1, t2 Element - - t0.Square(x) // x^2 - t1.Square(&t0) // x^4 - t1.Square(&t1) // x^8 - t1.Multiply(x, &t1) // x^9 - t0.Multiply(&t0, &t1) // x^11 - t0.Square(&t0) // x^22 - t0.Multiply(&t1, &t0) // x^31 - t1.Square(&t0) // x^62 - for i := 1; i < 5; i++ { // x^992 - t1.Square(&t1) - } - t0.Multiply(&t1, &t0) // x^1023 -> 1023 = 2^10 - 1 - t1.Square(&t0) // 2^11 - 2 - for i := 1; i < 10; i++ { // 2^20 - 2^10 - t1.Square(&t1) - } - t1.Multiply(&t1, &t0) // 2^20 - 1 - t2.Square(&t1) // 2^21 - 2 - for i := 1; i < 20; i++ { // 2^40 - 2^20 - t2.Square(&t2) - } - t1.Multiply(&t2, &t1) // 2^40 - 1 - t1.Square(&t1) // 2^41 - 2 - for i := 1; i < 10; i++ { // 2^50 - 2^10 - t1.Square(&t1) - } - t0.Multiply(&t1, &t0) // 2^50 - 1 - t1.Square(&t0) // 2^51 - 2 - for i := 1; i < 50; i++ { // 2^100 - 2^50 - t1.Square(&t1) - } - t1.Multiply(&t1, &t0) // 2^100 - 1 - t2.Square(&t1) // 2^101 - 2 - for i := 1; i < 100; i++ { // 2^200 - 2^100 - t2.Square(&t2) - } - t1.Multiply(&t2, &t1) // 2^200 - 1 - t1.Square(&t1) // 2^201 - 2 - for i := 1; i < 50; i++ { // 2^250 - 2^50 - t1.Square(&t1) - } - t0.Multiply(&t1, &t0) // 2^250 - 1 - t0.Square(&t0) // 2^251 - 2 - t0.Square(&t0) // 2^252 - 4 - return v.Multiply(&t0, x) // 2^252 - 3 -> x^(2^252-3) -} - -// sqrtM1 is 2^((p-1)/4), which squared is equal to -1 by Euler's Criterion. -var sqrtM1 = &Element{1718705420411056, 234908883556509, - 2233514472574048, 2117202627021982, 765476049583133} - -// SqrtRatio sets r to the non-negative square root of the ratio of u and v. -// -// If u/v is square, SqrtRatio returns r and 1. If u/v is not square, SqrtRatio -// sets r according to Section 4.3 of draft-irtf-cfrg-ristretto255-decaf448-00, -// and returns r and 0. -func (r *Element) SqrtRatio(u, v *Element) (R *Element, wasSquare int) { - t0 := new(Element) - - // r = (u * v3) * (u * v7)^((p-5)/8) - v2 := new(Element).Square(v) - uv3 := new(Element).Multiply(u, t0.Multiply(v2, v)) - uv7 := new(Element).Multiply(uv3, t0.Square(v2)) - rr := new(Element).Multiply(uv3, t0.Pow22523(uv7)) - - check := new(Element).Multiply(v, t0.Square(rr)) // check = v * r^2 - - uNeg := new(Element).Negate(u) - correctSignSqrt := check.Equal(u) - flippedSignSqrt := check.Equal(uNeg) - flippedSignSqrtI := check.Equal(t0.Multiply(uNeg, sqrtM1)) - - rPrime := new(Element).Multiply(rr, sqrtM1) // r_prime = SQRT_M1 * r - // r = CT_SELECT(r_prime IF flipped_sign_sqrt | flipped_sign_sqrt_i ELSE r) - rr.Select(rPrime, rr, flippedSignSqrt|flippedSignSqrtI) - - r.Absolute(rr) // Choose the nonnegative square root. - return r, correctSignSqrt | flippedSignSqrt -} diff --git a/vendor/filippo.io/edwards25519/field/fe_amd64.go b/vendor/filippo.io/edwards25519/field/fe_amd64.go deleted file mode 100644 index edcf163c4e..0000000000 --- a/vendor/filippo.io/edwards25519/field/fe_amd64.go +++ /dev/null @@ -1,16 +0,0 @@ -// Code generated by command: go run fe_amd64_asm.go -out ../fe_amd64.s -stubs ../fe_amd64.go -pkg field. DO NOT EDIT. - -//go:build amd64 && gc && !purego -// +build amd64,gc,!purego - -package field - -// feMul sets out = a * b. It works like feMulGeneric. -// -//go:noescape -func feMul(out *Element, a *Element, b *Element) - -// feSquare sets out = a * a. It works like feSquareGeneric. -// -//go:noescape -func feSquare(out *Element, a *Element) diff --git a/vendor/filippo.io/edwards25519/field/fe_amd64.s b/vendor/filippo.io/edwards25519/field/fe_amd64.s deleted file mode 100644 index 293f013c94..0000000000 --- a/vendor/filippo.io/edwards25519/field/fe_amd64.s +++ /dev/null @@ -1,379 +0,0 @@ -// Code generated by command: go run fe_amd64_asm.go -out ../fe_amd64.s -stubs ../fe_amd64.go -pkg field. DO NOT EDIT. - -//go:build amd64 && gc && !purego -// +build amd64,gc,!purego - -#include "textflag.h" - -// func feMul(out *Element, a *Element, b *Element) -TEXT ·feMul(SB), NOSPLIT, $0-24 - MOVQ a+8(FP), CX - MOVQ b+16(FP), BX - - // r0 = a0×b0 - MOVQ (CX), AX - MULQ (BX) - MOVQ AX, DI - MOVQ DX, SI - - // r0 += 19×a1×b4 - MOVQ 8(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 32(BX) - ADDQ AX, DI - ADCQ DX, SI - - // r0 += 19×a2×b3 - MOVQ 16(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 24(BX) - ADDQ AX, DI - ADCQ DX, SI - - // r0 += 19×a3×b2 - MOVQ 24(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 16(BX) - ADDQ AX, DI - ADCQ DX, SI - - // r0 += 19×a4×b1 - MOVQ 32(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 8(BX) - ADDQ AX, DI - ADCQ DX, SI - - // r1 = a0×b1 - MOVQ (CX), AX - MULQ 8(BX) - MOVQ AX, R9 - MOVQ DX, R8 - - // r1 += a1×b0 - MOVQ 8(CX), AX - MULQ (BX) - ADDQ AX, R9 - ADCQ DX, R8 - - // r1 += 19×a2×b4 - MOVQ 16(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 32(BX) - ADDQ AX, R9 - ADCQ DX, R8 - - // r1 += 19×a3×b3 - MOVQ 24(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 24(BX) - ADDQ AX, R9 - ADCQ DX, R8 - - // r1 += 19×a4×b2 - MOVQ 32(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 16(BX) - ADDQ AX, R9 - ADCQ DX, R8 - - // r2 = a0×b2 - MOVQ (CX), AX - MULQ 16(BX) - MOVQ AX, R11 - MOVQ DX, R10 - - // r2 += a1×b1 - MOVQ 8(CX), AX - MULQ 8(BX) - ADDQ AX, R11 - ADCQ DX, R10 - - // r2 += a2×b0 - MOVQ 16(CX), AX - MULQ (BX) - ADDQ AX, R11 - ADCQ DX, R10 - - // r2 += 19×a3×b4 - MOVQ 24(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 32(BX) - ADDQ AX, R11 - ADCQ DX, R10 - - // r2 += 19×a4×b3 - MOVQ 32(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 24(BX) - ADDQ AX, R11 - ADCQ DX, R10 - - // r3 = a0×b3 - MOVQ (CX), AX - MULQ 24(BX) - MOVQ AX, R13 - MOVQ DX, R12 - - // r3 += a1×b2 - MOVQ 8(CX), AX - MULQ 16(BX) - ADDQ AX, R13 - ADCQ DX, R12 - - // r3 += a2×b1 - MOVQ 16(CX), AX - MULQ 8(BX) - ADDQ AX, R13 - ADCQ DX, R12 - - // r3 += a3×b0 - MOVQ 24(CX), AX - MULQ (BX) - ADDQ AX, R13 - ADCQ DX, R12 - - // r3 += 19×a4×b4 - MOVQ 32(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 32(BX) - ADDQ AX, R13 - ADCQ DX, R12 - - // r4 = a0×b4 - MOVQ (CX), AX - MULQ 32(BX) - MOVQ AX, R15 - MOVQ DX, R14 - - // r4 += a1×b3 - MOVQ 8(CX), AX - MULQ 24(BX) - ADDQ AX, R15 - ADCQ DX, R14 - - // r4 += a2×b2 - MOVQ 16(CX), AX - MULQ 16(BX) - ADDQ AX, R15 - ADCQ DX, R14 - - // r4 += a3×b1 - MOVQ 24(CX), AX - MULQ 8(BX) - ADDQ AX, R15 - ADCQ DX, R14 - - // r4 += a4×b0 - MOVQ 32(CX), AX - MULQ (BX) - ADDQ AX, R15 - ADCQ DX, R14 - - // First reduction chain - MOVQ $0x0007ffffffffffff, AX - SHLQ $0x0d, DI, SI - SHLQ $0x0d, R9, R8 - SHLQ $0x0d, R11, R10 - SHLQ $0x0d, R13, R12 - SHLQ $0x0d, R15, R14 - ANDQ AX, DI - IMUL3Q $0x13, R14, R14 - ADDQ R14, DI - ANDQ AX, R9 - ADDQ SI, R9 - ANDQ AX, R11 - ADDQ R8, R11 - ANDQ AX, R13 - ADDQ R10, R13 - ANDQ AX, R15 - ADDQ R12, R15 - - // Second reduction chain (carryPropagate) - MOVQ DI, SI - SHRQ $0x33, SI - MOVQ R9, R8 - SHRQ $0x33, R8 - MOVQ R11, R10 - SHRQ $0x33, R10 - MOVQ R13, R12 - SHRQ $0x33, R12 - MOVQ R15, R14 - SHRQ $0x33, R14 - ANDQ AX, DI - IMUL3Q $0x13, R14, R14 - ADDQ R14, DI - ANDQ AX, R9 - ADDQ SI, R9 - ANDQ AX, R11 - ADDQ R8, R11 - ANDQ AX, R13 - ADDQ R10, R13 - ANDQ AX, R15 - ADDQ R12, R15 - - // Store output - MOVQ out+0(FP), AX - MOVQ DI, (AX) - MOVQ R9, 8(AX) - MOVQ R11, 16(AX) - MOVQ R13, 24(AX) - MOVQ R15, 32(AX) - RET - -// func feSquare(out *Element, a *Element) -TEXT ·feSquare(SB), NOSPLIT, $0-16 - MOVQ a+8(FP), CX - - // r0 = l0×l0 - MOVQ (CX), AX - MULQ (CX) - MOVQ AX, SI - MOVQ DX, BX - - // r0 += 38×l1×l4 - MOVQ 8(CX), AX - IMUL3Q $0x26, AX, AX - MULQ 32(CX) - ADDQ AX, SI - ADCQ DX, BX - - // r0 += 38×l2×l3 - MOVQ 16(CX), AX - IMUL3Q $0x26, AX, AX - MULQ 24(CX) - ADDQ AX, SI - ADCQ DX, BX - - // r1 = 2×l0×l1 - MOVQ (CX), AX - SHLQ $0x01, AX - MULQ 8(CX) - MOVQ AX, R8 - MOVQ DX, DI - - // r1 += 38×l2×l4 - MOVQ 16(CX), AX - IMUL3Q $0x26, AX, AX - MULQ 32(CX) - ADDQ AX, R8 - ADCQ DX, DI - - // r1 += 19×l3×l3 - MOVQ 24(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 24(CX) - ADDQ AX, R8 - ADCQ DX, DI - - // r2 = 2×l0×l2 - MOVQ (CX), AX - SHLQ $0x01, AX - MULQ 16(CX) - MOVQ AX, R10 - MOVQ DX, R9 - - // r2 += l1×l1 - MOVQ 8(CX), AX - MULQ 8(CX) - ADDQ AX, R10 - ADCQ DX, R9 - - // r2 += 38×l3×l4 - MOVQ 24(CX), AX - IMUL3Q $0x26, AX, AX - MULQ 32(CX) - ADDQ AX, R10 - ADCQ DX, R9 - - // r3 = 2×l0×l3 - MOVQ (CX), AX - SHLQ $0x01, AX - MULQ 24(CX) - MOVQ AX, R12 - MOVQ DX, R11 - - // r3 += 2×l1×l2 - MOVQ 8(CX), AX - IMUL3Q $0x02, AX, AX - MULQ 16(CX) - ADDQ AX, R12 - ADCQ DX, R11 - - // r3 += 19×l4×l4 - MOVQ 32(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 32(CX) - ADDQ AX, R12 - ADCQ DX, R11 - - // r4 = 2×l0×l4 - MOVQ (CX), AX - SHLQ $0x01, AX - MULQ 32(CX) - MOVQ AX, R14 - MOVQ DX, R13 - - // r4 += 2×l1×l3 - MOVQ 8(CX), AX - IMUL3Q $0x02, AX, AX - MULQ 24(CX) - ADDQ AX, R14 - ADCQ DX, R13 - - // r4 += l2×l2 - MOVQ 16(CX), AX - MULQ 16(CX) - ADDQ AX, R14 - ADCQ DX, R13 - - // First reduction chain - MOVQ $0x0007ffffffffffff, AX - SHLQ $0x0d, SI, BX - SHLQ $0x0d, R8, DI - SHLQ $0x0d, R10, R9 - SHLQ $0x0d, R12, R11 - SHLQ $0x0d, R14, R13 - ANDQ AX, SI - IMUL3Q $0x13, R13, R13 - ADDQ R13, SI - ANDQ AX, R8 - ADDQ BX, R8 - ANDQ AX, R10 - ADDQ DI, R10 - ANDQ AX, R12 - ADDQ R9, R12 - ANDQ AX, R14 - ADDQ R11, R14 - - // Second reduction chain (carryPropagate) - MOVQ SI, BX - SHRQ $0x33, BX - MOVQ R8, DI - SHRQ $0x33, DI - MOVQ R10, R9 - SHRQ $0x33, R9 - MOVQ R12, R11 - SHRQ $0x33, R11 - MOVQ R14, R13 - SHRQ $0x33, R13 - ANDQ AX, SI - IMUL3Q $0x13, R13, R13 - ADDQ R13, SI - ANDQ AX, R8 - ADDQ BX, R8 - ANDQ AX, R10 - ADDQ DI, R10 - ANDQ AX, R12 - ADDQ R9, R12 - ANDQ AX, R14 - ADDQ R11, R14 - - // Store output - MOVQ out+0(FP), AX - MOVQ SI, (AX) - MOVQ R8, 8(AX) - MOVQ R10, 16(AX) - MOVQ R12, 24(AX) - MOVQ R14, 32(AX) - RET diff --git a/vendor/filippo.io/edwards25519/field/fe_amd64_noasm.go b/vendor/filippo.io/edwards25519/field/fe_amd64_noasm.go deleted file mode 100644 index ddb6c9b8f7..0000000000 --- a/vendor/filippo.io/edwards25519/field/fe_amd64_noasm.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !amd64 || !gc || purego -// +build !amd64 !gc purego - -package field - -func feMul(v, x, y *Element) { feMulGeneric(v, x, y) } - -func feSquare(v, x *Element) { feSquareGeneric(v, x) } diff --git a/vendor/filippo.io/edwards25519/field/fe_arm64.go b/vendor/filippo.io/edwards25519/field/fe_arm64.go deleted file mode 100644 index af459ef515..0000000000 --- a/vendor/filippo.io/edwards25519/field/fe_arm64.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build arm64 && gc && !purego -// +build arm64,gc,!purego - -package field - -//go:noescape -func carryPropagate(v *Element) - -func (v *Element) carryPropagate() *Element { - carryPropagate(v) - return v -} diff --git a/vendor/filippo.io/edwards25519/field/fe_arm64.s b/vendor/filippo.io/edwards25519/field/fe_arm64.s deleted file mode 100644 index 3126a43419..0000000000 --- a/vendor/filippo.io/edwards25519/field/fe_arm64.s +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build arm64 && gc && !purego - -#include "textflag.h" - -// carryPropagate works exactly like carryPropagateGeneric and uses the -// same AND, ADD, and LSR+MADD instructions emitted by the compiler, but -// avoids loading R0-R4 twice and uses LDP and STP. -// -// See https://golang.org/issues/43145 for the main compiler issue. -// -// func carryPropagate(v *Element) -TEXT ·carryPropagate(SB),NOFRAME|NOSPLIT,$0-8 - MOVD v+0(FP), R20 - - LDP 0(R20), (R0, R1) - LDP 16(R20), (R2, R3) - MOVD 32(R20), R4 - - AND $0x7ffffffffffff, R0, R10 - AND $0x7ffffffffffff, R1, R11 - AND $0x7ffffffffffff, R2, R12 - AND $0x7ffffffffffff, R3, R13 - AND $0x7ffffffffffff, R4, R14 - - ADD R0>>51, R11, R11 - ADD R1>>51, R12, R12 - ADD R2>>51, R13, R13 - ADD R3>>51, R14, R14 - // R4>>51 * 19 + R10 -> R10 - LSR $51, R4, R21 - MOVD $19, R22 - MADD R22, R10, R21, R10 - - STP (R10, R11), 0(R20) - STP (R12, R13), 16(R20) - MOVD R14, 32(R20) - - RET diff --git a/vendor/filippo.io/edwards25519/field/fe_arm64_noasm.go b/vendor/filippo.io/edwards25519/field/fe_arm64_noasm.go deleted file mode 100644 index 234a5b2e5d..0000000000 --- a/vendor/filippo.io/edwards25519/field/fe_arm64_noasm.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) 2021 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !arm64 || !gc || purego -// +build !arm64 !gc purego - -package field - -func (v *Element) carryPropagate() *Element { - return v.carryPropagateGeneric() -} diff --git a/vendor/filippo.io/edwards25519/field/fe_extra.go b/vendor/filippo.io/edwards25519/field/fe_extra.go deleted file mode 100644 index 1ef503b9a2..0000000000 --- a/vendor/filippo.io/edwards25519/field/fe_extra.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2021 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package field - -import "errors" - -// This file contains additional functionality that is not included in the -// upstream crypto/ed25519/edwards25519/field package. - -// SetWideBytes sets v to x, where x is a 64-byte little-endian encoding, which -// is reduced modulo the field order. If x is not of the right length, -// SetWideBytes returns nil and an error, and the receiver is unchanged. -// -// SetWideBytes is not necessary to select a uniformly distributed value, and is -// only provided for compatibility: SetBytes can be used instead as the chance -// of bias is less than 2⁻²⁵⁰. -func (v *Element) SetWideBytes(x []byte) (*Element, error) { - if len(x) != 64 { - return nil, errors.New("edwards25519: invalid SetWideBytes input size") - } - - // Split the 64 bytes into two elements, and extract the most significant - // bit of each, which is ignored by SetBytes. - lo, _ := new(Element).SetBytes(x[:32]) - loMSB := uint64(x[31] >> 7) - hi, _ := new(Element).SetBytes(x[32:]) - hiMSB := uint64(x[63] >> 7) - - // The output we want is - // - // v = lo + loMSB * 2²⁵⁵ + hi * 2²⁵⁶ + hiMSB * 2⁵¹¹ - // - // which applying the reduction identity comes out to - // - // v = lo + loMSB * 19 + hi * 2 * 19 + hiMSB * 2 * 19² - // - // l0 will be the sum of a 52 bits value (lo.l0), plus a 5 bits value - // (loMSB * 19), a 6 bits value (hi.l0 * 2 * 19), and a 10 bits value - // (hiMSB * 2 * 19²), so it fits in a uint64. - - v.l0 = lo.l0 + loMSB*19 + hi.l0*2*19 + hiMSB*2*19*19 - v.l1 = lo.l1 + hi.l1*2*19 - v.l2 = lo.l2 + hi.l2*2*19 - v.l3 = lo.l3 + hi.l3*2*19 - v.l4 = lo.l4 + hi.l4*2*19 - - return v.carryPropagate(), nil -} diff --git a/vendor/filippo.io/edwards25519/field/fe_generic.go b/vendor/filippo.io/edwards25519/field/fe_generic.go deleted file mode 100644 index 86f5fd9553..0000000000 --- a/vendor/filippo.io/edwards25519/field/fe_generic.go +++ /dev/null @@ -1,266 +0,0 @@ -// Copyright (c) 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package field - -import "math/bits" - -// uint128 holds a 128-bit number as two 64-bit limbs, for use with the -// bits.Mul64 and bits.Add64 intrinsics. -type uint128 struct { - lo, hi uint64 -} - -// mul64 returns a * b. -func mul64(a, b uint64) uint128 { - hi, lo := bits.Mul64(a, b) - return uint128{lo, hi} -} - -// addMul64 returns v + a * b. -func addMul64(v uint128, a, b uint64) uint128 { - hi, lo := bits.Mul64(a, b) - lo, c := bits.Add64(lo, v.lo, 0) - hi, _ = bits.Add64(hi, v.hi, c) - return uint128{lo, hi} -} - -// shiftRightBy51 returns a >> 51. a is assumed to be at most 115 bits. -func shiftRightBy51(a uint128) uint64 { - return (a.hi << (64 - 51)) | (a.lo >> 51) -} - -func feMulGeneric(v, a, b *Element) { - a0 := a.l0 - a1 := a.l1 - a2 := a.l2 - a3 := a.l3 - a4 := a.l4 - - b0 := b.l0 - b1 := b.l1 - b2 := b.l2 - b3 := b.l3 - b4 := b.l4 - - // Limb multiplication works like pen-and-paper columnar multiplication, but - // with 51-bit limbs instead of digits. - // - // a4 a3 a2 a1 a0 x - // b4 b3 b2 b1 b0 = - // ------------------------ - // a4b0 a3b0 a2b0 a1b0 a0b0 + - // a4b1 a3b1 a2b1 a1b1 a0b1 + - // a4b2 a3b2 a2b2 a1b2 a0b2 + - // a4b3 a3b3 a2b3 a1b3 a0b3 + - // a4b4 a3b4 a2b4 a1b4 a0b4 = - // ---------------------------------------------- - // r8 r7 r6 r5 r4 r3 r2 r1 r0 - // - // We can then use the reduction identity (a * 2²⁵⁵ + b = a * 19 + b) to - // reduce the limbs that would overflow 255 bits. r5 * 2²⁵⁵ becomes 19 * r5, - // r6 * 2³⁰⁶ becomes 19 * r6 * 2⁵¹, etc. - // - // Reduction can be carried out simultaneously to multiplication. For - // example, we do not compute r5: whenever the result of a multiplication - // belongs to r5, like a1b4, we multiply it by 19 and add the result to r0. - // - // a4b0 a3b0 a2b0 a1b0 a0b0 + - // a3b1 a2b1 a1b1 a0b1 19×a4b1 + - // a2b2 a1b2 a0b2 19×a4b2 19×a3b2 + - // a1b3 a0b3 19×a4b3 19×a3b3 19×a2b3 + - // a0b4 19×a4b4 19×a3b4 19×a2b4 19×a1b4 = - // -------------------------------------- - // r4 r3 r2 r1 r0 - // - // Finally we add up the columns into wide, overlapping limbs. - - a1_19 := a1 * 19 - a2_19 := a2 * 19 - a3_19 := a3 * 19 - a4_19 := a4 * 19 - - // r0 = a0×b0 + 19×(a1×b4 + a2×b3 + a3×b2 + a4×b1) - r0 := mul64(a0, b0) - r0 = addMul64(r0, a1_19, b4) - r0 = addMul64(r0, a2_19, b3) - r0 = addMul64(r0, a3_19, b2) - r0 = addMul64(r0, a4_19, b1) - - // r1 = a0×b1 + a1×b0 + 19×(a2×b4 + a3×b3 + a4×b2) - r1 := mul64(a0, b1) - r1 = addMul64(r1, a1, b0) - r1 = addMul64(r1, a2_19, b4) - r1 = addMul64(r1, a3_19, b3) - r1 = addMul64(r1, a4_19, b2) - - // r2 = a0×b2 + a1×b1 + a2×b0 + 19×(a3×b4 + a4×b3) - r2 := mul64(a0, b2) - r2 = addMul64(r2, a1, b1) - r2 = addMul64(r2, a2, b0) - r2 = addMul64(r2, a3_19, b4) - r2 = addMul64(r2, a4_19, b3) - - // r3 = a0×b3 + a1×b2 + a2×b1 + a3×b0 + 19×a4×b4 - r3 := mul64(a0, b3) - r3 = addMul64(r3, a1, b2) - r3 = addMul64(r3, a2, b1) - r3 = addMul64(r3, a3, b0) - r3 = addMul64(r3, a4_19, b4) - - // r4 = a0×b4 + a1×b3 + a2×b2 + a3×b1 + a4×b0 - r4 := mul64(a0, b4) - r4 = addMul64(r4, a1, b3) - r4 = addMul64(r4, a2, b2) - r4 = addMul64(r4, a3, b1) - r4 = addMul64(r4, a4, b0) - - // After the multiplication, we need to reduce (carry) the five coefficients - // to obtain a result with limbs that are at most slightly larger than 2⁵¹, - // to respect the Element invariant. - // - // Overall, the reduction works the same as carryPropagate, except with - // wider inputs: we take the carry for each coefficient by shifting it right - // by 51, and add it to the limb above it. The top carry is multiplied by 19 - // according to the reduction identity and added to the lowest limb. - // - // The largest coefficient (r0) will be at most 111 bits, which guarantees - // that all carries are at most 111 - 51 = 60 bits, which fits in a uint64. - // - // r0 = a0×b0 + 19×(a1×b4 + a2×b3 + a3×b2 + a4×b1) - // r0 < 2⁵²×2⁵² + 19×(2⁵²×2⁵² + 2⁵²×2⁵² + 2⁵²×2⁵² + 2⁵²×2⁵²) - // r0 < (1 + 19 × 4) × 2⁵² × 2⁵² - // r0 < 2⁷ × 2⁵² × 2⁵² - // r0 < 2¹¹¹ - // - // Moreover, the top coefficient (r4) is at most 107 bits, so c4 is at most - // 56 bits, and c4 * 19 is at most 61 bits, which again fits in a uint64 and - // allows us to easily apply the reduction identity. - // - // r4 = a0×b4 + a1×b3 + a2×b2 + a3×b1 + a4×b0 - // r4 < 5 × 2⁵² × 2⁵² - // r4 < 2¹⁰⁷ - // - - c0 := shiftRightBy51(r0) - c1 := shiftRightBy51(r1) - c2 := shiftRightBy51(r2) - c3 := shiftRightBy51(r3) - c4 := shiftRightBy51(r4) - - rr0 := r0.lo&maskLow51Bits + c4*19 - rr1 := r1.lo&maskLow51Bits + c0 - rr2 := r2.lo&maskLow51Bits + c1 - rr3 := r3.lo&maskLow51Bits + c2 - rr4 := r4.lo&maskLow51Bits + c3 - - // Now all coefficients fit into 64-bit registers but are still too large to - // be passed around as an Element. We therefore do one last carry chain, - // where the carries will be small enough to fit in the wiggle room above 2⁵¹. - *v = Element{rr0, rr1, rr2, rr3, rr4} - v.carryPropagate() -} - -func feSquareGeneric(v, a *Element) { - l0 := a.l0 - l1 := a.l1 - l2 := a.l2 - l3 := a.l3 - l4 := a.l4 - - // Squaring works precisely like multiplication above, but thanks to its - // symmetry we get to group a few terms together. - // - // l4 l3 l2 l1 l0 x - // l4 l3 l2 l1 l0 = - // ------------------------ - // l4l0 l3l0 l2l0 l1l0 l0l0 + - // l4l1 l3l1 l2l1 l1l1 l0l1 + - // l4l2 l3l2 l2l2 l1l2 l0l2 + - // l4l3 l3l3 l2l3 l1l3 l0l3 + - // l4l4 l3l4 l2l4 l1l4 l0l4 = - // ---------------------------------------------- - // r8 r7 r6 r5 r4 r3 r2 r1 r0 - // - // l4l0 l3l0 l2l0 l1l0 l0l0 + - // l3l1 l2l1 l1l1 l0l1 19×l4l1 + - // l2l2 l1l2 l0l2 19×l4l2 19×l3l2 + - // l1l3 l0l3 19×l4l3 19×l3l3 19×l2l3 + - // l0l4 19×l4l4 19×l3l4 19×l2l4 19×l1l4 = - // -------------------------------------- - // r4 r3 r2 r1 r0 - // - // With precomputed 2×, 19×, and 2×19× terms, we can compute each limb with - // only three Mul64 and four Add64, instead of five and eight. - - l0_2 := l0 * 2 - l1_2 := l1 * 2 - - l1_38 := l1 * 38 - l2_38 := l2 * 38 - l3_38 := l3 * 38 - - l3_19 := l3 * 19 - l4_19 := l4 * 19 - - // r0 = l0×l0 + 19×(l1×l4 + l2×l3 + l3×l2 + l4×l1) = l0×l0 + 19×2×(l1×l4 + l2×l3) - r0 := mul64(l0, l0) - r0 = addMul64(r0, l1_38, l4) - r0 = addMul64(r0, l2_38, l3) - - // r1 = l0×l1 + l1×l0 + 19×(l2×l4 + l3×l3 + l4×l2) = 2×l0×l1 + 19×2×l2×l4 + 19×l3×l3 - r1 := mul64(l0_2, l1) - r1 = addMul64(r1, l2_38, l4) - r1 = addMul64(r1, l3_19, l3) - - // r2 = l0×l2 + l1×l1 + l2×l0 + 19×(l3×l4 + l4×l3) = 2×l0×l2 + l1×l1 + 19×2×l3×l4 - r2 := mul64(l0_2, l2) - r2 = addMul64(r2, l1, l1) - r2 = addMul64(r2, l3_38, l4) - - // r3 = l0×l3 + l1×l2 + l2×l1 + l3×l0 + 19×l4×l4 = 2×l0×l3 + 2×l1×l2 + 19×l4×l4 - r3 := mul64(l0_2, l3) - r3 = addMul64(r3, l1_2, l2) - r3 = addMul64(r3, l4_19, l4) - - // r4 = l0×l4 + l1×l3 + l2×l2 + l3×l1 + l4×l0 = 2×l0×l4 + 2×l1×l3 + l2×l2 - r4 := mul64(l0_2, l4) - r4 = addMul64(r4, l1_2, l3) - r4 = addMul64(r4, l2, l2) - - c0 := shiftRightBy51(r0) - c1 := shiftRightBy51(r1) - c2 := shiftRightBy51(r2) - c3 := shiftRightBy51(r3) - c4 := shiftRightBy51(r4) - - rr0 := r0.lo&maskLow51Bits + c4*19 - rr1 := r1.lo&maskLow51Bits + c0 - rr2 := r2.lo&maskLow51Bits + c1 - rr3 := r3.lo&maskLow51Bits + c2 - rr4 := r4.lo&maskLow51Bits + c3 - - *v = Element{rr0, rr1, rr2, rr3, rr4} - v.carryPropagate() -} - -// carryPropagateGeneric brings the limbs below 52 bits by applying the reduction -// identity (a * 2²⁵⁵ + b = a * 19 + b) to the l4 carry. -func (v *Element) carryPropagateGeneric() *Element { - c0 := v.l0 >> 51 - c1 := v.l1 >> 51 - c2 := v.l2 >> 51 - c3 := v.l3 >> 51 - c4 := v.l4 >> 51 - - // c4 is at most 64 - 51 = 13 bits, so c4*19 is at most 18 bits, and - // the final l0 will be at most 52 bits. Similarly for the rest. - v.l0 = v.l0&maskLow51Bits + c4*19 - v.l1 = v.l1&maskLow51Bits + c0 - v.l2 = v.l2&maskLow51Bits + c1 - v.l3 = v.l3&maskLow51Bits + c2 - v.l4 = v.l4&maskLow51Bits + c3 - - return v -} diff --git a/vendor/filippo.io/edwards25519/scalar.go b/vendor/filippo.io/edwards25519/scalar.go deleted file mode 100644 index 3fd1653877..0000000000 --- a/vendor/filippo.io/edwards25519/scalar.go +++ /dev/null @@ -1,343 +0,0 @@ -// Copyright (c) 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package edwards25519 - -import ( - "encoding/binary" - "errors" -) - -// A Scalar is an integer modulo -// -// l = 2^252 + 27742317777372353535851937790883648493 -// -// which is the prime order of the edwards25519 group. -// -// This type works similarly to math/big.Int, and all arguments and -// receivers are allowed to alias. -// -// The zero value is a valid zero element. -type Scalar struct { - // s is the scalar in the Montgomery domain, in the format of the - // fiat-crypto implementation. - s fiatScalarMontgomeryDomainFieldElement -} - -// The field implementation in scalar_fiat.go is generated by the fiat-crypto -// project (https://github.com/mit-plv/fiat-crypto) at version v0.0.9 (23d2dbc) -// from a formally verified model. -// -// fiat-crypto code comes under the following license. -// -// Copyright (c) 2015-2020 The fiat-crypto Authors. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// -// THIS SOFTWARE IS PROVIDED BY the fiat-crypto authors "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Berkeley Software Design, -// Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// - -// NewScalar returns a new zero Scalar. -func NewScalar() *Scalar { - return &Scalar{} -} - -// MultiplyAdd sets s = x * y + z mod l, and returns s. It is equivalent to -// using Multiply and then Add. -func (s *Scalar) MultiplyAdd(x, y, z *Scalar) *Scalar { - // Make a copy of z in case it aliases s. - zCopy := new(Scalar).Set(z) - return s.Multiply(x, y).Add(s, zCopy) -} - -// Add sets s = x + y mod l, and returns s. -func (s *Scalar) Add(x, y *Scalar) *Scalar { - // s = 1 * x + y mod l - fiatScalarAdd(&s.s, &x.s, &y.s) - return s -} - -// Subtract sets s = x - y mod l, and returns s. -func (s *Scalar) Subtract(x, y *Scalar) *Scalar { - // s = -1 * y + x mod l - fiatScalarSub(&s.s, &x.s, &y.s) - return s -} - -// Negate sets s = -x mod l, and returns s. -func (s *Scalar) Negate(x *Scalar) *Scalar { - // s = -1 * x + 0 mod l - fiatScalarOpp(&s.s, &x.s) - return s -} - -// Multiply sets s = x * y mod l, and returns s. -func (s *Scalar) Multiply(x, y *Scalar) *Scalar { - // s = x * y + 0 mod l - fiatScalarMul(&s.s, &x.s, &y.s) - return s -} - -// Set sets s = x, and returns s. -func (s *Scalar) Set(x *Scalar) *Scalar { - *s = *x - return s -} - -// SetUniformBytes sets s = x mod l, where x is a 64-byte little-endian integer. -// If x is not of the right length, SetUniformBytes returns nil and an error, -// and the receiver is unchanged. -// -// SetUniformBytes can be used to set s to a uniformly distributed value given -// 64 uniformly distributed random bytes. -func (s *Scalar) SetUniformBytes(x []byte) (*Scalar, error) { - if len(x) != 64 { - return nil, errors.New("edwards25519: invalid SetUniformBytes input length") - } - - // We have a value x of 512 bits, but our fiatScalarFromBytes function - // expects an input lower than l, which is a little over 252 bits. - // - // Instead of writing a reduction function that operates on wider inputs, we - // can interpret x as the sum of three shorter values a, b, and c. - // - // x = a + b * 2^168 + c * 2^336 mod l - // - // We then precompute 2^168 and 2^336 modulo l, and perform the reduction - // with two multiplications and two additions. - - s.setShortBytes(x[:21]) - t := new(Scalar).setShortBytes(x[21:42]) - s.Add(s, t.Multiply(t, scalarTwo168)) - t.setShortBytes(x[42:]) - s.Add(s, t.Multiply(t, scalarTwo336)) - - return s, nil -} - -// scalarTwo168 and scalarTwo336 are 2^168 and 2^336 modulo l, encoded as a -// fiatScalarMontgomeryDomainFieldElement, which is a little-endian 4-limb value -// in the 2^256 Montgomery domain. -var scalarTwo168 = &Scalar{s: [4]uint64{0x5b8ab432eac74798, 0x38afddd6de59d5d7, - 0xa2c131b399411b7c, 0x6329a7ed9ce5a30}} -var scalarTwo336 = &Scalar{s: [4]uint64{0xbd3d108e2b35ecc5, 0x5c3a3718bdf9c90b, - 0x63aa97a331b4f2ee, 0x3d217f5be65cb5c}} - -// setShortBytes sets s = x mod l, where x is a little-endian integer shorter -// than 32 bytes. -func (s *Scalar) setShortBytes(x []byte) *Scalar { - if len(x) >= 32 { - panic("edwards25519: internal error: setShortBytes called with a long string") - } - var buf [32]byte - copy(buf[:], x) - fiatScalarFromBytes((*[4]uint64)(&s.s), &buf) - fiatScalarToMontgomery(&s.s, (*fiatScalarNonMontgomeryDomainFieldElement)(&s.s)) - return s -} - -// SetCanonicalBytes sets s = x, where x is a 32-byte little-endian encoding of -// s, and returns s. If x is not a canonical encoding of s, SetCanonicalBytes -// returns nil and an error, and the receiver is unchanged. -func (s *Scalar) SetCanonicalBytes(x []byte) (*Scalar, error) { - if len(x) != 32 { - return nil, errors.New("invalid scalar length") - } - if !isReduced(x) { - return nil, errors.New("invalid scalar encoding") - } - - fiatScalarFromBytes((*[4]uint64)(&s.s), (*[32]byte)(x)) - fiatScalarToMontgomery(&s.s, (*fiatScalarNonMontgomeryDomainFieldElement)(&s.s)) - - return s, nil -} - -// scalarMinusOneBytes is l - 1 in little endian. -var scalarMinusOneBytes = [32]byte{236, 211, 245, 92, 26, 99, 18, 88, 214, 156, 247, 162, 222, 249, 222, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16} - -// isReduced returns whether the given scalar in 32-byte little endian encoded -// form is reduced modulo l. -func isReduced(s []byte) bool { - if len(s) != 32 { - return false - } - - for i := len(s) - 1; i >= 0; i-- { - switch { - case s[i] > scalarMinusOneBytes[i]: - return false - case s[i] < scalarMinusOneBytes[i]: - return true - } - } - return true -} - -// SetBytesWithClamping applies the buffer pruning described in RFC 8032, -// Section 5.1.5 (also known as clamping) and sets s to the result. The input -// must be 32 bytes, and it is not modified. If x is not of the right length, -// SetBytesWithClamping returns nil and an error, and the receiver is unchanged. -// -// Note that since Scalar values are always reduced modulo the prime order of -// the curve, the resulting value will not preserve any of the cofactor-clearing -// properties that clamping is meant to provide. It will however work as -// expected as long as it is applied to points on the prime order subgroup, like -// in Ed25519. In fact, it is lost to history why RFC 8032 adopted the -// irrelevant RFC 7748 clamping, but it is now required for compatibility. -func (s *Scalar) SetBytesWithClamping(x []byte) (*Scalar, error) { - // The description above omits the purpose of the high bits of the clamping - // for brevity, but those are also lost to reductions, and are also - // irrelevant to edwards25519 as they protect against a specific - // implementation bug that was once observed in a generic Montgomery ladder. - if len(x) != 32 { - return nil, errors.New("edwards25519: invalid SetBytesWithClamping input length") - } - - // We need to use the wide reduction from SetUniformBytes, since clamping - // sets the 2^254 bit, making the value higher than the order. - var wideBytes [64]byte - copy(wideBytes[:], x[:]) - wideBytes[0] &= 248 - wideBytes[31] &= 63 - wideBytes[31] |= 64 - return s.SetUniformBytes(wideBytes[:]) -} - -// Bytes returns the canonical 32-byte little-endian encoding of s. -func (s *Scalar) Bytes() []byte { - // This function is outlined to make the allocations inline in the caller - // rather than happen on the heap. - var encoded [32]byte - return s.bytes(&encoded) -} - -func (s *Scalar) bytes(out *[32]byte) []byte { - var ss fiatScalarNonMontgomeryDomainFieldElement - fiatScalarFromMontgomery(&ss, &s.s) - fiatScalarToBytes(out, (*[4]uint64)(&ss)) - return out[:] -} - -// Equal returns 1 if s and t are equal, and 0 otherwise. -func (s *Scalar) Equal(t *Scalar) int { - var diff fiatScalarMontgomeryDomainFieldElement - fiatScalarSub(&diff, &s.s, &t.s) - var nonzero uint64 - fiatScalarNonzero(&nonzero, (*[4]uint64)(&diff)) - nonzero |= nonzero >> 32 - nonzero |= nonzero >> 16 - nonzero |= nonzero >> 8 - nonzero |= nonzero >> 4 - nonzero |= nonzero >> 2 - nonzero |= nonzero >> 1 - return int(^nonzero) & 1 -} - -// nonAdjacentForm computes a width-w non-adjacent form for this scalar. -// -// w must be between 2 and 8, or nonAdjacentForm will panic. -func (s *Scalar) nonAdjacentForm(w uint) [256]int8 { - // This implementation is adapted from the one - // in curve25519-dalek and is documented there: - // https://github.com/dalek-cryptography/curve25519-dalek/blob/f630041af28e9a405255f98a8a93adca18e4315b/src/scalar.rs#L800-L871 - b := s.Bytes() - if b[31] > 127 { - panic("scalar has high bit set illegally") - } - if w < 2 { - panic("w must be at least 2 by the definition of NAF") - } else if w > 8 { - panic("NAF digits must fit in int8") - } - - var naf [256]int8 - var digits [5]uint64 - - for i := 0; i < 4; i++ { - digits[i] = binary.LittleEndian.Uint64(b[i*8:]) - } - - width := uint64(1 << w) - windowMask := uint64(width - 1) - - pos := uint(0) - carry := uint64(0) - for pos < 256 { - indexU64 := pos / 64 - indexBit := pos % 64 - var bitBuf uint64 - if indexBit < 64-w { - // This window's bits are contained in a single u64 - bitBuf = digits[indexU64] >> indexBit - } else { - // Combine the current 64 bits with bits from the next 64 - bitBuf = (digits[indexU64] >> indexBit) | (digits[1+indexU64] << (64 - indexBit)) - } - - // Add carry into the current window - window := carry + (bitBuf & windowMask) - - if window&1 == 0 { - // If the window value is even, preserve the carry and continue. - // Why is the carry preserved? - // If carry == 0 and window & 1 == 0, - // then the next carry should be 0 - // If carry == 1 and window & 1 == 0, - // then bit_buf & 1 == 1 so the next carry should be 1 - pos += 1 - continue - } - - if window < width/2 { - carry = 0 - naf[pos] = int8(window) - } else { - carry = 1 - naf[pos] = int8(window) - int8(width) - } - - pos += w - } - return naf -} - -func (s *Scalar) signedRadix16() [64]int8 { - b := s.Bytes() - if b[31] > 127 { - panic("scalar has high bit set illegally") - } - - var digits [64]int8 - - // Compute unsigned radix-16 digits: - for i := 0; i < 32; i++ { - digits[2*i] = int8(b[i] & 15) - digits[2*i+1] = int8((b[i] >> 4) & 15) - } - - // Recenter coefficients: - for i := 0; i < 63; i++ { - carry := (digits[i] + 8) >> 4 - digits[i] -= carry << 4 - digits[i+1] += carry - } - - return digits -} diff --git a/vendor/filippo.io/edwards25519/scalar_fiat.go b/vendor/filippo.io/edwards25519/scalar_fiat.go deleted file mode 100644 index 2e5782b605..0000000000 --- a/vendor/filippo.io/edwards25519/scalar_fiat.go +++ /dev/null @@ -1,1147 +0,0 @@ -// Code generated by Fiat Cryptography. DO NOT EDIT. -// -// Autogenerated: word_by_word_montgomery --lang Go --cmovznz-by-mul --relax-primitive-carry-to-bitwidth 32,64 --public-function-case camelCase --public-type-case camelCase --private-function-case camelCase --private-type-case camelCase --doc-text-before-function-name '' --doc-newline-before-package-declaration --doc-prepend-header 'Code generated by Fiat Cryptography. DO NOT EDIT.' --package-name edwards25519 Scalar 64 '2^252 + 27742317777372353535851937790883648493' mul add sub opp nonzero from_montgomery to_montgomery to_bytes from_bytes -// -// curve description: Scalar -// -// machine_wordsize = 64 (from "64") -// -// requested operations: mul, add, sub, opp, nonzero, from_montgomery, to_montgomery, to_bytes, from_bytes -// -// m = 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed (from "2^252 + 27742317777372353535851937790883648493") -// -// -// -// NOTE: In addition to the bounds specified above each function, all -// -// functions synthesized for this Montgomery arithmetic require the -// -// input to be strictly less than the prime modulus (m), and also -// -// require the input to be in the unique saturated representation. -// -// All functions also ensure that these two properties are true of -// -// return values. -// -// -// -// Computed values: -// -// eval z = z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) -// -// bytes_eval z = z[0] + (z[1] << 8) + (z[2] << 16) + (z[3] << 24) + (z[4] << 32) + (z[5] << 40) + (z[6] << 48) + (z[7] << 56) + (z[8] << 64) + (z[9] << 72) + (z[10] << 80) + (z[11] << 88) + (z[12] << 96) + (z[13] << 104) + (z[14] << 112) + (z[15] << 120) + (z[16] << 128) + (z[17] << 136) + (z[18] << 144) + (z[19] << 152) + (z[20] << 160) + (z[21] << 168) + (z[22] << 176) + (z[23] << 184) + (z[24] << 192) + (z[25] << 200) + (z[26] << 208) + (z[27] << 216) + (z[28] << 224) + (z[29] << 232) + (z[30] << 240) + (z[31] << 248) -// -// twos_complement_eval z = let x1 := z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) in -// -// if x1 & (2^256-1) < 2^255 then x1 & (2^256-1) else (x1 & (2^256-1)) - 2^256 - -package edwards25519 - -import "math/bits" - -type fiatScalarUint1 uint64 // We use uint64 instead of a more narrow type for performance reasons; see https://github.com/mit-plv/fiat-crypto/pull/1006#issuecomment-892625927 -type fiatScalarInt1 int64 // We use uint64 instead of a more narrow type for performance reasons; see https://github.com/mit-plv/fiat-crypto/pull/1006#issuecomment-892625927 - -// The type fiatScalarMontgomeryDomainFieldElement is a field element in the Montgomery domain. -// -// Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -type fiatScalarMontgomeryDomainFieldElement [4]uint64 - -// The type fiatScalarNonMontgomeryDomainFieldElement is a field element NOT in the Montgomery domain. -// -// Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -type fiatScalarNonMontgomeryDomainFieldElement [4]uint64 - -// fiatScalarCmovznzU64 is a single-word conditional move. -// -// Postconditions: -// -// out1 = (if arg1 = 0 then arg2 else arg3) -// -// Input Bounds: -// -// arg1: [0x0 ~> 0x1] -// arg2: [0x0 ~> 0xffffffffffffffff] -// arg3: [0x0 ~> 0xffffffffffffffff] -// -// Output Bounds: -// -// out1: [0x0 ~> 0xffffffffffffffff] -func fiatScalarCmovznzU64(out1 *uint64, arg1 fiatScalarUint1, arg2 uint64, arg3 uint64) { - x1 := (uint64(arg1) * 0xffffffffffffffff) - x2 := ((x1 & arg3) | ((^x1) & arg2)) - *out1 = x2 -} - -// fiatScalarMul multiplies two field elements in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// 0 ≤ eval arg2 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m -// 0 ≤ eval out1 < m -func fiatScalarMul(out1 *fiatScalarMontgomeryDomainFieldElement, arg1 *fiatScalarMontgomeryDomainFieldElement, arg2 *fiatScalarMontgomeryDomainFieldElement) { - x1 := arg1[1] - x2 := arg1[2] - x3 := arg1[3] - x4 := arg1[0] - var x5 uint64 - var x6 uint64 - x6, x5 = bits.Mul64(x4, arg2[3]) - var x7 uint64 - var x8 uint64 - x8, x7 = bits.Mul64(x4, arg2[2]) - var x9 uint64 - var x10 uint64 - x10, x9 = bits.Mul64(x4, arg2[1]) - var x11 uint64 - var x12 uint64 - x12, x11 = bits.Mul64(x4, arg2[0]) - var x13 uint64 - var x14 uint64 - x13, x14 = bits.Add64(x12, x9, uint64(0x0)) - var x15 uint64 - var x16 uint64 - x15, x16 = bits.Add64(x10, x7, uint64(fiatScalarUint1(x14))) - var x17 uint64 - var x18 uint64 - x17, x18 = bits.Add64(x8, x5, uint64(fiatScalarUint1(x16))) - x19 := (uint64(fiatScalarUint1(x18)) + x6) - var x20 uint64 - _, x20 = bits.Mul64(x11, 0xd2b51da312547e1b) - var x22 uint64 - var x23 uint64 - x23, x22 = bits.Mul64(x20, 0x1000000000000000) - var x24 uint64 - var x25 uint64 - x25, x24 = bits.Mul64(x20, 0x14def9dea2f79cd6) - var x26 uint64 - var x27 uint64 - x27, x26 = bits.Mul64(x20, 0x5812631a5cf5d3ed) - var x28 uint64 - var x29 uint64 - x28, x29 = bits.Add64(x27, x24, uint64(0x0)) - x30 := (uint64(fiatScalarUint1(x29)) + x25) - var x32 uint64 - _, x32 = bits.Add64(x11, x26, uint64(0x0)) - var x33 uint64 - var x34 uint64 - x33, x34 = bits.Add64(x13, x28, uint64(fiatScalarUint1(x32))) - var x35 uint64 - var x36 uint64 - x35, x36 = bits.Add64(x15, x30, uint64(fiatScalarUint1(x34))) - var x37 uint64 - var x38 uint64 - x37, x38 = bits.Add64(x17, x22, uint64(fiatScalarUint1(x36))) - var x39 uint64 - var x40 uint64 - x39, x40 = bits.Add64(x19, x23, uint64(fiatScalarUint1(x38))) - var x41 uint64 - var x42 uint64 - x42, x41 = bits.Mul64(x1, arg2[3]) - var x43 uint64 - var x44 uint64 - x44, x43 = bits.Mul64(x1, arg2[2]) - var x45 uint64 - var x46 uint64 - x46, x45 = bits.Mul64(x1, arg2[1]) - var x47 uint64 - var x48 uint64 - x48, x47 = bits.Mul64(x1, arg2[0]) - var x49 uint64 - var x50 uint64 - x49, x50 = bits.Add64(x48, x45, uint64(0x0)) - var x51 uint64 - var x52 uint64 - x51, x52 = bits.Add64(x46, x43, uint64(fiatScalarUint1(x50))) - var x53 uint64 - var x54 uint64 - x53, x54 = bits.Add64(x44, x41, uint64(fiatScalarUint1(x52))) - x55 := (uint64(fiatScalarUint1(x54)) + x42) - var x56 uint64 - var x57 uint64 - x56, x57 = bits.Add64(x33, x47, uint64(0x0)) - var x58 uint64 - var x59 uint64 - x58, x59 = bits.Add64(x35, x49, uint64(fiatScalarUint1(x57))) - var x60 uint64 - var x61 uint64 - x60, x61 = bits.Add64(x37, x51, uint64(fiatScalarUint1(x59))) - var x62 uint64 - var x63 uint64 - x62, x63 = bits.Add64(x39, x53, uint64(fiatScalarUint1(x61))) - var x64 uint64 - var x65 uint64 - x64, x65 = bits.Add64(uint64(fiatScalarUint1(x40)), x55, uint64(fiatScalarUint1(x63))) - var x66 uint64 - _, x66 = bits.Mul64(x56, 0xd2b51da312547e1b) - var x68 uint64 - var x69 uint64 - x69, x68 = bits.Mul64(x66, 0x1000000000000000) - var x70 uint64 - var x71 uint64 - x71, x70 = bits.Mul64(x66, 0x14def9dea2f79cd6) - var x72 uint64 - var x73 uint64 - x73, x72 = bits.Mul64(x66, 0x5812631a5cf5d3ed) - var x74 uint64 - var x75 uint64 - x74, x75 = bits.Add64(x73, x70, uint64(0x0)) - x76 := (uint64(fiatScalarUint1(x75)) + x71) - var x78 uint64 - _, x78 = bits.Add64(x56, x72, uint64(0x0)) - var x79 uint64 - var x80 uint64 - x79, x80 = bits.Add64(x58, x74, uint64(fiatScalarUint1(x78))) - var x81 uint64 - var x82 uint64 - x81, x82 = bits.Add64(x60, x76, uint64(fiatScalarUint1(x80))) - var x83 uint64 - var x84 uint64 - x83, x84 = bits.Add64(x62, x68, uint64(fiatScalarUint1(x82))) - var x85 uint64 - var x86 uint64 - x85, x86 = bits.Add64(x64, x69, uint64(fiatScalarUint1(x84))) - x87 := (uint64(fiatScalarUint1(x86)) + uint64(fiatScalarUint1(x65))) - var x88 uint64 - var x89 uint64 - x89, x88 = bits.Mul64(x2, arg2[3]) - var x90 uint64 - var x91 uint64 - x91, x90 = bits.Mul64(x2, arg2[2]) - var x92 uint64 - var x93 uint64 - x93, x92 = bits.Mul64(x2, arg2[1]) - var x94 uint64 - var x95 uint64 - x95, x94 = bits.Mul64(x2, arg2[0]) - var x96 uint64 - var x97 uint64 - x96, x97 = bits.Add64(x95, x92, uint64(0x0)) - var x98 uint64 - var x99 uint64 - x98, x99 = bits.Add64(x93, x90, uint64(fiatScalarUint1(x97))) - var x100 uint64 - var x101 uint64 - x100, x101 = bits.Add64(x91, x88, uint64(fiatScalarUint1(x99))) - x102 := (uint64(fiatScalarUint1(x101)) + x89) - var x103 uint64 - var x104 uint64 - x103, x104 = bits.Add64(x79, x94, uint64(0x0)) - var x105 uint64 - var x106 uint64 - x105, x106 = bits.Add64(x81, x96, uint64(fiatScalarUint1(x104))) - var x107 uint64 - var x108 uint64 - x107, x108 = bits.Add64(x83, x98, uint64(fiatScalarUint1(x106))) - var x109 uint64 - var x110 uint64 - x109, x110 = bits.Add64(x85, x100, uint64(fiatScalarUint1(x108))) - var x111 uint64 - var x112 uint64 - x111, x112 = bits.Add64(x87, x102, uint64(fiatScalarUint1(x110))) - var x113 uint64 - _, x113 = bits.Mul64(x103, 0xd2b51da312547e1b) - var x115 uint64 - var x116 uint64 - x116, x115 = bits.Mul64(x113, 0x1000000000000000) - var x117 uint64 - var x118 uint64 - x118, x117 = bits.Mul64(x113, 0x14def9dea2f79cd6) - var x119 uint64 - var x120 uint64 - x120, x119 = bits.Mul64(x113, 0x5812631a5cf5d3ed) - var x121 uint64 - var x122 uint64 - x121, x122 = bits.Add64(x120, x117, uint64(0x0)) - x123 := (uint64(fiatScalarUint1(x122)) + x118) - var x125 uint64 - _, x125 = bits.Add64(x103, x119, uint64(0x0)) - var x126 uint64 - var x127 uint64 - x126, x127 = bits.Add64(x105, x121, uint64(fiatScalarUint1(x125))) - var x128 uint64 - var x129 uint64 - x128, x129 = bits.Add64(x107, x123, uint64(fiatScalarUint1(x127))) - var x130 uint64 - var x131 uint64 - x130, x131 = bits.Add64(x109, x115, uint64(fiatScalarUint1(x129))) - var x132 uint64 - var x133 uint64 - x132, x133 = bits.Add64(x111, x116, uint64(fiatScalarUint1(x131))) - x134 := (uint64(fiatScalarUint1(x133)) + uint64(fiatScalarUint1(x112))) - var x135 uint64 - var x136 uint64 - x136, x135 = bits.Mul64(x3, arg2[3]) - var x137 uint64 - var x138 uint64 - x138, x137 = bits.Mul64(x3, arg2[2]) - var x139 uint64 - var x140 uint64 - x140, x139 = bits.Mul64(x3, arg2[1]) - var x141 uint64 - var x142 uint64 - x142, x141 = bits.Mul64(x3, arg2[0]) - var x143 uint64 - var x144 uint64 - x143, x144 = bits.Add64(x142, x139, uint64(0x0)) - var x145 uint64 - var x146 uint64 - x145, x146 = bits.Add64(x140, x137, uint64(fiatScalarUint1(x144))) - var x147 uint64 - var x148 uint64 - x147, x148 = bits.Add64(x138, x135, uint64(fiatScalarUint1(x146))) - x149 := (uint64(fiatScalarUint1(x148)) + x136) - var x150 uint64 - var x151 uint64 - x150, x151 = bits.Add64(x126, x141, uint64(0x0)) - var x152 uint64 - var x153 uint64 - x152, x153 = bits.Add64(x128, x143, uint64(fiatScalarUint1(x151))) - var x154 uint64 - var x155 uint64 - x154, x155 = bits.Add64(x130, x145, uint64(fiatScalarUint1(x153))) - var x156 uint64 - var x157 uint64 - x156, x157 = bits.Add64(x132, x147, uint64(fiatScalarUint1(x155))) - var x158 uint64 - var x159 uint64 - x158, x159 = bits.Add64(x134, x149, uint64(fiatScalarUint1(x157))) - var x160 uint64 - _, x160 = bits.Mul64(x150, 0xd2b51da312547e1b) - var x162 uint64 - var x163 uint64 - x163, x162 = bits.Mul64(x160, 0x1000000000000000) - var x164 uint64 - var x165 uint64 - x165, x164 = bits.Mul64(x160, 0x14def9dea2f79cd6) - var x166 uint64 - var x167 uint64 - x167, x166 = bits.Mul64(x160, 0x5812631a5cf5d3ed) - var x168 uint64 - var x169 uint64 - x168, x169 = bits.Add64(x167, x164, uint64(0x0)) - x170 := (uint64(fiatScalarUint1(x169)) + x165) - var x172 uint64 - _, x172 = bits.Add64(x150, x166, uint64(0x0)) - var x173 uint64 - var x174 uint64 - x173, x174 = bits.Add64(x152, x168, uint64(fiatScalarUint1(x172))) - var x175 uint64 - var x176 uint64 - x175, x176 = bits.Add64(x154, x170, uint64(fiatScalarUint1(x174))) - var x177 uint64 - var x178 uint64 - x177, x178 = bits.Add64(x156, x162, uint64(fiatScalarUint1(x176))) - var x179 uint64 - var x180 uint64 - x179, x180 = bits.Add64(x158, x163, uint64(fiatScalarUint1(x178))) - x181 := (uint64(fiatScalarUint1(x180)) + uint64(fiatScalarUint1(x159))) - var x182 uint64 - var x183 uint64 - x182, x183 = bits.Sub64(x173, 0x5812631a5cf5d3ed, uint64(0x0)) - var x184 uint64 - var x185 uint64 - x184, x185 = bits.Sub64(x175, 0x14def9dea2f79cd6, uint64(fiatScalarUint1(x183))) - var x186 uint64 - var x187 uint64 - x186, x187 = bits.Sub64(x177, uint64(0x0), uint64(fiatScalarUint1(x185))) - var x188 uint64 - var x189 uint64 - x188, x189 = bits.Sub64(x179, 0x1000000000000000, uint64(fiatScalarUint1(x187))) - var x191 uint64 - _, x191 = bits.Sub64(x181, uint64(0x0), uint64(fiatScalarUint1(x189))) - var x192 uint64 - fiatScalarCmovznzU64(&x192, fiatScalarUint1(x191), x182, x173) - var x193 uint64 - fiatScalarCmovznzU64(&x193, fiatScalarUint1(x191), x184, x175) - var x194 uint64 - fiatScalarCmovznzU64(&x194, fiatScalarUint1(x191), x186, x177) - var x195 uint64 - fiatScalarCmovznzU64(&x195, fiatScalarUint1(x191), x188, x179) - out1[0] = x192 - out1[1] = x193 - out1[2] = x194 - out1[3] = x195 -} - -// fiatScalarAdd adds two field elements in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// 0 ≤ eval arg2 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m -// 0 ≤ eval out1 < m -func fiatScalarAdd(out1 *fiatScalarMontgomeryDomainFieldElement, arg1 *fiatScalarMontgomeryDomainFieldElement, arg2 *fiatScalarMontgomeryDomainFieldElement) { - var x1 uint64 - var x2 uint64 - x1, x2 = bits.Add64(arg1[0], arg2[0], uint64(0x0)) - var x3 uint64 - var x4 uint64 - x3, x4 = bits.Add64(arg1[1], arg2[1], uint64(fiatScalarUint1(x2))) - var x5 uint64 - var x6 uint64 - x5, x6 = bits.Add64(arg1[2], arg2[2], uint64(fiatScalarUint1(x4))) - var x7 uint64 - var x8 uint64 - x7, x8 = bits.Add64(arg1[3], arg2[3], uint64(fiatScalarUint1(x6))) - var x9 uint64 - var x10 uint64 - x9, x10 = bits.Sub64(x1, 0x5812631a5cf5d3ed, uint64(0x0)) - var x11 uint64 - var x12 uint64 - x11, x12 = bits.Sub64(x3, 0x14def9dea2f79cd6, uint64(fiatScalarUint1(x10))) - var x13 uint64 - var x14 uint64 - x13, x14 = bits.Sub64(x5, uint64(0x0), uint64(fiatScalarUint1(x12))) - var x15 uint64 - var x16 uint64 - x15, x16 = bits.Sub64(x7, 0x1000000000000000, uint64(fiatScalarUint1(x14))) - var x18 uint64 - _, x18 = bits.Sub64(uint64(fiatScalarUint1(x8)), uint64(0x0), uint64(fiatScalarUint1(x16))) - var x19 uint64 - fiatScalarCmovznzU64(&x19, fiatScalarUint1(x18), x9, x1) - var x20 uint64 - fiatScalarCmovznzU64(&x20, fiatScalarUint1(x18), x11, x3) - var x21 uint64 - fiatScalarCmovznzU64(&x21, fiatScalarUint1(x18), x13, x5) - var x22 uint64 - fiatScalarCmovznzU64(&x22, fiatScalarUint1(x18), x15, x7) - out1[0] = x19 - out1[1] = x20 - out1[2] = x21 - out1[3] = x22 -} - -// fiatScalarSub subtracts two field elements in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// 0 ≤ eval arg2 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m -// 0 ≤ eval out1 < m -func fiatScalarSub(out1 *fiatScalarMontgomeryDomainFieldElement, arg1 *fiatScalarMontgomeryDomainFieldElement, arg2 *fiatScalarMontgomeryDomainFieldElement) { - var x1 uint64 - var x2 uint64 - x1, x2 = bits.Sub64(arg1[0], arg2[0], uint64(0x0)) - var x3 uint64 - var x4 uint64 - x3, x4 = bits.Sub64(arg1[1], arg2[1], uint64(fiatScalarUint1(x2))) - var x5 uint64 - var x6 uint64 - x5, x6 = bits.Sub64(arg1[2], arg2[2], uint64(fiatScalarUint1(x4))) - var x7 uint64 - var x8 uint64 - x7, x8 = bits.Sub64(arg1[3], arg2[3], uint64(fiatScalarUint1(x6))) - var x9 uint64 - fiatScalarCmovznzU64(&x9, fiatScalarUint1(x8), uint64(0x0), 0xffffffffffffffff) - var x10 uint64 - var x11 uint64 - x10, x11 = bits.Add64(x1, (x9 & 0x5812631a5cf5d3ed), uint64(0x0)) - var x12 uint64 - var x13 uint64 - x12, x13 = bits.Add64(x3, (x9 & 0x14def9dea2f79cd6), uint64(fiatScalarUint1(x11))) - var x14 uint64 - var x15 uint64 - x14, x15 = bits.Add64(x5, uint64(0x0), uint64(fiatScalarUint1(x13))) - var x16 uint64 - x16, _ = bits.Add64(x7, (x9 & 0x1000000000000000), uint64(fiatScalarUint1(x15))) - out1[0] = x10 - out1[1] = x12 - out1[2] = x14 - out1[3] = x16 -} - -// fiatScalarOpp negates a field element in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m -// 0 ≤ eval out1 < m -func fiatScalarOpp(out1 *fiatScalarMontgomeryDomainFieldElement, arg1 *fiatScalarMontgomeryDomainFieldElement) { - var x1 uint64 - var x2 uint64 - x1, x2 = bits.Sub64(uint64(0x0), arg1[0], uint64(0x0)) - var x3 uint64 - var x4 uint64 - x3, x4 = bits.Sub64(uint64(0x0), arg1[1], uint64(fiatScalarUint1(x2))) - var x5 uint64 - var x6 uint64 - x5, x6 = bits.Sub64(uint64(0x0), arg1[2], uint64(fiatScalarUint1(x4))) - var x7 uint64 - var x8 uint64 - x7, x8 = bits.Sub64(uint64(0x0), arg1[3], uint64(fiatScalarUint1(x6))) - var x9 uint64 - fiatScalarCmovznzU64(&x9, fiatScalarUint1(x8), uint64(0x0), 0xffffffffffffffff) - var x10 uint64 - var x11 uint64 - x10, x11 = bits.Add64(x1, (x9 & 0x5812631a5cf5d3ed), uint64(0x0)) - var x12 uint64 - var x13 uint64 - x12, x13 = bits.Add64(x3, (x9 & 0x14def9dea2f79cd6), uint64(fiatScalarUint1(x11))) - var x14 uint64 - var x15 uint64 - x14, x15 = bits.Add64(x5, uint64(0x0), uint64(fiatScalarUint1(x13))) - var x16 uint64 - x16, _ = bits.Add64(x7, (x9 & 0x1000000000000000), uint64(fiatScalarUint1(x15))) - out1[0] = x10 - out1[1] = x12 - out1[2] = x14 - out1[3] = x16 -} - -// fiatScalarNonzero outputs a single non-zero word if the input is non-zero and zero otherwise. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// out1 = 0 ↔ eval (from_montgomery arg1) mod m = 0 -// -// Input Bounds: -// -// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// -// Output Bounds: -// -// out1: [0x0 ~> 0xffffffffffffffff] -func fiatScalarNonzero(out1 *uint64, arg1 *[4]uint64) { - x1 := (arg1[0] | (arg1[1] | (arg1[2] | arg1[3]))) - *out1 = x1 -} - -// fiatScalarFromMontgomery translates a field element out of the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval out1 mod m = (eval arg1 * ((2^64)⁻¹ mod m)^4) mod m -// 0 ≤ eval out1 < m -func fiatScalarFromMontgomery(out1 *fiatScalarNonMontgomeryDomainFieldElement, arg1 *fiatScalarMontgomeryDomainFieldElement) { - x1 := arg1[0] - var x2 uint64 - _, x2 = bits.Mul64(x1, 0xd2b51da312547e1b) - var x4 uint64 - var x5 uint64 - x5, x4 = bits.Mul64(x2, 0x1000000000000000) - var x6 uint64 - var x7 uint64 - x7, x6 = bits.Mul64(x2, 0x14def9dea2f79cd6) - var x8 uint64 - var x9 uint64 - x9, x8 = bits.Mul64(x2, 0x5812631a5cf5d3ed) - var x10 uint64 - var x11 uint64 - x10, x11 = bits.Add64(x9, x6, uint64(0x0)) - var x13 uint64 - _, x13 = bits.Add64(x1, x8, uint64(0x0)) - var x14 uint64 - var x15 uint64 - x14, x15 = bits.Add64(uint64(0x0), x10, uint64(fiatScalarUint1(x13))) - var x16 uint64 - var x17 uint64 - x16, x17 = bits.Add64(x14, arg1[1], uint64(0x0)) - var x18 uint64 - _, x18 = bits.Mul64(x16, 0xd2b51da312547e1b) - var x20 uint64 - var x21 uint64 - x21, x20 = bits.Mul64(x18, 0x1000000000000000) - var x22 uint64 - var x23 uint64 - x23, x22 = bits.Mul64(x18, 0x14def9dea2f79cd6) - var x24 uint64 - var x25 uint64 - x25, x24 = bits.Mul64(x18, 0x5812631a5cf5d3ed) - var x26 uint64 - var x27 uint64 - x26, x27 = bits.Add64(x25, x22, uint64(0x0)) - var x29 uint64 - _, x29 = bits.Add64(x16, x24, uint64(0x0)) - var x30 uint64 - var x31 uint64 - x30, x31 = bits.Add64((uint64(fiatScalarUint1(x17)) + (uint64(fiatScalarUint1(x15)) + (uint64(fiatScalarUint1(x11)) + x7))), x26, uint64(fiatScalarUint1(x29))) - var x32 uint64 - var x33 uint64 - x32, x33 = bits.Add64(x4, (uint64(fiatScalarUint1(x27)) + x23), uint64(fiatScalarUint1(x31))) - var x34 uint64 - var x35 uint64 - x34, x35 = bits.Add64(x5, x20, uint64(fiatScalarUint1(x33))) - var x36 uint64 - var x37 uint64 - x36, x37 = bits.Add64(x30, arg1[2], uint64(0x0)) - var x38 uint64 - var x39 uint64 - x38, x39 = bits.Add64(x32, uint64(0x0), uint64(fiatScalarUint1(x37))) - var x40 uint64 - var x41 uint64 - x40, x41 = bits.Add64(x34, uint64(0x0), uint64(fiatScalarUint1(x39))) - var x42 uint64 - _, x42 = bits.Mul64(x36, 0xd2b51da312547e1b) - var x44 uint64 - var x45 uint64 - x45, x44 = bits.Mul64(x42, 0x1000000000000000) - var x46 uint64 - var x47 uint64 - x47, x46 = bits.Mul64(x42, 0x14def9dea2f79cd6) - var x48 uint64 - var x49 uint64 - x49, x48 = bits.Mul64(x42, 0x5812631a5cf5d3ed) - var x50 uint64 - var x51 uint64 - x50, x51 = bits.Add64(x49, x46, uint64(0x0)) - var x53 uint64 - _, x53 = bits.Add64(x36, x48, uint64(0x0)) - var x54 uint64 - var x55 uint64 - x54, x55 = bits.Add64(x38, x50, uint64(fiatScalarUint1(x53))) - var x56 uint64 - var x57 uint64 - x56, x57 = bits.Add64(x40, (uint64(fiatScalarUint1(x51)) + x47), uint64(fiatScalarUint1(x55))) - var x58 uint64 - var x59 uint64 - x58, x59 = bits.Add64((uint64(fiatScalarUint1(x41)) + (uint64(fiatScalarUint1(x35)) + x21)), x44, uint64(fiatScalarUint1(x57))) - var x60 uint64 - var x61 uint64 - x60, x61 = bits.Add64(x54, arg1[3], uint64(0x0)) - var x62 uint64 - var x63 uint64 - x62, x63 = bits.Add64(x56, uint64(0x0), uint64(fiatScalarUint1(x61))) - var x64 uint64 - var x65 uint64 - x64, x65 = bits.Add64(x58, uint64(0x0), uint64(fiatScalarUint1(x63))) - var x66 uint64 - _, x66 = bits.Mul64(x60, 0xd2b51da312547e1b) - var x68 uint64 - var x69 uint64 - x69, x68 = bits.Mul64(x66, 0x1000000000000000) - var x70 uint64 - var x71 uint64 - x71, x70 = bits.Mul64(x66, 0x14def9dea2f79cd6) - var x72 uint64 - var x73 uint64 - x73, x72 = bits.Mul64(x66, 0x5812631a5cf5d3ed) - var x74 uint64 - var x75 uint64 - x74, x75 = bits.Add64(x73, x70, uint64(0x0)) - var x77 uint64 - _, x77 = bits.Add64(x60, x72, uint64(0x0)) - var x78 uint64 - var x79 uint64 - x78, x79 = bits.Add64(x62, x74, uint64(fiatScalarUint1(x77))) - var x80 uint64 - var x81 uint64 - x80, x81 = bits.Add64(x64, (uint64(fiatScalarUint1(x75)) + x71), uint64(fiatScalarUint1(x79))) - var x82 uint64 - var x83 uint64 - x82, x83 = bits.Add64((uint64(fiatScalarUint1(x65)) + (uint64(fiatScalarUint1(x59)) + x45)), x68, uint64(fiatScalarUint1(x81))) - x84 := (uint64(fiatScalarUint1(x83)) + x69) - var x85 uint64 - var x86 uint64 - x85, x86 = bits.Sub64(x78, 0x5812631a5cf5d3ed, uint64(0x0)) - var x87 uint64 - var x88 uint64 - x87, x88 = bits.Sub64(x80, 0x14def9dea2f79cd6, uint64(fiatScalarUint1(x86))) - var x89 uint64 - var x90 uint64 - x89, x90 = bits.Sub64(x82, uint64(0x0), uint64(fiatScalarUint1(x88))) - var x91 uint64 - var x92 uint64 - x91, x92 = bits.Sub64(x84, 0x1000000000000000, uint64(fiatScalarUint1(x90))) - var x94 uint64 - _, x94 = bits.Sub64(uint64(0x0), uint64(0x0), uint64(fiatScalarUint1(x92))) - var x95 uint64 - fiatScalarCmovznzU64(&x95, fiatScalarUint1(x94), x85, x78) - var x96 uint64 - fiatScalarCmovznzU64(&x96, fiatScalarUint1(x94), x87, x80) - var x97 uint64 - fiatScalarCmovznzU64(&x97, fiatScalarUint1(x94), x89, x82) - var x98 uint64 - fiatScalarCmovznzU64(&x98, fiatScalarUint1(x94), x91, x84) - out1[0] = x95 - out1[1] = x96 - out1[2] = x97 - out1[3] = x98 -} - -// fiatScalarToMontgomery translates a field element into the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = eval arg1 mod m -// 0 ≤ eval out1 < m -func fiatScalarToMontgomery(out1 *fiatScalarMontgomeryDomainFieldElement, arg1 *fiatScalarNonMontgomeryDomainFieldElement) { - x1 := arg1[1] - x2 := arg1[2] - x3 := arg1[3] - x4 := arg1[0] - var x5 uint64 - var x6 uint64 - x6, x5 = bits.Mul64(x4, 0x399411b7c309a3d) - var x7 uint64 - var x8 uint64 - x8, x7 = bits.Mul64(x4, 0xceec73d217f5be65) - var x9 uint64 - var x10 uint64 - x10, x9 = bits.Mul64(x4, 0xd00e1ba768859347) - var x11 uint64 - var x12 uint64 - x12, x11 = bits.Mul64(x4, 0xa40611e3449c0f01) - var x13 uint64 - var x14 uint64 - x13, x14 = bits.Add64(x12, x9, uint64(0x0)) - var x15 uint64 - var x16 uint64 - x15, x16 = bits.Add64(x10, x7, uint64(fiatScalarUint1(x14))) - var x17 uint64 - var x18 uint64 - x17, x18 = bits.Add64(x8, x5, uint64(fiatScalarUint1(x16))) - var x19 uint64 - _, x19 = bits.Mul64(x11, 0xd2b51da312547e1b) - var x21 uint64 - var x22 uint64 - x22, x21 = bits.Mul64(x19, 0x1000000000000000) - var x23 uint64 - var x24 uint64 - x24, x23 = bits.Mul64(x19, 0x14def9dea2f79cd6) - var x25 uint64 - var x26 uint64 - x26, x25 = bits.Mul64(x19, 0x5812631a5cf5d3ed) - var x27 uint64 - var x28 uint64 - x27, x28 = bits.Add64(x26, x23, uint64(0x0)) - var x30 uint64 - _, x30 = bits.Add64(x11, x25, uint64(0x0)) - var x31 uint64 - var x32 uint64 - x31, x32 = bits.Add64(x13, x27, uint64(fiatScalarUint1(x30))) - var x33 uint64 - var x34 uint64 - x33, x34 = bits.Add64(x15, (uint64(fiatScalarUint1(x28)) + x24), uint64(fiatScalarUint1(x32))) - var x35 uint64 - var x36 uint64 - x35, x36 = bits.Add64(x17, x21, uint64(fiatScalarUint1(x34))) - var x37 uint64 - var x38 uint64 - x38, x37 = bits.Mul64(x1, 0x399411b7c309a3d) - var x39 uint64 - var x40 uint64 - x40, x39 = bits.Mul64(x1, 0xceec73d217f5be65) - var x41 uint64 - var x42 uint64 - x42, x41 = bits.Mul64(x1, 0xd00e1ba768859347) - var x43 uint64 - var x44 uint64 - x44, x43 = bits.Mul64(x1, 0xa40611e3449c0f01) - var x45 uint64 - var x46 uint64 - x45, x46 = bits.Add64(x44, x41, uint64(0x0)) - var x47 uint64 - var x48 uint64 - x47, x48 = bits.Add64(x42, x39, uint64(fiatScalarUint1(x46))) - var x49 uint64 - var x50 uint64 - x49, x50 = bits.Add64(x40, x37, uint64(fiatScalarUint1(x48))) - var x51 uint64 - var x52 uint64 - x51, x52 = bits.Add64(x31, x43, uint64(0x0)) - var x53 uint64 - var x54 uint64 - x53, x54 = bits.Add64(x33, x45, uint64(fiatScalarUint1(x52))) - var x55 uint64 - var x56 uint64 - x55, x56 = bits.Add64(x35, x47, uint64(fiatScalarUint1(x54))) - var x57 uint64 - var x58 uint64 - x57, x58 = bits.Add64(((uint64(fiatScalarUint1(x36)) + (uint64(fiatScalarUint1(x18)) + x6)) + x22), x49, uint64(fiatScalarUint1(x56))) - var x59 uint64 - _, x59 = bits.Mul64(x51, 0xd2b51da312547e1b) - var x61 uint64 - var x62 uint64 - x62, x61 = bits.Mul64(x59, 0x1000000000000000) - var x63 uint64 - var x64 uint64 - x64, x63 = bits.Mul64(x59, 0x14def9dea2f79cd6) - var x65 uint64 - var x66 uint64 - x66, x65 = bits.Mul64(x59, 0x5812631a5cf5d3ed) - var x67 uint64 - var x68 uint64 - x67, x68 = bits.Add64(x66, x63, uint64(0x0)) - var x70 uint64 - _, x70 = bits.Add64(x51, x65, uint64(0x0)) - var x71 uint64 - var x72 uint64 - x71, x72 = bits.Add64(x53, x67, uint64(fiatScalarUint1(x70))) - var x73 uint64 - var x74 uint64 - x73, x74 = bits.Add64(x55, (uint64(fiatScalarUint1(x68)) + x64), uint64(fiatScalarUint1(x72))) - var x75 uint64 - var x76 uint64 - x75, x76 = bits.Add64(x57, x61, uint64(fiatScalarUint1(x74))) - var x77 uint64 - var x78 uint64 - x78, x77 = bits.Mul64(x2, 0x399411b7c309a3d) - var x79 uint64 - var x80 uint64 - x80, x79 = bits.Mul64(x2, 0xceec73d217f5be65) - var x81 uint64 - var x82 uint64 - x82, x81 = bits.Mul64(x2, 0xd00e1ba768859347) - var x83 uint64 - var x84 uint64 - x84, x83 = bits.Mul64(x2, 0xa40611e3449c0f01) - var x85 uint64 - var x86 uint64 - x85, x86 = bits.Add64(x84, x81, uint64(0x0)) - var x87 uint64 - var x88 uint64 - x87, x88 = bits.Add64(x82, x79, uint64(fiatScalarUint1(x86))) - var x89 uint64 - var x90 uint64 - x89, x90 = bits.Add64(x80, x77, uint64(fiatScalarUint1(x88))) - var x91 uint64 - var x92 uint64 - x91, x92 = bits.Add64(x71, x83, uint64(0x0)) - var x93 uint64 - var x94 uint64 - x93, x94 = bits.Add64(x73, x85, uint64(fiatScalarUint1(x92))) - var x95 uint64 - var x96 uint64 - x95, x96 = bits.Add64(x75, x87, uint64(fiatScalarUint1(x94))) - var x97 uint64 - var x98 uint64 - x97, x98 = bits.Add64(((uint64(fiatScalarUint1(x76)) + (uint64(fiatScalarUint1(x58)) + (uint64(fiatScalarUint1(x50)) + x38))) + x62), x89, uint64(fiatScalarUint1(x96))) - var x99 uint64 - _, x99 = bits.Mul64(x91, 0xd2b51da312547e1b) - var x101 uint64 - var x102 uint64 - x102, x101 = bits.Mul64(x99, 0x1000000000000000) - var x103 uint64 - var x104 uint64 - x104, x103 = bits.Mul64(x99, 0x14def9dea2f79cd6) - var x105 uint64 - var x106 uint64 - x106, x105 = bits.Mul64(x99, 0x5812631a5cf5d3ed) - var x107 uint64 - var x108 uint64 - x107, x108 = bits.Add64(x106, x103, uint64(0x0)) - var x110 uint64 - _, x110 = bits.Add64(x91, x105, uint64(0x0)) - var x111 uint64 - var x112 uint64 - x111, x112 = bits.Add64(x93, x107, uint64(fiatScalarUint1(x110))) - var x113 uint64 - var x114 uint64 - x113, x114 = bits.Add64(x95, (uint64(fiatScalarUint1(x108)) + x104), uint64(fiatScalarUint1(x112))) - var x115 uint64 - var x116 uint64 - x115, x116 = bits.Add64(x97, x101, uint64(fiatScalarUint1(x114))) - var x117 uint64 - var x118 uint64 - x118, x117 = bits.Mul64(x3, 0x399411b7c309a3d) - var x119 uint64 - var x120 uint64 - x120, x119 = bits.Mul64(x3, 0xceec73d217f5be65) - var x121 uint64 - var x122 uint64 - x122, x121 = bits.Mul64(x3, 0xd00e1ba768859347) - var x123 uint64 - var x124 uint64 - x124, x123 = bits.Mul64(x3, 0xa40611e3449c0f01) - var x125 uint64 - var x126 uint64 - x125, x126 = bits.Add64(x124, x121, uint64(0x0)) - var x127 uint64 - var x128 uint64 - x127, x128 = bits.Add64(x122, x119, uint64(fiatScalarUint1(x126))) - var x129 uint64 - var x130 uint64 - x129, x130 = bits.Add64(x120, x117, uint64(fiatScalarUint1(x128))) - var x131 uint64 - var x132 uint64 - x131, x132 = bits.Add64(x111, x123, uint64(0x0)) - var x133 uint64 - var x134 uint64 - x133, x134 = bits.Add64(x113, x125, uint64(fiatScalarUint1(x132))) - var x135 uint64 - var x136 uint64 - x135, x136 = bits.Add64(x115, x127, uint64(fiatScalarUint1(x134))) - var x137 uint64 - var x138 uint64 - x137, x138 = bits.Add64(((uint64(fiatScalarUint1(x116)) + (uint64(fiatScalarUint1(x98)) + (uint64(fiatScalarUint1(x90)) + x78))) + x102), x129, uint64(fiatScalarUint1(x136))) - var x139 uint64 - _, x139 = bits.Mul64(x131, 0xd2b51da312547e1b) - var x141 uint64 - var x142 uint64 - x142, x141 = bits.Mul64(x139, 0x1000000000000000) - var x143 uint64 - var x144 uint64 - x144, x143 = bits.Mul64(x139, 0x14def9dea2f79cd6) - var x145 uint64 - var x146 uint64 - x146, x145 = bits.Mul64(x139, 0x5812631a5cf5d3ed) - var x147 uint64 - var x148 uint64 - x147, x148 = bits.Add64(x146, x143, uint64(0x0)) - var x150 uint64 - _, x150 = bits.Add64(x131, x145, uint64(0x0)) - var x151 uint64 - var x152 uint64 - x151, x152 = bits.Add64(x133, x147, uint64(fiatScalarUint1(x150))) - var x153 uint64 - var x154 uint64 - x153, x154 = bits.Add64(x135, (uint64(fiatScalarUint1(x148)) + x144), uint64(fiatScalarUint1(x152))) - var x155 uint64 - var x156 uint64 - x155, x156 = bits.Add64(x137, x141, uint64(fiatScalarUint1(x154))) - x157 := ((uint64(fiatScalarUint1(x156)) + (uint64(fiatScalarUint1(x138)) + (uint64(fiatScalarUint1(x130)) + x118))) + x142) - var x158 uint64 - var x159 uint64 - x158, x159 = bits.Sub64(x151, 0x5812631a5cf5d3ed, uint64(0x0)) - var x160 uint64 - var x161 uint64 - x160, x161 = bits.Sub64(x153, 0x14def9dea2f79cd6, uint64(fiatScalarUint1(x159))) - var x162 uint64 - var x163 uint64 - x162, x163 = bits.Sub64(x155, uint64(0x0), uint64(fiatScalarUint1(x161))) - var x164 uint64 - var x165 uint64 - x164, x165 = bits.Sub64(x157, 0x1000000000000000, uint64(fiatScalarUint1(x163))) - var x167 uint64 - _, x167 = bits.Sub64(uint64(0x0), uint64(0x0), uint64(fiatScalarUint1(x165))) - var x168 uint64 - fiatScalarCmovznzU64(&x168, fiatScalarUint1(x167), x158, x151) - var x169 uint64 - fiatScalarCmovznzU64(&x169, fiatScalarUint1(x167), x160, x153) - var x170 uint64 - fiatScalarCmovznzU64(&x170, fiatScalarUint1(x167), x162, x155) - var x171 uint64 - fiatScalarCmovznzU64(&x171, fiatScalarUint1(x167), x164, x157) - out1[0] = x168 - out1[1] = x169 - out1[2] = x170 - out1[3] = x171 -} - -// fiatScalarToBytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..31] -// -// Input Bounds: -// -// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0x1fffffffffffffff]] -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x1f]] -func fiatScalarToBytes(out1 *[32]uint8, arg1 *[4]uint64) { - x1 := arg1[3] - x2 := arg1[2] - x3 := arg1[1] - x4 := arg1[0] - x5 := (uint8(x4) & 0xff) - x6 := (x4 >> 8) - x7 := (uint8(x6) & 0xff) - x8 := (x6 >> 8) - x9 := (uint8(x8) & 0xff) - x10 := (x8 >> 8) - x11 := (uint8(x10) & 0xff) - x12 := (x10 >> 8) - x13 := (uint8(x12) & 0xff) - x14 := (x12 >> 8) - x15 := (uint8(x14) & 0xff) - x16 := (x14 >> 8) - x17 := (uint8(x16) & 0xff) - x18 := uint8((x16 >> 8)) - x19 := (uint8(x3) & 0xff) - x20 := (x3 >> 8) - x21 := (uint8(x20) & 0xff) - x22 := (x20 >> 8) - x23 := (uint8(x22) & 0xff) - x24 := (x22 >> 8) - x25 := (uint8(x24) & 0xff) - x26 := (x24 >> 8) - x27 := (uint8(x26) & 0xff) - x28 := (x26 >> 8) - x29 := (uint8(x28) & 0xff) - x30 := (x28 >> 8) - x31 := (uint8(x30) & 0xff) - x32 := uint8((x30 >> 8)) - x33 := (uint8(x2) & 0xff) - x34 := (x2 >> 8) - x35 := (uint8(x34) & 0xff) - x36 := (x34 >> 8) - x37 := (uint8(x36) & 0xff) - x38 := (x36 >> 8) - x39 := (uint8(x38) & 0xff) - x40 := (x38 >> 8) - x41 := (uint8(x40) & 0xff) - x42 := (x40 >> 8) - x43 := (uint8(x42) & 0xff) - x44 := (x42 >> 8) - x45 := (uint8(x44) & 0xff) - x46 := uint8((x44 >> 8)) - x47 := (uint8(x1) & 0xff) - x48 := (x1 >> 8) - x49 := (uint8(x48) & 0xff) - x50 := (x48 >> 8) - x51 := (uint8(x50) & 0xff) - x52 := (x50 >> 8) - x53 := (uint8(x52) & 0xff) - x54 := (x52 >> 8) - x55 := (uint8(x54) & 0xff) - x56 := (x54 >> 8) - x57 := (uint8(x56) & 0xff) - x58 := (x56 >> 8) - x59 := (uint8(x58) & 0xff) - x60 := uint8((x58 >> 8)) - out1[0] = x5 - out1[1] = x7 - out1[2] = x9 - out1[3] = x11 - out1[4] = x13 - out1[5] = x15 - out1[6] = x17 - out1[7] = x18 - out1[8] = x19 - out1[9] = x21 - out1[10] = x23 - out1[11] = x25 - out1[12] = x27 - out1[13] = x29 - out1[14] = x31 - out1[15] = x32 - out1[16] = x33 - out1[17] = x35 - out1[18] = x37 - out1[19] = x39 - out1[20] = x41 - out1[21] = x43 - out1[22] = x45 - out1[23] = x46 - out1[24] = x47 - out1[25] = x49 - out1[26] = x51 - out1[27] = x53 - out1[28] = x55 - out1[29] = x57 - out1[30] = x59 - out1[31] = x60 -} - -// fiatScalarFromBytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order. -// -// Preconditions: -// -// 0 ≤ bytes_eval arg1 < m -// -// Postconditions: -// -// eval out1 mod m = bytes_eval arg1 mod m -// 0 ≤ eval out1 < m -// -// Input Bounds: -// -// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x1f]] -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0x1fffffffffffffff]] -func fiatScalarFromBytes(out1 *[4]uint64, arg1 *[32]uint8) { - x1 := (uint64(arg1[31]) << 56) - x2 := (uint64(arg1[30]) << 48) - x3 := (uint64(arg1[29]) << 40) - x4 := (uint64(arg1[28]) << 32) - x5 := (uint64(arg1[27]) << 24) - x6 := (uint64(arg1[26]) << 16) - x7 := (uint64(arg1[25]) << 8) - x8 := arg1[24] - x9 := (uint64(arg1[23]) << 56) - x10 := (uint64(arg1[22]) << 48) - x11 := (uint64(arg1[21]) << 40) - x12 := (uint64(arg1[20]) << 32) - x13 := (uint64(arg1[19]) << 24) - x14 := (uint64(arg1[18]) << 16) - x15 := (uint64(arg1[17]) << 8) - x16 := arg1[16] - x17 := (uint64(arg1[15]) << 56) - x18 := (uint64(arg1[14]) << 48) - x19 := (uint64(arg1[13]) << 40) - x20 := (uint64(arg1[12]) << 32) - x21 := (uint64(arg1[11]) << 24) - x22 := (uint64(arg1[10]) << 16) - x23 := (uint64(arg1[9]) << 8) - x24 := arg1[8] - x25 := (uint64(arg1[7]) << 56) - x26 := (uint64(arg1[6]) << 48) - x27 := (uint64(arg1[5]) << 40) - x28 := (uint64(arg1[4]) << 32) - x29 := (uint64(arg1[3]) << 24) - x30 := (uint64(arg1[2]) << 16) - x31 := (uint64(arg1[1]) << 8) - x32 := arg1[0] - x33 := (x31 + uint64(x32)) - x34 := (x30 + x33) - x35 := (x29 + x34) - x36 := (x28 + x35) - x37 := (x27 + x36) - x38 := (x26 + x37) - x39 := (x25 + x38) - x40 := (x23 + uint64(x24)) - x41 := (x22 + x40) - x42 := (x21 + x41) - x43 := (x20 + x42) - x44 := (x19 + x43) - x45 := (x18 + x44) - x46 := (x17 + x45) - x47 := (x15 + uint64(x16)) - x48 := (x14 + x47) - x49 := (x13 + x48) - x50 := (x12 + x49) - x51 := (x11 + x50) - x52 := (x10 + x51) - x53 := (x9 + x52) - x54 := (x7 + uint64(x8)) - x55 := (x6 + x54) - x56 := (x5 + x55) - x57 := (x4 + x56) - x58 := (x3 + x57) - x59 := (x2 + x58) - x60 := (x1 + x59) - out1[0] = x39 - out1[1] = x46 - out1[2] = x53 - out1[3] = x60 -} diff --git a/vendor/filippo.io/edwards25519/scalarmult.go b/vendor/filippo.io/edwards25519/scalarmult.go deleted file mode 100644 index f7ca3cef99..0000000000 --- a/vendor/filippo.io/edwards25519/scalarmult.go +++ /dev/null @@ -1,214 +0,0 @@ -// Copyright (c) 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package edwards25519 - -import "sync" - -// basepointTable is a set of 32 affineLookupTables, where table i is generated -// from 256i * basepoint. It is precomputed the first time it's used. -func basepointTable() *[32]affineLookupTable { - basepointTablePrecomp.initOnce.Do(func() { - p := NewGeneratorPoint() - for i := 0; i < 32; i++ { - basepointTablePrecomp.table[i].FromP3(p) - for j := 0; j < 8; j++ { - p.Add(p, p) - } - } - }) - return &basepointTablePrecomp.table -} - -var basepointTablePrecomp struct { - table [32]affineLookupTable - initOnce sync.Once -} - -// ScalarBaseMult sets v = x * B, where B is the canonical generator, and -// returns v. -// -// The scalar multiplication is done in constant time. -func (v *Point) ScalarBaseMult(x *Scalar) *Point { - basepointTable := basepointTable() - - // Write x = sum(x_i * 16^i) so x*B = sum( B*x_i*16^i ) - // as described in the Ed25519 paper - // - // Group even and odd coefficients - // x*B = x_0*16^0*B + x_2*16^2*B + ... + x_62*16^62*B - // + x_1*16^1*B + x_3*16^3*B + ... + x_63*16^63*B - // x*B = x_0*16^0*B + x_2*16^2*B + ... + x_62*16^62*B - // + 16*( x_1*16^0*B + x_3*16^2*B + ... + x_63*16^62*B) - // - // We use a lookup table for each i to get x_i*16^(2*i)*B - // and do four doublings to multiply by 16. - digits := x.signedRadix16() - - multiple := &affineCached{} - tmp1 := &projP1xP1{} - tmp2 := &projP2{} - - // Accumulate the odd components first - v.Set(NewIdentityPoint()) - for i := 1; i < 64; i += 2 { - basepointTable[i/2].SelectInto(multiple, digits[i]) - tmp1.AddAffine(v, multiple) - v.fromP1xP1(tmp1) - } - - // Multiply by 16 - tmp2.FromP3(v) // tmp2 = v in P2 coords - tmp1.Double(tmp2) // tmp1 = 2*v in P1xP1 coords - tmp2.FromP1xP1(tmp1) // tmp2 = 2*v in P2 coords - tmp1.Double(tmp2) // tmp1 = 4*v in P1xP1 coords - tmp2.FromP1xP1(tmp1) // tmp2 = 4*v in P2 coords - tmp1.Double(tmp2) // tmp1 = 8*v in P1xP1 coords - tmp2.FromP1xP1(tmp1) // tmp2 = 8*v in P2 coords - tmp1.Double(tmp2) // tmp1 = 16*v in P1xP1 coords - v.fromP1xP1(tmp1) // now v = 16*(odd components) - - // Accumulate the even components - for i := 0; i < 64; i += 2 { - basepointTable[i/2].SelectInto(multiple, digits[i]) - tmp1.AddAffine(v, multiple) - v.fromP1xP1(tmp1) - } - - return v -} - -// ScalarMult sets v = x * q, and returns v. -// -// The scalar multiplication is done in constant time. -func (v *Point) ScalarMult(x *Scalar, q *Point) *Point { - checkInitialized(q) - - var table projLookupTable - table.FromP3(q) - - // Write x = sum(x_i * 16^i) - // so x*Q = sum( Q*x_i*16^i ) - // = Q*x_0 + 16*(Q*x_1 + 16*( ... + Q*x_63) ... ) - // <------compute inside out--------- - // - // We use the lookup table to get the x_i*Q values - // and do four doublings to compute 16*Q - digits := x.signedRadix16() - - // Unwrap first loop iteration to save computing 16*identity - multiple := &projCached{} - tmp1 := &projP1xP1{} - tmp2 := &projP2{} - table.SelectInto(multiple, digits[63]) - - v.Set(NewIdentityPoint()) - tmp1.Add(v, multiple) // tmp1 = x_63*Q in P1xP1 coords - for i := 62; i >= 0; i-- { - tmp2.FromP1xP1(tmp1) // tmp2 = (prev) in P2 coords - tmp1.Double(tmp2) // tmp1 = 2*(prev) in P1xP1 coords - tmp2.FromP1xP1(tmp1) // tmp2 = 2*(prev) in P2 coords - tmp1.Double(tmp2) // tmp1 = 4*(prev) in P1xP1 coords - tmp2.FromP1xP1(tmp1) // tmp2 = 4*(prev) in P2 coords - tmp1.Double(tmp2) // tmp1 = 8*(prev) in P1xP1 coords - tmp2.FromP1xP1(tmp1) // tmp2 = 8*(prev) in P2 coords - tmp1.Double(tmp2) // tmp1 = 16*(prev) in P1xP1 coords - v.fromP1xP1(tmp1) // v = 16*(prev) in P3 coords - table.SelectInto(multiple, digits[i]) - tmp1.Add(v, multiple) // tmp1 = x_i*Q + 16*(prev) in P1xP1 coords - } - v.fromP1xP1(tmp1) - return v -} - -// basepointNafTable is the nafLookupTable8 for the basepoint. -// It is precomputed the first time it's used. -func basepointNafTable() *nafLookupTable8 { - basepointNafTablePrecomp.initOnce.Do(func() { - basepointNafTablePrecomp.table.FromP3(NewGeneratorPoint()) - }) - return &basepointNafTablePrecomp.table -} - -var basepointNafTablePrecomp struct { - table nafLookupTable8 - initOnce sync.Once -} - -// VarTimeDoubleScalarBaseMult sets v = a * A + b * B, where B is the canonical -// generator, and returns v. -// -// Execution time depends on the inputs. -func (v *Point) VarTimeDoubleScalarBaseMult(a *Scalar, A *Point, b *Scalar) *Point { - checkInitialized(A) - - // Similarly to the single variable-base approach, we compute - // digits and use them with a lookup table. However, because - // we are allowed to do variable-time operations, we don't - // need constant-time lookups or constant-time digit - // computations. - // - // So we use a non-adjacent form of some width w instead of - // radix 16. This is like a binary representation (one digit - // for each binary place) but we allow the digits to grow in - // magnitude up to 2^{w-1} so that the nonzero digits are as - // sparse as possible. Intuitively, this "condenses" the - // "mass" of the scalar onto sparse coefficients (meaning - // fewer additions). - - basepointNafTable := basepointNafTable() - var aTable nafLookupTable5 - aTable.FromP3(A) - // Because the basepoint is fixed, we can use a wider NAF - // corresponding to a bigger table. - aNaf := a.nonAdjacentForm(5) - bNaf := b.nonAdjacentForm(8) - - // Find the first nonzero coefficient. - i := 255 - for j := i; j >= 0; j-- { - if aNaf[j] != 0 || bNaf[j] != 0 { - break - } - } - - multA := &projCached{} - multB := &affineCached{} - tmp1 := &projP1xP1{} - tmp2 := &projP2{} - tmp2.Zero() - - // Move from high to low bits, doubling the accumulator - // at each iteration and checking whether there is a nonzero - // coefficient to look up a multiple of. - for ; i >= 0; i-- { - tmp1.Double(tmp2) - - // Only update v if we have a nonzero coeff to add in. - if aNaf[i] > 0 { - v.fromP1xP1(tmp1) - aTable.SelectInto(multA, aNaf[i]) - tmp1.Add(v, multA) - } else if aNaf[i] < 0 { - v.fromP1xP1(tmp1) - aTable.SelectInto(multA, -aNaf[i]) - tmp1.Sub(v, multA) - } - - if bNaf[i] > 0 { - v.fromP1xP1(tmp1) - basepointNafTable.SelectInto(multB, bNaf[i]) - tmp1.AddAffine(v, multB) - } else if bNaf[i] < 0 { - v.fromP1xP1(tmp1) - basepointNafTable.SelectInto(multB, -bNaf[i]) - tmp1.SubAffine(v, multB) - } - - tmp2.FromP1xP1(tmp1) - } - - v.fromP2(tmp2) - return v -} diff --git a/vendor/filippo.io/edwards25519/tables.go b/vendor/filippo.io/edwards25519/tables.go deleted file mode 100644 index 83234bbc0f..0000000000 --- a/vendor/filippo.io/edwards25519/tables.go +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright (c) 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package edwards25519 - -import ( - "crypto/subtle" -) - -// A dynamic lookup table for variable-base, constant-time scalar muls. -type projLookupTable struct { - points [8]projCached -} - -// A precomputed lookup table for fixed-base, constant-time scalar muls. -type affineLookupTable struct { - points [8]affineCached -} - -// A dynamic lookup table for variable-base, variable-time scalar muls. -type nafLookupTable5 struct { - points [8]projCached -} - -// A precomputed lookup table for fixed-base, variable-time scalar muls. -type nafLookupTable8 struct { - points [64]affineCached -} - -// Constructors. - -// Builds a lookup table at runtime. Fast. -func (v *projLookupTable) FromP3(q *Point) { - // Goal: v.points[i] = (i+1)*Q, i.e., Q, 2Q, ..., 8Q - // This allows lookup of -8Q, ..., -Q, 0, Q, ..., 8Q - v.points[0].FromP3(q) - tmpP3 := Point{} - tmpP1xP1 := projP1xP1{} - for i := 0; i < 7; i++ { - // Compute (i+1)*Q as Q + i*Q and convert to a projCached - // This is needlessly complicated because the API has explicit - // receivers instead of creating stack objects and relying on RVO - v.points[i+1].FromP3(tmpP3.fromP1xP1(tmpP1xP1.Add(q, &v.points[i]))) - } -} - -// This is not optimised for speed; fixed-base tables should be precomputed. -func (v *affineLookupTable) FromP3(q *Point) { - // Goal: v.points[i] = (i+1)*Q, i.e., Q, 2Q, ..., 8Q - // This allows lookup of -8Q, ..., -Q, 0, Q, ..., 8Q - v.points[0].FromP3(q) - tmpP3 := Point{} - tmpP1xP1 := projP1xP1{} - for i := 0; i < 7; i++ { - // Compute (i+1)*Q as Q + i*Q and convert to affineCached - v.points[i+1].FromP3(tmpP3.fromP1xP1(tmpP1xP1.AddAffine(q, &v.points[i]))) - } -} - -// Builds a lookup table at runtime. Fast. -func (v *nafLookupTable5) FromP3(q *Point) { - // Goal: v.points[i] = (2*i+1)*Q, i.e., Q, 3Q, 5Q, ..., 15Q - // This allows lookup of -15Q, ..., -3Q, -Q, 0, Q, 3Q, ..., 15Q - v.points[0].FromP3(q) - q2 := Point{} - q2.Add(q, q) - tmpP3 := Point{} - tmpP1xP1 := projP1xP1{} - for i := 0; i < 7; i++ { - v.points[i+1].FromP3(tmpP3.fromP1xP1(tmpP1xP1.Add(&q2, &v.points[i]))) - } -} - -// This is not optimised for speed; fixed-base tables should be precomputed. -func (v *nafLookupTable8) FromP3(q *Point) { - v.points[0].FromP3(q) - q2 := Point{} - q2.Add(q, q) - tmpP3 := Point{} - tmpP1xP1 := projP1xP1{} - for i := 0; i < 63; i++ { - v.points[i+1].FromP3(tmpP3.fromP1xP1(tmpP1xP1.AddAffine(&q2, &v.points[i]))) - } -} - -// Selectors. - -// Set dest to x*Q, where -8 <= x <= 8, in constant time. -func (v *projLookupTable) SelectInto(dest *projCached, x int8) { - // Compute xabs = |x| - xmask := x >> 7 - xabs := uint8((x + xmask) ^ xmask) - - dest.Zero() - for j := 1; j <= 8; j++ { - // Set dest = j*Q if |x| = j - cond := subtle.ConstantTimeByteEq(xabs, uint8(j)) - dest.Select(&v.points[j-1], dest, cond) - } - // Now dest = |x|*Q, conditionally negate to get x*Q - dest.CondNeg(int(xmask & 1)) -} - -// Set dest to x*Q, where -8 <= x <= 8, in constant time. -func (v *affineLookupTable) SelectInto(dest *affineCached, x int8) { - // Compute xabs = |x| - xmask := x >> 7 - xabs := uint8((x + xmask) ^ xmask) - - dest.Zero() - for j := 1; j <= 8; j++ { - // Set dest = j*Q if |x| = j - cond := subtle.ConstantTimeByteEq(xabs, uint8(j)) - dest.Select(&v.points[j-1], dest, cond) - } - // Now dest = |x|*Q, conditionally negate to get x*Q - dest.CondNeg(int(xmask & 1)) -} - -// Given odd x with 0 < x < 2^4, return x*Q (in variable time). -func (v *nafLookupTable5) SelectInto(dest *projCached, x int8) { - *dest = v.points[x/2] -} - -// Given odd x with 0 < x < 2^7, return x*Q (in variable time). -func (v *nafLookupTable8) SelectInto(dest *affineCached, x int8) { - *dest = v.points[x/2] -} diff --git a/vendor/github.com/agnivade/levenshtein/.travis.yml b/vendor/github.com/agnivade/levenshtein/.travis.yml deleted file mode 100644 index 0873fa983f..0000000000 --- a/vendor/github.com/agnivade/levenshtein/.travis.yml +++ /dev/null @@ -1,23 +0,0 @@ -language: go - -# See https://travis-ci.community/t/goos-js-goarch-wasm-go-run-fails-panic-newosproc-not-implemented/1651 -#addons: -# chrome: stable - -before_install: -- export GO111MODULE=on - -#install: -#- go get github.com/agnivade/wasmbrowsertest -#- mv $GOPATH/bin/wasmbrowsertest $GOPATH/bin/go_js_wasm_exec -#- export PATH=$GOPATH/bin:$PATH - -go: -- 1.13.x -- 1.14.x -- 1.15.x -- tip - -script: -#- GOOS=js GOARCH=wasm go test -v -- go test -v diff --git a/vendor/github.com/agnivade/levenshtein/Makefile b/vendor/github.com/agnivade/levenshtein/Makefile index 5f6890d613..3bbda319e4 100644 --- a/vendor/github.com/agnivade/levenshtein/Makefile +++ b/vendor/github.com/agnivade/levenshtein/Makefile @@ -4,12 +4,10 @@ install: go install lint: - gofmt -l -s -w . && go vet . && golint -set_exit_status=1 . + gofmt -l -s -w . && go vet . -test: # The first 2 go gets are to support older Go versions - go get github.com/arbovm/levenshtein - go get github.com/dgryski/trifles/leven - GO111MODULE=on go test -race -v -coverprofile=coverage.txt -covermode=atomic +test: + go test -race -v -coverprofile=coverage.txt -covermode=atomic bench: go test -run=XXX -bench=. -benchmem -count=5 diff --git a/vendor/github.com/agnivade/levenshtein/README.md b/vendor/github.com/agnivade/levenshtein/README.md index 13c52a2101..34378aabec 100644 --- a/vendor/github.com/agnivade/levenshtein/README.md +++ b/vendor/github.com/agnivade/levenshtein/README.md @@ -1,4 +1,4 @@ -levenshtein [![Build Status](https://travis-ci.org/agnivade/levenshtein.svg?branch=master)](https://travis-ci.org/agnivade/levenshtein) [![Go Report Card](https://goreportcard.com/badge/github.com/agnivade/levenshtein)](https://goreportcard.com/report/github.com/agnivade/levenshtein) [![PkgGoDev](https://pkg.go.dev/badge/github.com/agnivade/levenshtein)](https://pkg.go.dev/github.com/agnivade/levenshtein) +levenshtein ![Build Status](https://github.com/agnivade/levenshtein/actions/workflows/ci.yml/badge.svg) [![Go Report Card](https://goreportcard.com/badge/github.com/agnivade/levenshtein)](https://goreportcard.com/report/github.com/agnivade/levenshtein) [![PkgGoDev](https://pkg.go.dev/badge/github.com/agnivade/levenshtein)](https://pkg.go.dev/github.com/agnivade/levenshtein) =========== [Go](http://golang.org) package to calculate the [Levenshtein Distance](http://en.wikipedia.org/wiki/Levenshtein_distance) diff --git a/vendor/github.com/agnivade/levenshtein/levenshtein.go b/vendor/github.com/agnivade/levenshtein/levenshtein.go index f727a66fe7..861f409dd2 100644 --- a/vendor/github.com/agnivade/levenshtein/levenshtein.go +++ b/vendor/github.com/agnivade/levenshtein/levenshtein.go @@ -41,6 +41,25 @@ func ComputeDistance(a, b string) int { if len(s1) > len(s2) { s1, s2 = s2, s1 } + + // remove trailing identical runes. + for i := 0; i < len(s1); i++ { + if s1[len(s1)-1-i] != s2[len(s2)-1-i] { + s1 = s1[:len(s1)-i] + s2 = s2[:len(s2)-i] + break + } + } + + // Remove leading identical runes. + for i := 0; i < len(s1); i++ { + if s1[i] != s2[i] { + s1 = s1[i:] + s2 = s2[i:] + break + } + } + lenS1 := len(s1) lenS2 := len(s2) @@ -71,7 +90,7 @@ func ComputeDistance(a, b string) int { for j := 1; j <= lenS1; j++ { current := x[j-1] // match if s2[i-1] != s1[j-1] { - current = min(min(x[j-1]+1, prev+1), x[j]+1) + current = min(x[j-1]+1, prev+1, x[j]+1) } x[j-1] = prev prev = current @@ -80,10 +99,3 @@ func ComputeDistance(a, b string) int { } return int(x[lenS1]) } - -func min(a, b uint16) uint16 { - if a < b { - return a - } - return b -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/checksum.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/checksum.go new file mode 100644 index 0000000000..4152caade1 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/checksum.go @@ -0,0 +1,33 @@ +package aws + +// RequestChecksumCalculation controls request checksum calculation workflow +type RequestChecksumCalculation int + +const ( + // RequestChecksumCalculationUnset is the unset value for RequestChecksumCalculation + RequestChecksumCalculationUnset RequestChecksumCalculation = iota + + // RequestChecksumCalculationWhenSupported indicates request checksum will be calculated + // if the operation supports input checksums + RequestChecksumCalculationWhenSupported + + // RequestChecksumCalculationWhenRequired indicates request checksum will be calculated + // if required by the operation or if user elects to set a checksum algorithm in request + RequestChecksumCalculationWhenRequired +) + +// ResponseChecksumValidation controls response checksum validation workflow +type ResponseChecksumValidation int + +const ( + // ResponseChecksumValidationUnset is the unset value for ResponseChecksumValidation + ResponseChecksumValidationUnset ResponseChecksumValidation = iota + + // ResponseChecksumValidationWhenSupported indicates response checksum will be validated + // if the operation supports output checksums + ResponseChecksumValidationWhenSupported + + // ResponseChecksumValidationWhenRequired indicates response checksum will only + // be validated if the operation requires output checksum validation + ResponseChecksumValidationWhenRequired +) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/config.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/config.go index 16000d7927..a015cc5b20 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/config.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/config.go @@ -165,6 +165,33 @@ type Config struct { // Controls how a resolved AWS account ID is handled for endpoint routing. AccountIDEndpointMode AccountIDEndpointMode + + // RequestChecksumCalculation determines when request checksum calculation is performed. + // + // There are two possible values for this setting: + // + // 1. RequestChecksumCalculationWhenSupported (default): The checksum is always calculated + // if the operation supports it, regardless of whether the user sets an algorithm in the request. + // + // 2. RequestChecksumCalculationWhenRequired: The checksum is only calculated if the user + // explicitly sets a checksum algorithm in the request. + // + // This setting is sourced from the environment variable AWS_REQUEST_CHECKSUM_CALCULATION + // or the shared config profile attribute "request_checksum_calculation". + RequestChecksumCalculation RequestChecksumCalculation + + // ResponseChecksumValidation determines when response checksum validation is performed + // + // There are two possible values for this setting: + // + // 1. ResponseChecksumValidationWhenSupported (default): The checksum is always validated + // if the operation supports it, regardless of whether the user sets the validation mode to ENABLED in request. + // + // 2. ResponseChecksumValidationWhenRequired: The checksum is only validated if the user + // explicitly sets the validation mode to ENABLED in the request + // This variable is sourced from environment variable AWS_RESPONSE_CHECKSUM_VALIDATION or + // the shared config profile attribute "response_checksum_validation". + ResponseChecksumValidation ResponseChecksumValidation } // NewConfig returns a new Config pointer that can be chained with builder diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/go_module_metadata.go index 6fc9dbe1bb..63642a9dd8 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/go_module_metadata.go @@ -3,4 +3,4 @@ package aws // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.32.7" +const goModuleVersion = "1.36.1" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/user_agent.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/user_agent.go index ab4e619073..95b6268f49 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/user_agent.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/user_agent.go @@ -76,19 +76,39 @@ type UserAgentFeature string // Enumerates UserAgentFeature. const ( - UserAgentFeatureResourceModel UserAgentFeature = "A" // n/a (we don't generate separate resource types) - UserAgentFeatureWaiter = "B" - UserAgentFeaturePaginator = "C" - UserAgentFeatureRetryModeLegacy = "D" // n/a (equivalent to standard) - UserAgentFeatureRetryModeStandard = "E" - UserAgentFeatureRetryModeAdaptive = "F" - UserAgentFeatureS3Transfer = "G" - UserAgentFeatureS3CryptoV1N = "H" // n/a (crypto client is external) - UserAgentFeatureS3CryptoV2 = "I" // n/a - UserAgentFeatureS3ExpressBucket = "J" - UserAgentFeatureS3AccessGrants = "K" // not yet implemented - UserAgentFeatureGZIPRequestCompression = "L" - UserAgentFeatureProtocolRPCV2CBOR = "M" + UserAgentFeatureResourceModel UserAgentFeature = "A" // n/a (we don't generate separate resource types) + + UserAgentFeatureWaiter = "B" + UserAgentFeaturePaginator = "C" + + UserAgentFeatureRetryModeLegacy = "D" // n/a (equivalent to standard) + UserAgentFeatureRetryModeStandard = "E" + UserAgentFeatureRetryModeAdaptive = "F" + + UserAgentFeatureS3Transfer = "G" + UserAgentFeatureS3CryptoV1N = "H" // n/a (crypto client is external) + UserAgentFeatureS3CryptoV2 = "I" // n/a + UserAgentFeatureS3ExpressBucket = "J" + UserAgentFeatureS3AccessGrants = "K" // not yet implemented + + UserAgentFeatureGZIPRequestCompression = "L" + + UserAgentFeatureProtocolRPCV2CBOR = "M" + + UserAgentFeatureAccountIDEndpoint = "O" // DO NOT IMPLEMENT: rules output is not currently defined. SDKs should not parse endpoints for feature information. + UserAgentFeatureAccountIDModePreferred = "P" + UserAgentFeatureAccountIDModeDisabled = "Q" + UserAgentFeatureAccountIDModeRequired = "R" + + UserAgentFeatureRequestChecksumCRC32 = "U" + UserAgentFeatureRequestChecksumCRC32C = "V" + UserAgentFeatureRequestChecksumCRC64 = "W" + UserAgentFeatureRequestChecksumSHA1 = "X" + UserAgentFeatureRequestChecksumSHA256 = "Y" + UserAgentFeatureRequestChecksumWhenSupported = "Z" + UserAgentFeatureRequestChecksumWhenRequired = "a" + UserAgentFeatureResponseChecksumWhenSupported = "b" + UserAgentFeatureResponseChecksumWhenRequired = "c" ) // RequestUserAgent is a build middleware that set the User-Agent for the request. diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/array.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/array.go index 47ebc0f547..6669a3ddfd 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/array.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/array.go @@ -1,8 +1,8 @@ package query import ( - "fmt" "net/url" + "strconv" ) // Array represents the encoding of Query lists and sets. A Query array is a @@ -21,19 +21,8 @@ type Array struct { // keys for each element in the list. For example, an entry might have the // key "ParentStructure.ListName.member.MemberName.1". // - // While this is currently represented as a string that gets added to, it - // could also be represented as a stack that only gets condensed into a - // string when a finalized key is created. This could potentially reduce - // allocations. + // When the array is not flat the prefix will contain the memberName otherwise the memberName is ignored prefix string - // Whether the list is flat or not. A list that is not flat will produce the - // following entry to the url.Values for a given entry: - // ListName.MemberName.1=value - // A list that is flat will produce the following: - // ListName.1=value - flat bool - // The location name of the member. In most cases this should be "member". - memberName string // Elements are stored in values, so we keep track of the list size here. size int32 // Empty lists are encoded as "=", if we add a value later we will @@ -45,11 +34,14 @@ func newArray(values url.Values, prefix string, flat bool, memberName string) *A emptyValue := newValue(values, prefix, flat) emptyValue.String("") + if !flat { + // This uses string concatenation in place of fmt.Sprintf as fmt.Sprintf has a much higher resource overhead + prefix = prefix + keySeparator + memberName + } + return &Array{ values: values, prefix: prefix, - flat: flat, - memberName: memberName, emptyValue: emptyValue, } } @@ -63,10 +55,7 @@ func (a *Array) Value() Value { // Query lists start a 1, so adjust the size first a.size++ - prefix := a.prefix - if !a.flat { - prefix = fmt.Sprintf("%s.%s", prefix, a.memberName) - } // Lists can't have flat members - return newValue(a.values, fmt.Sprintf("%s.%d", prefix, a.size), false) + // This uses string concatenation in place of fmt.Sprintf as fmt.Sprintf has a much higher resource overhead + return newValue(a.values, a.prefix+keySeparator+strconv.FormatInt(int64(a.size), 10), false) } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/object.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/object.go index 455b92515c..305a8ace30 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/object.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/object.go @@ -1,9 +1,6 @@ package query -import ( - "fmt" - "net/url" -) +import "net/url" // Object represents the encoding of Query structures and unions. A Query // object is a representation of a mapping of string keys to arbitrary @@ -56,14 +53,16 @@ func (o *Object) FlatKey(name string) Value { func (o *Object) key(name string, flatValue bool) Value { if o.prefix != "" { - return newValue(o.values, fmt.Sprintf("%s.%s", o.prefix, name), flatValue) + // This uses string concatenation in place of fmt.Sprintf as fmt.Sprintf has a much higher resource overhead + return newValue(o.values, o.prefix+keySeparator+name, flatValue) } return newValue(o.values, name, flatValue) } func (o *Object) keyWithValues(name string, flatValue bool) Value { if o.prefix != "" { - return newAppendValue(o.values, fmt.Sprintf("%s.%s", o.prefix, name), flatValue) + // This uses string concatenation in place of fmt.Sprintf as fmt.Sprintf has a much higher resource overhead + return newAppendValue(o.values, o.prefix+keySeparator+name, flatValue) } return newAppendValue(o.values, name, flatValue) } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/value.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/value.go index a9251521f1..8063c592dd 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/value.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/value.go @@ -7,6 +7,8 @@ import ( "github.com/aws/smithy-go/encoding/httpbinding" ) +const keySeparator = "." + // Value represents a Query Value type. type Value struct { // The query values to add the value to. diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/retryable_error.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/retryable_error.go index acd8d1cc3d..1b485f9988 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/retryable_error.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/retryable_error.go @@ -116,7 +116,13 @@ func (r RetryableConnectionError) IsErrorRetryable(err error) aws.Ternary { case errors.As(err, &conErr) && conErr.ConnectionError(): retryable = true + case strings.Contains(err.Error(), "use of closed network connection"): + fallthrough case strings.Contains(err.Error(), "connection reset"): + // The errors "connection reset" and "use of closed network connection" + // are effectively the same. It appears to be the difference between + // sync and async read of TCP RST in the stdlib's net.Conn read loop. + // see #2737 retryable = true case errors.As(err, &urlErr): diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/headers.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/headers.go index 734e548bd6..d99b32ceb0 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/headers.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/headers.go @@ -4,10 +4,11 @@ package v4 var IgnoredHeaders = Rules{ ExcludeList{ MapRule{ - "Authorization": struct{}{}, - "User-Agent": struct{}{}, - "X-Amzn-Trace-Id": struct{}{}, - "Expect": struct{}{}, + "Authorization": struct{}{}, + "User-Agent": struct{}{}, + "X-Amzn-Trace-Id": struct{}{}, + "Expect": struct{}{}, + "Transfer-Encoding": struct{}{}, }, }, } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/config/CHANGELOG.md index 52b2856c9a..e28d91766b 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/config/CHANGELOG.md @@ -1,3 +1,50 @@ +# v1.29.6 (2025-02-05) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.29.5 (2025-02-04) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.29.4 (2025-01-31) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.29.3 (2025-01-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.29.2 (2025-01-24) + +* **Bug Fix**: Fix env config naming and usage of deprecated ioutil +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.22.2. + +# v1.29.1 (2025-01-17) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.29.0 (2025-01-15) + +* **Feature**: S3 client behavior is updated to always calculate a checksum by default for operations that support it (such as PutObject or UploadPart), or require it (such as DeleteObjects). The checksum algorithm used by default now becomes CRC32. Checksum behavior can be configured using `when_supported` and `when_required` options - in code using RequestChecksumCalculation, in shared config using request_checksum_calculation, or as env variable using AWS_REQUEST_CHECKSUM_CALCULATION. The S3 client attempts to validate response checksums for all S3 API operations that support checksums. However, if the SDK has not implemented the specified checksum algorithm then this validation is skipped. Checksum validation behavior can be configured using `when_supported` and `when_required` options - in code using ResponseChecksumValidation, in shared config using response_checksum_validation, or as env variable using AWS_RESPONSE_CHECKSUM_VALIDATION. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.28.11 (2025-01-14) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.28.10 (2025-01-10) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.28.9 (2025-01-09) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.28.8 (2025-01-08) + +* **Dependency Update**: Updated to the latest SDK module versions + # v1.28.7 (2024-12-19) * **Bug Fix**: Fix improper use of printf-style functions. diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/config.go b/vendor/github.com/aws/aws-sdk-go-v2/config/config.go index d5226cb043..09d9b63116 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/config.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/config/config.go @@ -83,6 +83,12 @@ var defaultAWSConfigResolvers = []awsConfigResolver{ // Sets the AccountIDEndpointMode if present in env var or shared config profile resolveAccountIDEndpointMode, + + // Sets the RequestChecksumCalculation if present in env var or shared config profile + resolveRequestChecksumCalculation, + + // Sets the ResponseChecksumValidation if present in env var or shared config profile + resolveResponseChecksumValidation, } // A Config represents a generic configuration value or set of values. This type @@ -212,7 +218,7 @@ func resolveConfigLoaders(options *LoadOptions) []loader { loaders[0] = loadEnvConfig // specification of a profile should cause a load failure if it doesn't exist - if os.Getenv(awsProfileEnvVar) != "" || options.SharedConfigProfile != "" { + if os.Getenv(awsProfileEnv) != "" || options.SharedConfigProfile != "" { loaders[1] = loadSharedConfig } else { loaders[1] = loadSharedConfigIgnoreNotExist diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/env_config.go b/vendor/github.com/aws/aws-sdk-go-v2/config/env_config.go index 3a06f1412a..9db507e38e 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/env_config.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/config/env_config.go @@ -5,7 +5,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "os" "strconv" "strings" @@ -21,86 +20,89 @@ const CredentialsSourceName = "EnvConfigCredentials" // Environment variables that will be read for configuration values. const ( - awsAccessKeyIDEnvVar = "AWS_ACCESS_KEY_ID" - awsAccessKeyEnvVar = "AWS_ACCESS_KEY" + awsAccessKeyIDEnv = "AWS_ACCESS_KEY_ID" + awsAccessKeyEnv = "AWS_ACCESS_KEY" - awsSecretAccessKeyEnvVar = "AWS_SECRET_ACCESS_KEY" - awsSecretKeyEnvVar = "AWS_SECRET_KEY" + awsSecretAccessKeyEnv = "AWS_SECRET_ACCESS_KEY" + awsSecretKeyEnv = "AWS_SECRET_KEY" - awsSessionTokenEnvVar = "AWS_SESSION_TOKEN" + awsSessionTokenEnv = "AWS_SESSION_TOKEN" - awsContainerCredentialsEndpointEnvVar = "AWS_CONTAINER_CREDENTIALS_FULL_URI" - awsContainerCredentialsRelativePathEnvVar = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" - awsContainerPProviderAuthorizationEnvVar = "AWS_CONTAINER_AUTHORIZATION_TOKEN" + awsContainerCredentialsFullURIEnv = "AWS_CONTAINER_CREDENTIALS_FULL_URI" + awsContainerCredentialsRelativeURIEnv = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" + awsContainerAuthorizationTokenEnv = "AWS_CONTAINER_AUTHORIZATION_TOKEN" - awsRegionEnvVar = "AWS_REGION" - awsDefaultRegionEnvVar = "AWS_DEFAULT_REGION" + awsRegionEnv = "AWS_REGION" + awsDefaultRegionEnv = "AWS_DEFAULT_REGION" - awsProfileEnvVar = "AWS_PROFILE" - awsDefaultProfileEnvVar = "AWS_DEFAULT_PROFILE" + awsProfileEnv = "AWS_PROFILE" + awsDefaultProfileEnv = "AWS_DEFAULT_PROFILE" - awsSharedCredentialsFileEnvVar = "AWS_SHARED_CREDENTIALS_FILE" + awsSharedCredentialsFileEnv = "AWS_SHARED_CREDENTIALS_FILE" - awsConfigFileEnvVar = "AWS_CONFIG_FILE" + awsConfigFileEnv = "AWS_CONFIG_FILE" - awsCustomCABundleEnvVar = "AWS_CA_BUNDLE" + awsCABundleEnv = "AWS_CA_BUNDLE" - awsWebIdentityTokenFilePathEnvVar = "AWS_WEB_IDENTITY_TOKEN_FILE" + awsWebIdentityTokenFileEnv = "AWS_WEB_IDENTITY_TOKEN_FILE" - awsRoleARNEnvVar = "AWS_ROLE_ARN" - awsRoleSessionNameEnvVar = "AWS_ROLE_SESSION_NAME" + awsRoleARNEnv = "AWS_ROLE_ARN" + awsRoleSessionNameEnv = "AWS_ROLE_SESSION_NAME" - awsEnableEndpointDiscoveryEnvVar = "AWS_ENABLE_ENDPOINT_DISCOVERY" + awsEnableEndpointDiscoveryEnv = "AWS_ENABLE_ENDPOINT_DISCOVERY" - awsS3UseARNRegionEnvVar = "AWS_S3_USE_ARN_REGION" + awsS3UseARNRegionEnv = "AWS_S3_USE_ARN_REGION" - awsEc2MetadataServiceEndpointModeEnvVar = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE" + awsEc2MetadataServiceEndpointModeEnv = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE" - awsEc2MetadataServiceEndpointEnvVar = "AWS_EC2_METADATA_SERVICE_ENDPOINT" + awsEc2MetadataServiceEndpointEnv = "AWS_EC2_METADATA_SERVICE_ENDPOINT" - awsEc2MetadataDisabled = "AWS_EC2_METADATA_DISABLED" - awsEc2MetadataV1DisabledEnvVar = "AWS_EC2_METADATA_V1_DISABLED" + awsEc2MetadataDisabledEnv = "AWS_EC2_METADATA_DISABLED" + awsEc2MetadataV1DisabledEnv = "AWS_EC2_METADATA_V1_DISABLED" - awsS3DisableMultiRegionAccessPointEnvVar = "AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS" + awsS3DisableMultiRegionAccessPointsEnv = "AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS" - awsUseDualStackEndpoint = "AWS_USE_DUALSTACK_ENDPOINT" + awsUseDualStackEndpointEnv = "AWS_USE_DUALSTACK_ENDPOINT" - awsUseFIPSEndpoint = "AWS_USE_FIPS_ENDPOINT" + awsUseFIPSEndpointEnv = "AWS_USE_FIPS_ENDPOINT" - awsDefaultMode = "AWS_DEFAULTS_MODE" + awsDefaultsModeEnv = "AWS_DEFAULTS_MODE" - awsRetryMaxAttempts = "AWS_MAX_ATTEMPTS" - awsRetryMode = "AWS_RETRY_MODE" - awsSdkAppID = "AWS_SDK_UA_APP_ID" + awsMaxAttemptsEnv = "AWS_MAX_ATTEMPTS" + awsRetryModeEnv = "AWS_RETRY_MODE" + awsSdkUaAppIDEnv = "AWS_SDK_UA_APP_ID" - awsIgnoreConfiguredEndpoints = "AWS_IGNORE_CONFIGURED_ENDPOINT_URLS" - awsEndpointURL = "AWS_ENDPOINT_URL" + awsIgnoreConfiguredEndpointURLEnv = "AWS_IGNORE_CONFIGURED_ENDPOINT_URLS" + awsEndpointURLEnv = "AWS_ENDPOINT_URL" - awsDisableRequestCompression = "AWS_DISABLE_REQUEST_COMPRESSION" - awsRequestMinCompressionSizeBytes = "AWS_REQUEST_MIN_COMPRESSION_SIZE_BYTES" + awsDisableRequestCompressionEnv = "AWS_DISABLE_REQUEST_COMPRESSION" + awsRequestMinCompressionSizeBytesEnv = "AWS_REQUEST_MIN_COMPRESSION_SIZE_BYTES" awsS3DisableExpressSessionAuthEnv = "AWS_S3_DISABLE_EXPRESS_SESSION_AUTH" awsAccountIDEnv = "AWS_ACCOUNT_ID" awsAccountIDEndpointModeEnv = "AWS_ACCOUNT_ID_ENDPOINT_MODE" + + awsRequestChecksumCalculation = "AWS_REQUEST_CHECKSUM_CALCULATION" + awsResponseChecksumValidation = "AWS_RESPONSE_CHECKSUM_VALIDATION" ) var ( credAccessEnvKeys = []string{ - awsAccessKeyIDEnvVar, - awsAccessKeyEnvVar, + awsAccessKeyIDEnv, + awsAccessKeyEnv, } credSecretEnvKeys = []string{ - awsSecretAccessKeyEnvVar, - awsSecretKeyEnvVar, + awsSecretAccessKeyEnv, + awsSecretKeyEnv, } regionEnvKeys = []string{ - awsRegionEnvVar, - awsDefaultRegionEnvVar, + awsRegionEnv, + awsDefaultRegionEnv, } profileEnvKeys = []string{ - awsProfileEnvVar, - awsDefaultProfileEnvVar, + awsProfileEnv, + awsDefaultProfileEnv, } ) @@ -296,6 +298,12 @@ type EnvConfig struct { // Indicates whether account ID will be required/ignored in endpoint2.0 routing AccountIDEndpointMode aws.AccountIDEndpointMode + + // Indicates whether request checksum should be calculated + RequestChecksumCalculation aws.RequestChecksumCalculation + + // Indicates whether response checksum should be validated + ResponseChecksumValidation aws.ResponseChecksumValidation } // loadEnvConfig reads configuration values from the OS's environment variables. @@ -316,79 +324,79 @@ func NewEnvConfig() (EnvConfig, error) { setStringFromEnvVal(&creds.SecretAccessKey, credSecretEnvKeys) if creds.HasKeys() { creds.AccountID = os.Getenv(awsAccountIDEnv) - creds.SessionToken = os.Getenv(awsSessionTokenEnvVar) + creds.SessionToken = os.Getenv(awsSessionTokenEnv) cfg.Credentials = creds } - cfg.ContainerCredentialsEndpoint = os.Getenv(awsContainerCredentialsEndpointEnvVar) - cfg.ContainerCredentialsRelativePath = os.Getenv(awsContainerCredentialsRelativePathEnvVar) - cfg.ContainerAuthorizationToken = os.Getenv(awsContainerPProviderAuthorizationEnvVar) + cfg.ContainerCredentialsEndpoint = os.Getenv(awsContainerCredentialsFullURIEnv) + cfg.ContainerCredentialsRelativePath = os.Getenv(awsContainerCredentialsRelativeURIEnv) + cfg.ContainerAuthorizationToken = os.Getenv(awsContainerAuthorizationTokenEnv) setStringFromEnvVal(&cfg.Region, regionEnvKeys) setStringFromEnvVal(&cfg.SharedConfigProfile, profileEnvKeys) - cfg.SharedCredentialsFile = os.Getenv(awsSharedCredentialsFileEnvVar) - cfg.SharedConfigFile = os.Getenv(awsConfigFileEnvVar) + cfg.SharedCredentialsFile = os.Getenv(awsSharedCredentialsFileEnv) + cfg.SharedConfigFile = os.Getenv(awsConfigFileEnv) - cfg.CustomCABundle = os.Getenv(awsCustomCABundleEnvVar) + cfg.CustomCABundle = os.Getenv(awsCABundleEnv) - cfg.WebIdentityTokenFilePath = os.Getenv(awsWebIdentityTokenFilePathEnvVar) + cfg.WebIdentityTokenFilePath = os.Getenv(awsWebIdentityTokenFileEnv) - cfg.RoleARN = os.Getenv(awsRoleARNEnvVar) - cfg.RoleSessionName = os.Getenv(awsRoleSessionNameEnvVar) + cfg.RoleARN = os.Getenv(awsRoleARNEnv) + cfg.RoleSessionName = os.Getenv(awsRoleSessionNameEnv) - cfg.AppID = os.Getenv(awsSdkAppID) + cfg.AppID = os.Getenv(awsSdkUaAppIDEnv) - if err := setBoolPtrFromEnvVal(&cfg.DisableRequestCompression, []string{awsDisableRequestCompression}); err != nil { + if err := setBoolPtrFromEnvVal(&cfg.DisableRequestCompression, []string{awsDisableRequestCompressionEnv}); err != nil { return cfg, err } - if err := setInt64PtrFromEnvVal(&cfg.RequestMinCompressSizeBytes, []string{awsRequestMinCompressionSizeBytes}, smithyrequestcompression.MaxRequestMinCompressSizeBytes); err != nil { + if err := setInt64PtrFromEnvVal(&cfg.RequestMinCompressSizeBytes, []string{awsRequestMinCompressionSizeBytesEnv}, smithyrequestcompression.MaxRequestMinCompressSizeBytes); err != nil { return cfg, err } - if err := setEndpointDiscoveryTypeFromEnvVal(&cfg.EnableEndpointDiscovery, []string{awsEnableEndpointDiscoveryEnvVar}); err != nil { + if err := setEndpointDiscoveryTypeFromEnvVal(&cfg.EnableEndpointDiscovery, []string{awsEnableEndpointDiscoveryEnv}); err != nil { return cfg, err } - if err := setBoolPtrFromEnvVal(&cfg.S3UseARNRegion, []string{awsS3UseARNRegionEnvVar}); err != nil { + if err := setBoolPtrFromEnvVal(&cfg.S3UseARNRegion, []string{awsS3UseARNRegionEnv}); err != nil { return cfg, err } - setEC2IMDSClientEnableState(&cfg.EC2IMDSClientEnableState, []string{awsEc2MetadataDisabled}) - if err := setEC2IMDSEndpointMode(&cfg.EC2IMDSEndpointMode, []string{awsEc2MetadataServiceEndpointModeEnvVar}); err != nil { + setEC2IMDSClientEnableState(&cfg.EC2IMDSClientEnableState, []string{awsEc2MetadataDisabledEnv}) + if err := setEC2IMDSEndpointMode(&cfg.EC2IMDSEndpointMode, []string{awsEc2MetadataServiceEndpointModeEnv}); err != nil { return cfg, err } - cfg.EC2IMDSEndpoint = os.Getenv(awsEc2MetadataServiceEndpointEnvVar) - if err := setBoolPtrFromEnvVal(&cfg.EC2IMDSv1Disabled, []string{awsEc2MetadataV1DisabledEnvVar}); err != nil { + cfg.EC2IMDSEndpoint = os.Getenv(awsEc2MetadataServiceEndpointEnv) + if err := setBoolPtrFromEnvVal(&cfg.EC2IMDSv1Disabled, []string{awsEc2MetadataV1DisabledEnv}); err != nil { return cfg, err } - if err := setBoolPtrFromEnvVal(&cfg.S3DisableMultiRegionAccessPoints, []string{awsS3DisableMultiRegionAccessPointEnvVar}); err != nil { + if err := setBoolPtrFromEnvVal(&cfg.S3DisableMultiRegionAccessPoints, []string{awsS3DisableMultiRegionAccessPointsEnv}); err != nil { return cfg, err } - if err := setUseDualStackEndpointFromEnvVal(&cfg.UseDualStackEndpoint, []string{awsUseDualStackEndpoint}); err != nil { + if err := setUseDualStackEndpointFromEnvVal(&cfg.UseDualStackEndpoint, []string{awsUseDualStackEndpointEnv}); err != nil { return cfg, err } - if err := setUseFIPSEndpointFromEnvVal(&cfg.UseFIPSEndpoint, []string{awsUseFIPSEndpoint}); err != nil { + if err := setUseFIPSEndpointFromEnvVal(&cfg.UseFIPSEndpoint, []string{awsUseFIPSEndpointEnv}); err != nil { return cfg, err } - if err := setDefaultsModeFromEnvVal(&cfg.DefaultsMode, []string{awsDefaultMode}); err != nil { + if err := setDefaultsModeFromEnvVal(&cfg.DefaultsMode, []string{awsDefaultsModeEnv}); err != nil { return cfg, err } - if err := setIntFromEnvVal(&cfg.RetryMaxAttempts, []string{awsRetryMaxAttempts}); err != nil { + if err := setIntFromEnvVal(&cfg.RetryMaxAttempts, []string{awsMaxAttemptsEnv}); err != nil { return cfg, err } - if err := setRetryModeFromEnvVal(&cfg.RetryMode, []string{awsRetryMode}); err != nil { + if err := setRetryModeFromEnvVal(&cfg.RetryMode, []string{awsRetryModeEnv}); err != nil { return cfg, err } - setStringFromEnvVal(&cfg.BaseEndpoint, []string{awsEndpointURL}) + setStringFromEnvVal(&cfg.BaseEndpoint, []string{awsEndpointURLEnv}) - if err := setBoolPtrFromEnvVal(&cfg.IgnoreConfiguredEndpoints, []string{awsIgnoreConfiguredEndpoints}); err != nil { + if err := setBoolPtrFromEnvVal(&cfg.IgnoreConfiguredEndpoints, []string{awsIgnoreConfiguredEndpointURLEnv}); err != nil { return cfg, err } @@ -400,6 +408,13 @@ func NewEnvConfig() (EnvConfig, error) { return cfg, err } + if err := setRequestChecksumCalculationFromEnvVal(&cfg.RequestChecksumCalculation, []string{awsRequestChecksumCalculation}); err != nil { + return cfg, err + } + if err := setResponseChecksumValidationFromEnvVal(&cfg.ResponseChecksumValidation, []string{awsResponseChecksumValidation}); err != nil { + return cfg, err + } + return cfg, nil } @@ -432,6 +447,14 @@ func (c EnvConfig) getAccountIDEndpointMode(context.Context) (aws.AccountIDEndpo return c.AccountIDEndpointMode, len(c.AccountIDEndpointMode) > 0, nil } +func (c EnvConfig) getRequestChecksumCalculation(context.Context) (aws.RequestChecksumCalculation, bool, error) { + return c.RequestChecksumCalculation, c.RequestChecksumCalculation > 0, nil +} + +func (c EnvConfig) getResponseChecksumValidation(context.Context) (aws.ResponseChecksumValidation, bool, error) { + return c.ResponseChecksumValidation, c.ResponseChecksumValidation > 0, nil +} + // GetRetryMaxAttempts returns the value of AWS_MAX_ATTEMPTS if was specified, // and not 0. func (c EnvConfig) GetRetryMaxAttempts(ctx context.Context) (int, bool, error) { @@ -528,6 +551,45 @@ func setAIDEndPointModeFromEnvVal(m *aws.AccountIDEndpointMode, keys []string) e return nil } +func setRequestChecksumCalculationFromEnvVal(m *aws.RequestChecksumCalculation, keys []string) error { + for _, k := range keys { + value := os.Getenv(k) + if len(value) == 0 { + continue + } + + switch strings.ToLower(value) { + case checksumWhenSupported: + *m = aws.RequestChecksumCalculationWhenSupported + case checksumWhenRequired: + *m = aws.RequestChecksumCalculationWhenRequired + default: + return fmt.Errorf("invalid value for environment variable, %s=%s, must be when_supported/when_required", k, value) + } + } + return nil +} + +func setResponseChecksumValidationFromEnvVal(m *aws.ResponseChecksumValidation, keys []string) error { + for _, k := range keys { + value := os.Getenv(k) + if len(value) == 0 { + continue + } + + switch strings.ToLower(value) { + case checksumWhenSupported: + *m = aws.ResponseChecksumValidationWhenSupported + case checksumWhenRequired: + *m = aws.ResponseChecksumValidationWhenRequired + default: + return fmt.Errorf("invalid value for environment variable, %s=%s, must be when_supported/when_required", k, value) + } + + } + return nil +} + // GetRegion returns the AWS Region if set in the environment. Returns an empty // string if not set. func (c EnvConfig) getRegion(ctx context.Context) (string, bool, error) { @@ -584,7 +646,7 @@ func (c EnvConfig) getCustomCABundle(context.Context) (io.Reader, bool, error) { return nil, false, nil } - b, err := ioutil.ReadFile(c.CustomCABundle) + b, err := os.ReadFile(c.CustomCABundle) if err != nil { return nil, false, err } @@ -608,7 +670,7 @@ func (c EnvConfig) getBaseEndpoint(context.Context) (string, bool, error) { // GetServiceBaseEndpoint is used to retrieve a normalized SDK ID for use // with configured endpoints. func (c EnvConfig) GetServiceBaseEndpoint(ctx context.Context, sdkID string) (string, bool, error) { - if endpt := os.Getenv(fmt.Sprintf("%s_%s", awsEndpointURL, normalizeEnv(sdkID))); endpt != "" { + if endpt := os.Getenv(fmt.Sprintf("%s_%s", awsEndpointURLEnv, normalizeEnv(sdkID))); endpt != "" { return endpt, true, nil } return "", false, nil diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/config/go_module_metadata.go index 56fb062cfe..d30e01dc87 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/config/go_module_metadata.go @@ -3,4 +3,4 @@ package config // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.28.7" +const goModuleVersion = "1.29.6" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/load_options.go b/vendor/github.com/aws/aws-sdk-go-v2/config/load_options.go index dc6c7d29a8..0810ecf16a 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/load_options.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/config/load_options.go @@ -216,8 +216,15 @@ type LoadOptions struct { // Whether S3 Express auth is disabled. S3DisableExpressAuth *bool + // Whether account id should be built into endpoint resolution AccountIDEndpointMode aws.AccountIDEndpointMode + // Specify if request checksum should be calculated + RequestChecksumCalculation aws.RequestChecksumCalculation + + // Specifies if response checksum should be validated + ResponseChecksumValidation aws.ResponseChecksumValidation + // Service endpoint override. This value is not necessarily final and is // passed to the service's EndpointResolverV2 for further delegation. BaseEndpoint string @@ -288,6 +295,14 @@ func (o LoadOptions) getAccountIDEndpointMode(ctx context.Context) (aws.AccountI return o.AccountIDEndpointMode, len(o.AccountIDEndpointMode) > 0, nil } +func (o LoadOptions) getRequestChecksumCalculation(ctx context.Context) (aws.RequestChecksumCalculation, bool, error) { + return o.RequestChecksumCalculation, o.RequestChecksumCalculation > 0, nil +} + +func (o LoadOptions) getResponseChecksumValidation(ctx context.Context) (aws.ResponseChecksumValidation, bool, error) { + return o.ResponseChecksumValidation, o.ResponseChecksumValidation > 0, nil +} + func (o LoadOptions) getBaseEndpoint(context.Context) (string, bool, error) { return o.BaseEndpoint, o.BaseEndpoint != "", nil } @@ -357,6 +372,26 @@ func WithAccountIDEndpointMode(m aws.AccountIDEndpointMode) LoadOptionsFunc { } } +// WithRequestChecksumCalculation is a helper function to construct functional options +// that sets RequestChecksumCalculation on config's LoadOptions +func WithRequestChecksumCalculation(c aws.RequestChecksumCalculation) LoadOptionsFunc { + return func(o *LoadOptions) error { + if c > 0 { + o.RequestChecksumCalculation = c + } + return nil + } +} + +// WithResponseChecksumValidation is a helper function to construct functional options +// that sets ResponseChecksumValidation on config's LoadOptions +func WithResponseChecksumValidation(v aws.ResponseChecksumValidation) LoadOptionsFunc { + return func(o *LoadOptions) error { + o.ResponseChecksumValidation = v + return nil + } +} + // getDefaultRegion returns DefaultRegion from config's LoadOptions func (o LoadOptions) getDefaultRegion(ctx context.Context) (string, bool, error) { if len(o.DefaultRegion) == 0 { diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/provider.go b/vendor/github.com/aws/aws-sdk-go-v2/config/provider.go index 043781f1f7..a8ff40d846 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/provider.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/config/provider.go @@ -242,6 +242,40 @@ func getAccountIDEndpointMode(ctx context.Context, configs configs) (value aws.A return } +// requestChecksumCalculationProvider provides access to the RequestChecksumCalculation +type requestChecksumCalculationProvider interface { + getRequestChecksumCalculation(context.Context) (aws.RequestChecksumCalculation, bool, error) +} + +func getRequestChecksumCalculation(ctx context.Context, configs configs) (value aws.RequestChecksumCalculation, found bool, err error) { + for _, cfg := range configs { + if p, ok := cfg.(requestChecksumCalculationProvider); ok { + value, found, err = p.getRequestChecksumCalculation(ctx) + if err != nil || found { + break + } + } + } + return +} + +// responseChecksumValidationProvider provides access to the ResponseChecksumValidation +type responseChecksumValidationProvider interface { + getResponseChecksumValidation(context.Context) (aws.ResponseChecksumValidation, bool, error) +} + +func getResponseChecksumValidation(ctx context.Context, configs configs) (value aws.ResponseChecksumValidation, found bool, err error) { + for _, cfg := range configs { + if p, ok := cfg.(responseChecksumValidationProvider); ok { + value, found, err = p.getResponseChecksumValidation(ctx) + if err != nil || found { + break + } + } + } + return +} + // ec2IMDSRegionProvider provides access to the ec2 imds region // configuration value type ec2IMDSRegionProvider interface { diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/resolve.go b/vendor/github.com/aws/aws-sdk-go-v2/config/resolve.go index 41009c7da0..a68bd0993f 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/resolve.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/config/resolve.go @@ -182,6 +182,36 @@ func resolveAccountIDEndpointMode(ctx context.Context, cfg *aws.Config, configs return nil } +// resolveRequestChecksumCalculation extracts the RequestChecksumCalculation from the configs slice's +// SharedConfig or EnvConfig +func resolveRequestChecksumCalculation(ctx context.Context, cfg *aws.Config, configs configs) error { + c, found, err := getRequestChecksumCalculation(ctx, configs) + if err != nil { + return err + } + + if !found { + c = aws.RequestChecksumCalculationWhenSupported + } + cfg.RequestChecksumCalculation = c + return nil +} + +// resolveResponseValidation extracts the ResponseChecksumValidation from the configs slice's +// SharedConfig or EnvConfig +func resolveResponseChecksumValidation(ctx context.Context, cfg *aws.Config, configs configs) error { + c, found, err := getResponseChecksumValidation(ctx, configs) + if err != nil { + return err + } + + if !found { + c = aws.ResponseChecksumValidationWhenSupported + } + cfg.ResponseChecksumValidation = c + return nil +} + // resolveDefaultRegion extracts the first instance of a default region and sets `aws.Config.Region` to the default // region if region had not been resolved from other sources. func resolveDefaultRegion(ctx context.Context, cfg *aws.Config, configs configs) error { diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/shared_config.go b/vendor/github.com/aws/aws-sdk-go-v2/config/shared_config.go index d7a2b5307e..00b071fe6f 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/shared_config.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/config/shared_config.go @@ -118,6 +118,11 @@ const ( accountIDKey = "aws_account_id" accountIDEndpointMode = "account_id_endpoint_mode" + + requestChecksumCalculationKey = "request_checksum_calculation" + responseChecksumValidationKey = "response_checksum_validation" + checksumWhenSupported = "when_supported" + checksumWhenRequired = "when_required" ) // defaultSharedConfigProfile allows for swapping the default profile for testing @@ -346,6 +351,12 @@ type SharedConfig struct { S3DisableExpressAuth *bool AccountIDEndpointMode aws.AccountIDEndpointMode + + // RequestChecksumCalculation indicates if the request checksum should be calculated + RequestChecksumCalculation aws.RequestChecksumCalculation + + // ResponseChecksumValidation indicates if the response checksum should be validated + ResponseChecksumValidation aws.ResponseChecksumValidation } func (c SharedConfig) getDefaultsMode(ctx context.Context) (value aws.DefaultsMode, ok bool, err error) { @@ -1133,6 +1144,13 @@ func (c *SharedConfig) setFromIniSection(profile string, section ini.Section) er return fmt.Errorf("failed to load %s from shared config, %w", accountIDEndpointMode, err) } + if err := updateRequestChecksumCalculation(&c.RequestChecksumCalculation, section, requestChecksumCalculationKey); err != nil { + return fmt.Errorf("failed to load %s from shared config, %w", requestChecksumCalculationKey, err) + } + if err := updateResponseChecksumValidation(&c.ResponseChecksumValidation, section, responseChecksumValidationKey); err != nil { + return fmt.Errorf("failed to load %s from shared config, %w", responseChecksumValidationKey, err) + } + // Shared Credentials creds := aws.Credentials{ AccessKeyID: section.String(accessKeyIDKey), @@ -1207,6 +1225,42 @@ func updateAIDEndpointMode(m *aws.AccountIDEndpointMode, sec ini.Section, key st return nil } +func updateRequestChecksumCalculation(m *aws.RequestChecksumCalculation, sec ini.Section, key string) error { + if !sec.Has(key) { + return nil + } + + v := sec.String(key) + switch strings.ToLower(v) { + case checksumWhenSupported: + *m = aws.RequestChecksumCalculationWhenSupported + case checksumWhenRequired: + *m = aws.RequestChecksumCalculationWhenRequired + default: + return fmt.Errorf("invalid value for shared config profile field, %s=%s, must be when_supported/when_required", key, v) + } + + return nil +} + +func updateResponseChecksumValidation(m *aws.ResponseChecksumValidation, sec ini.Section, key string) error { + if !sec.Has(key) { + return nil + } + + v := sec.String(key) + switch strings.ToLower(v) { + case checksumWhenSupported: + *m = aws.ResponseChecksumValidationWhenSupported + case checksumWhenRequired: + *m = aws.ResponseChecksumValidationWhenRequired + default: + return fmt.Errorf("invalid value for shared config profile field, %s=%s, must be when_supported/when_required", key, v) + } + + return nil +} + func (c SharedConfig) getRequestMinCompressSizeBytes(ctx context.Context) (int64, bool, error) { if c.RequestMinCompressSizeBytes == nil { return 0, false, nil @@ -1225,6 +1279,14 @@ func (c SharedConfig) getAccountIDEndpointMode(ctx context.Context) (aws.Account return c.AccountIDEndpointMode, len(c.AccountIDEndpointMode) > 0, nil } +func (c SharedConfig) getRequestChecksumCalculation(ctx context.Context) (aws.RequestChecksumCalculation, bool, error) { + return c.RequestChecksumCalculation, c.RequestChecksumCalculation > 0, nil +} + +func (c SharedConfig) getResponseChecksumValidation(ctx context.Context) (aws.ResponseChecksumValidation, bool, error) { + return c.ResponseChecksumValidation, c.ResponseChecksumValidation > 0, nil +} + func updateDefaultsMode(mode *aws.DefaultsMode, section ini.Section, key string) error { if !section.Has(key) { return nil diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/credentials/CHANGELOG.md index 67843c3125..4ea068d62d 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/credentials/CHANGELOG.md @@ -1,3 +1,48 @@ +# v1.17.59 (2025-02-05) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.17.58 (2025-02-04) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.17.57 (2025-01-31) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.17.56 (2025-01-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.17.55 (2025-01-24) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.22.2. + +# v1.17.54 (2025-01-17) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.17.53 (2025-01-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.17.52 (2025-01-14) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.17.51 (2025-01-10) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.17.50 (2025-01-09) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.17.49 (2025-01-08) + +* **Dependency Update**: Updated to the latest SDK module versions + # v1.17.48 (2024-12-19) * **Bug Fix**: Fix improper use of printf-style functions. diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/go_module_metadata.go index f674eaa72c..280ad9ac13 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/credentials/go_module_metadata.go @@ -3,4 +3,4 @@ package credentials // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.17.48" +const goModuleVersion = "1.17.59" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/CHANGELOG.md index 9862361e03..d3bdd7b183 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/CHANGELOG.md @@ -1,3 +1,28 @@ +# v1.16.28 (2025-02-05) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.16.27 (2025-01-31) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.16.26 (2025-01-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.16.25 (2025-01-24) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.22.2. + +# v1.16.24 (2025-01-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.16.23 (2025-01-09) + +* **Dependency Update**: Updated to the latest SDK module versions + # v1.16.22 (2024-12-19) * **Dependency Update**: Updated to the latest SDK module versions diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/go_module_metadata.go index 3f1bc52a9c..a6d7e4d0aa 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/go_module_metadata.go @@ -3,4 +3,4 @@ package imds // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.16.22" +const goModuleVersion = "1.16.28" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/CHANGELOG.md index 5a5cdf0698..9c48f2ec98 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/CHANGELOG.md @@ -1,3 +1,28 @@ +# v1.3.32 (2025-02-05) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.3.31 (2025-01-31) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.3.30 (2025-01-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.3.29 (2025-01-24) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.22.2. + +# v1.3.28 (2025-01-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.3.27 (2025-01-09) + +* **Dependency Update**: Updated to the latest SDK module versions + # v1.3.26 (2024-12-19) * **Dependency Update**: Updated to the latest SDK module versions diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/go_module_metadata.go index a46fe9de69..7554df9a6b 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/go_module_metadata.go @@ -3,4 +3,4 @@ package configsources // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.3.26" +const goModuleVersion = "1.3.32" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.json b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.json index a2f0680888..43f6449be3 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.json +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.json @@ -47,6 +47,9 @@ "ap-southeast-5" : { "description" : "Asia Pacific (Malaysia)" }, + "ap-southeast-7" : { + "description" : "Asia Pacific (Thailand)" + }, "aws-global" : { "description" : "AWS Standard global region" }, @@ -89,6 +92,9 @@ "me-south-1" : { "description" : "Middle East (Bahrain)" }, + "mx-central-1" : { + "description" : "Mexico (Central)" + }, "sa-east-1" : { "description" : "South America (Sao Paulo)" }, diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/CHANGELOG.md index 748a80fb0f..103e54167f 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/CHANGELOG.md @@ -1,3 +1,28 @@ +# v2.6.32 (2025-02-05) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v2.6.31 (2025-01-31) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v2.6.30 (2025-01-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v2.6.29 (2025-01-24) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.22.2. + +# v2.6.28 (2025-01-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v2.6.27 (2025-01-09) + +* **Dependency Update**: Updated to the latest SDK module versions + # v2.6.26 (2024-12-19) * **Bug Fix**: Fix improper use of printf-style functions. diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/go_module_metadata.go index 6a5a4b648e..64106ff768 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/go_module_metadata.go @@ -3,4 +3,4 @@ package endpoints // goModuleVersion is the tagged release for this module -const goModuleVersion = "2.6.26" +const goModuleVersion = "2.6.32" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/CHANGELOG.md index be61098b46..1d23b9be22 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/CHANGELOG.md @@ -1,3 +1,7 @@ +# v1.8.2 (2025-01-24) + +* **Bug Fix**: Refactor filepath.Walk to filepath.WalkDir + # v1.8.1 (2024-08-15) * **Dependency Update**: Bump minimum Go version to 1.21. diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/go_module_metadata.go index ef6a38110e..355ed39e11 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/go_module_metadata.go @@ -3,4 +3,4 @@ package ini // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.8.1" +const goModuleVersion = "1.8.2" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/CHANGELOG.md index ac06c36355..4c2604e6b5 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/CHANGELOG.md @@ -1,3 +1,326 @@ +# v1.40.3 (2025-02-05) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.40.2 (2025-02-04) + +* No change notes available for this release. + +# v1.40.1 (2025-01-31) + +* **Dependency Update**: Switch to code-generated waiter matchers, removing the dependency on go-jmespath. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.40.0 (2025-01-30) + +* **Feature**: Temporarily updating dualstack endpoint support +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.39.0 (2025-01-29) + +* **Feature**: Add support for Dualstack and Dualstack-with-FIPS Endpoints + +# v1.38.7 (2025-01-24) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.22.2. + +# v1.38.6 (2025-01-17) + +* **Bug Fix**: Fix bug where credentials weren't refreshed during retry loop. + +# v1.38.5 (2025-01-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.38.4 (2025-01-14) + +* **Bug Fix**: Fix issue where waiters were not failing on unmatched errors as they should. This may have breaking behavioral changes for users in fringe cases. See [this announcement](https://github.com/aws/aws-sdk-go-v2/discussions/2954) for more information. + +# v1.38.3 (2025-01-09) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.38.2 (2025-01-08) + +* No change notes available for this release. + +# v1.38.1 (2025-01-03) + +* No change notes available for this release. + +# v1.38.0 (2024-12-28) + +* **Feature**: Restoring custom endpoint functionality for ECR + +# v1.37.0 (2024-12-26) + +* **Feature**: Add support for Dualstack Endpoints + +# v1.36.9 (2024-12-23) + +* **Documentation**: Documentation update for ECR GetAccountSetting and PutAccountSetting APIs. + +# v1.36.8 (2024-12-19) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.36.7 (2024-12-02) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.36.6 (2024-11-18) + +* **Dependency Update**: Update to smithy-go v1.22.1. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.36.5 (2024-11-07) + +* **Bug Fix**: Adds case-insensitive handling of error message fields in service responses + +# v1.36.4 (2024-11-06) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.36.3 (2024-10-28) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.36.2 (2024-10-08) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.36.1 (2024-10-07) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.36.0 (2024-10-04) + +* **Feature**: Add support for HTTP client metrics. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.35.4 (2024-10-03) + +* No change notes available for this release. + +# v1.35.3 (2024-09-27) + +* No change notes available for this release. + +# v1.35.2 (2024-09-25) + +* No change notes available for this release. + +# v1.35.1 (2024-09-23) + +* No change notes available for this release. + +# v1.35.0 (2024-09-20) + +* **Feature**: Add tracing and metrics support to service clients. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.34.0 (2024-09-17) + +* **Feature**: The `DescribeImageScanning` API now includes `fixAvailable`, `exploitAvailable`, and `fixedInVersion` fields to provide more detailed information about the availability of fixes, exploits, and fixed versions for identified image vulnerabilities. +* **Bug Fix**: **BREAKFIX**: Only generate AccountIDEndpointMode config for services that use it. This is a compiler break, but removes no actual functionality, as no services currently use the account ID in endpoint resolution. + +# v1.33.0 (2024-09-11) + +* **Feature**: Added KMS_DSSE to EncryptionType + +# v1.32.4 (2024-09-04) + +* No change notes available for this release. + +# v1.32.3 (2024-09-03) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.32.2 (2024-08-22) + +* No change notes available for this release. + +# v1.32.1 (2024-08-15) + +* **Dependency Update**: Bump minimum Go version to 1.21. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.32.0 (2024-08-05) + +* **Feature**: Released two new APIs along with documentation updates. The GetAccountSetting API is used to view the current basic scan type version setting for your registry, while the PutAccountSetting API is used to update the basic scan type version for your registry. + +# v1.31.0 (2024-07-25) + +* **Feature**: API and documentation updates for Amazon ECR, adding support for creating, updating, describing and deleting ECR Repository Creation Template. + +# v1.30.3 (2024-07-10.2) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.30.2 (2024-07-10) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.30.1 (2024-06-28) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.30.0 (2024-06-26) + +* **Feature**: Support list-of-string endpoint parameter. + +# v1.29.1 (2024-06-19) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.29.0 (2024-06-18) + +* **Feature**: Track usage of various AWS SDK features in user-agent string. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.28.6 (2024-06-17) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.28.5 (2024-06-07) + +* **Bug Fix**: Add clock skew correction on all service clients +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.28.4 (2024-06-03) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.28.3 (2024-05-23) + +* No change notes available for this release. + +# v1.28.2 (2024-05-16) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.28.1 (2024-05-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.28.0 (2024-05-08) + +* **Feature**: This release adds pull through cache rules support for GitLab container registry in Amazon ECR. +* **Bug Fix**: GoDoc improvement + +# v1.27.4 (2024-03-29) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.27.3 (2024-03-18) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.27.2 (2024-03-07) + +* **Bug Fix**: Remove dependency on go-cmp. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.27.1 (2024-02-23) + +* **Bug Fix**: Move all common, SDK-side middleware stack ops into the service client module to prevent cross-module compatibility issues in the future. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.27.0 (2024-02-22) + +* **Feature**: Add middleware stack snapshot tests. + +# v1.26.2 (2024-02-21) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.26.1 (2024-02-20) + +* **Bug Fix**: When sourcing values for a service's `EndpointParameters`, the lack of a configured region (i.e. `options.Region == ""`) will now translate to a `nil` value for `EndpointParameters.Region` instead of a pointer to the empty string `""`. This will result in a much more explicit error when calling an operation instead of an obscure hostname lookup failure. + +# v1.26.0 (2024-02-16) + +* **Feature**: Add new ClientOptions field to waiter config which allows you to extend the config for operation calls made by waiters. + +# v1.25.1 (2024-02-15) + +* **Bug Fix**: Correct failure to determine the error type in awsJson services that could occur when errors were modeled with a non-string `code` field. + +# v1.25.0 (2024-02-13) + +* **Feature**: Bump minimum Go version to 1.20 per our language support policy. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.24.7 (2024-01-04) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.24.6 (2023-12-20) + +* No change notes available for this release. + +# v1.24.5 (2023-12-08) + +* **Bug Fix**: Reinstate presence of default Retryer in functional options, but still respect max attempts set therein. + +# v1.24.4 (2023-12-07) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.24.3 (2023-12-06) + +* **Bug Fix**: Restore pre-refactor auth behavior where all operations could technically be performed anonymously. + +# v1.24.2 (2023-12-01) + +* **Bug Fix**: Correct wrapping of errors in authentication workflow. +* **Bug Fix**: Correctly recognize cache-wrapped instances of AnonymousCredentials at client construction. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.24.1 (2023-11-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.24.0 (2023-11-29) + +* **Feature**: Expose Options() accessor on service clients. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.23.3 (2023-11-28.2) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.23.2 (2023-11-28) + +* **Bug Fix**: Respect setting RetryMaxAttempts in functional options at client construction. + +# v1.23.1 (2023-11-20) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.23.0 (2023-11-17) + +* **Feature**: Documentation and operational updates for Amazon ECR, adding support for pull through cache rules for upstream registries that require authentication. + +# v1.22.2 (2023-11-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.22.1 (2023-11-09) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.22.0 (2023-11-01) + +* **Feature**: Adds support for configured endpoints via environment variables and the AWS shared configuration file. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.21.0 (2023-10-31) + +* **Feature**: **BREAKING CHANGE**: Bump minimum go version to 1.19 per the revised [go version support policy](https://aws.amazon.com/blogs/developer/aws-sdk-for-go-aligns-with-go-release-policy-on-supported-runtimes/). +* **Dependency Update**: Updated to the latest SDK module versions + # v1.20.2 (2023-10-12) * **Dependency Update**: Updated to the latest SDK module versions diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_client.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_client.go index f1984dd44b..1cc8f55cfd 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_client.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_client.go @@ -4,6 +4,7 @@ package ecr import ( "context" + "errors" "fmt" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/aws/defaults" @@ -11,193 +12,234 @@ import ( "github.com/aws/aws-sdk-go-v2/aws/retry" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" + internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" + internalauthsmithy "github.com/aws/aws-sdk-go-v2/internal/auth/smithy" internalConfig "github.com/aws/aws-sdk-go-v2/internal/configsources" + internalmiddleware "github.com/aws/aws-sdk-go-v2/internal/middleware" smithy "github.com/aws/smithy-go" + smithyauth "github.com/aws/smithy-go/auth" smithydocument "github.com/aws/smithy-go/document" "github.com/aws/smithy-go/logging" + "github.com/aws/smithy-go/metrics" "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/tracing" smithyhttp "github.com/aws/smithy-go/transport/http" "net" "net/http" + "sync/atomic" "time" ) const ServiceID = "ECR" const ServiceAPIVersion = "2015-09-21" -// Client provides the API client to make operations call for Amazon EC2 Container -// Registry. -type Client struct { - options Options +type operationMetrics struct { + Duration metrics.Float64Histogram + SerializeDuration metrics.Float64Histogram + ResolveIdentityDuration metrics.Float64Histogram + ResolveEndpointDuration metrics.Float64Histogram + SignRequestDuration metrics.Float64Histogram + DeserializeDuration metrics.Float64Histogram +} + +func (m *operationMetrics) histogramFor(name string) metrics.Float64Histogram { + switch name { + case "client.call.duration": + return m.Duration + case "client.call.serialization_duration": + return m.SerializeDuration + case "client.call.resolve_identity_duration": + return m.ResolveIdentityDuration + case "client.call.resolve_endpoint_duration": + return m.ResolveEndpointDuration + case "client.call.signing_duration": + return m.SignRequestDuration + case "client.call.deserialization_duration": + return m.DeserializeDuration + default: + panic("unrecognized operation metric") + } } -// New returns an initialized Client based on the functional options. Provide -// additional functional options to further configure the behavior of the client, -// such as changing the client's endpoint or adding custom middleware behavior. -func New(options Options, optFns ...func(*Options)) *Client { - options = options.Copy() +func timeOperationMetric[T any]( + ctx context.Context, metric string, fn func() (T, error), + opts ...metrics.RecordMetricOption, +) (T, error) { + instr := getOperationMetrics(ctx).histogramFor(metric) + opts = append([]metrics.RecordMetricOption{withOperationMetadata(ctx)}, opts...) - resolveDefaultLogger(&options) + start := time.Now() + v, err := fn() + end := time.Now() - setResolvedDefaultsMode(&options) + elapsed := end.Sub(start) + instr.Record(ctx, float64(elapsed)/1e9, opts...) + return v, err +} - resolveRetryer(&options) +func startMetricTimer(ctx context.Context, metric string, opts ...metrics.RecordMetricOption) func() { + instr := getOperationMetrics(ctx).histogramFor(metric) + opts = append([]metrics.RecordMetricOption{withOperationMetadata(ctx)}, opts...) - resolveHTTPClient(&options) + var ended bool + start := time.Now() + return func() { + if ended { + return + } + ended = true - resolveHTTPSignerV4(&options) + end := time.Now() - for _, fn := range optFns { - fn(&options) + elapsed := end.Sub(start) + instr.Record(ctx, float64(elapsed)/1e9, opts...) } +} - client := &Client{ - options: options, +func withOperationMetadata(ctx context.Context) metrics.RecordMetricOption { + return func(o *metrics.RecordMetricOptions) { + o.Properties.Set("rpc.service", middleware.GetServiceID(ctx)) + o.Properties.Set("rpc.method", middleware.GetOperationName(ctx)) } - - return client } -type Options struct { - // Set of options to modify how an operation is invoked. These apply to all - // operations invoked for this client. Use functional options on operation call to - // modify this list for per operation behavior. - APIOptions []func(*middleware.Stack) error - - // The optional application specific identifier appended to the User-Agent header. - AppID string +type operationMetricsKey struct{} - // This endpoint will be given as input to an EndpointResolverV2. It is used for - // providing a custom base endpoint that is subject to modifications by the - // processing EndpointResolverV2. - BaseEndpoint *string - - // Configures the events that will be sent to the configured logger. - ClientLogMode aws.ClientLogMode +func withOperationMetrics(parent context.Context, mp metrics.MeterProvider) (context.Context, error) { + meter := mp.Meter("github.com/aws/aws-sdk-go-v2/service/ecr") + om := &operationMetrics{} - // The credentials object to use when signing requests. - Credentials aws.CredentialsProvider + var err error - // The configuration DefaultsMode that the SDK should use when constructing the - // clients initial default settings. - DefaultsMode aws.DefaultsMode + om.Duration, err = operationMetricTimer(meter, "client.call.duration", + "Overall call duration (including retries and time to send or receive request and response body)") + if err != nil { + return nil, err + } + om.SerializeDuration, err = operationMetricTimer(meter, "client.call.serialization_duration", + "The time it takes to serialize a message body") + if err != nil { + return nil, err + } + om.ResolveIdentityDuration, err = operationMetricTimer(meter, "client.call.auth.resolve_identity_duration", + "The time taken to acquire an identity (AWS credentials, bearer token, etc) from an Identity Provider") + if err != nil { + return nil, err + } + om.ResolveEndpointDuration, err = operationMetricTimer(meter, "client.call.resolve_endpoint_duration", + "The time it takes to resolve an endpoint (endpoint resolver, not DNS) for the request") + if err != nil { + return nil, err + } + om.SignRequestDuration, err = operationMetricTimer(meter, "client.call.auth.signing_duration", + "The time it takes to sign a request") + if err != nil { + return nil, err + } + om.DeserializeDuration, err = operationMetricTimer(meter, "client.call.deserialization_duration", + "The time it takes to deserialize a message body") + if err != nil { + return nil, err + } - // The endpoint options to be used when attempting to resolve an endpoint. - EndpointOptions EndpointResolverOptions + return context.WithValue(parent, operationMetricsKey{}, om), nil +} - // The service endpoint resolver. - // - // Deprecated: Deprecated: EndpointResolver and WithEndpointResolver. Providing a - // value for this field will likely prevent you from using any endpoint-related - // service features released after the introduction of EndpointResolverV2 and - // BaseEndpoint. To migrate an EndpointResolver implementation that uses a custom - // endpoint, set the client option BaseEndpoint instead. - EndpointResolver EndpointResolver +func operationMetricTimer(m metrics.Meter, name, desc string) (metrics.Float64Histogram, error) { + return m.Float64Histogram(name, func(o *metrics.InstrumentOptions) { + o.UnitLabel = "s" + o.Description = desc + }) +} - // Resolves the endpoint used for a particular service. This should be used over - // the deprecated EndpointResolver - EndpointResolverV2 EndpointResolverV2 +func getOperationMetrics(ctx context.Context) *operationMetrics { + return ctx.Value(operationMetricsKey{}).(*operationMetrics) +} - // Signature Version 4 (SigV4) Signer - HTTPSignerV4 HTTPSignerV4 +func operationTracer(p tracing.TracerProvider) tracing.Tracer { + return p.Tracer("github.com/aws/aws-sdk-go-v2/service/ecr") +} - // The logger writer interface to write logging messages to. - Logger logging.Logger +// Client provides the API client to make operations call for Amazon Elastic +// Container Registry. +type Client struct { + options Options - // The region to send requests to. (Required) - Region string + // Difference between the time reported by the server and the client + timeOffset *atomic.Int64 +} - // RetryMaxAttempts specifies the maximum number attempts an API client will call - // an operation that fails with a retryable error. A value of 0 is ignored, and - // will not be used to configure the API client created default retryer, or modify - // per operation call's retry max attempts. When creating a new API Clients this - // member will only be used if the Retryer Options member is nil. This value will - // be ignored if Retryer is not nil. If specified in an operation call's functional - // options with a value that is different than the constructed client's Options, - // the Client's Retryer will be wrapped to use the operation's specific - // RetryMaxAttempts value. - RetryMaxAttempts int +// New returns an initialized Client based on the functional options. Provide +// additional functional options to further configure the behavior of the client, +// such as changing the client's endpoint or adding custom middleware behavior. +func New(options Options, optFns ...func(*Options)) *Client { + options = options.Copy() - // RetryMode specifies the retry mode the API client will be created with, if - // Retryer option is not also specified. When creating a new API Clients this - // member will only be used if the Retryer Options member is nil. This value will - // be ignored if Retryer is not nil. Currently does not support per operation call - // overrides, may in the future. - RetryMode aws.RetryMode + resolveDefaultLogger(&options) - // Retryer guides how HTTP requests should be retried in case of recoverable - // failures. When nil the API client will use a default retryer. The kind of - // default retry created by the API client can be changed with the RetryMode - // option. - Retryer aws.Retryer + setResolvedDefaultsMode(&options) - // The RuntimeEnvironment configuration, only populated if the DefaultsMode is set - // to DefaultsModeAuto and is initialized using config.LoadDefaultConfig . You - // should not populate this structure programmatically, or rely on the values here - // within your applications. - RuntimeEnvironment aws.RuntimeEnvironment + resolveRetryer(&options) - // The initial DefaultsMode used when the client options were constructed. If the - // DefaultsMode was set to aws.DefaultsModeAuto this will store what the resolved - // value was at that point in time. Currently does not support per operation call - // overrides, may in the future. - resolvedDefaultsMode aws.DefaultsMode + resolveHTTPClient(&options) - // The HTTP client to invoke API calls with. Defaults to client's default HTTP - // implementation if nil. - HTTPClient HTTPClient -} + resolveHTTPSignerV4(&options) -// WithAPIOptions returns a functional option for setting the Client's APIOptions -// option. -func WithAPIOptions(optFns ...func(*middleware.Stack) error) func(*Options) { - return func(o *Options) { - o.APIOptions = append(o.APIOptions, optFns...) - } -} + resolveEndpointResolverV2(&options) + + resolveTracerProvider(&options) + + resolveMeterProvider(&options) -// Deprecated: EndpointResolver and WithEndpointResolver. Providing a value for -// this field will likely prevent you from using any endpoint-related service -// features released after the introduction of EndpointResolverV2 and BaseEndpoint. -// To migrate an EndpointResolver implementation that uses a custom endpoint, set -// the client option BaseEndpoint instead. -func WithEndpointResolver(v EndpointResolver) func(*Options) { - return func(o *Options) { - o.EndpointResolver = v + resolveAuthSchemeResolver(&options) + + for _, fn := range optFns { + fn(&options) } -} -// WithEndpointResolverV2 returns a functional option for setting the Client's -// EndpointResolverV2 option. -func WithEndpointResolverV2(v EndpointResolverV2) func(*Options) { - return func(o *Options) { - o.EndpointResolverV2 = v + finalizeRetryMaxAttempts(&options) + + ignoreAnonymousAuth(&options) + + wrapWithAnonymousAuth(&options) + + resolveAuthSchemes(&options) + + client := &Client{ + options: options, } -} -type HTTPClient interface { - Do(*http.Request) (*http.Response, error) -} + initializeTimeOffsetResolver(client) -// Copy creates a clone where the APIOptions list is deep copied. -func (o Options) Copy() Options { - to := o - to.APIOptions = make([]func(*middleware.Stack) error, len(o.APIOptions)) - copy(to.APIOptions, o.APIOptions) + return client +} - return to +// Options returns a copy of the client configuration. +// +// Callers SHOULD NOT perform mutations on any inner structures within client +// config. Config overrides should instead be made on a per-operation basis through +// functional options. +func (c *Client) Options() Options { + return c.options.Copy() } -func (c *Client) invokeOperation(ctx context.Context, opID string, params interface{}, optFns []func(*Options), stackFns ...func(*middleware.Stack, Options) error) (result interface{}, metadata middleware.Metadata, err error) { + +func (c *Client) invokeOperation( + ctx context.Context, opID string, params interface{}, optFns []func(*Options), stackFns ...func(*middleware.Stack, Options) error, +) ( + result interface{}, metadata middleware.Metadata, err error, +) { ctx = middleware.ClearStackValues(ctx) + ctx = middleware.WithServiceID(ctx, ServiceID) + ctx = middleware.WithOperationName(ctx, opID) + stack := middleware.NewStack(opID, smithyhttp.NewStackRequest) options := c.options.Copy() - resolveEndpointResolverV2(&options) for _, fn := range optFns { fn(&options) } - finalizeRetryMaxAttemptOptions(&options, *c) + finalizeOperationRetryMaxAttempts(&options, *c) finalizeClientEndpointResolverOptions(&options) @@ -213,18 +255,116 @@ func (c *Client) invokeOperation(ctx context.Context, opID string, params interf } } - handler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack) - result, metadata, err = handler.Handle(ctx, params) + ctx, err = withOperationMetrics(ctx, options.MeterProvider) + if err != nil { + return nil, metadata, err + } + + tracer := operationTracer(options.TracerProvider) + spanName := fmt.Sprintf("%s.%s", ServiceID, opID) + + ctx = tracing.WithOperationTracer(ctx, tracer) + + ctx, span := tracer.StartSpan(ctx, spanName, func(o *tracing.SpanOptions) { + o.Kind = tracing.SpanKindClient + o.Properties.Set("rpc.system", "aws-api") + o.Properties.Set("rpc.method", opID) + o.Properties.Set("rpc.service", ServiceID) + }) + endTimer := startMetricTimer(ctx, "client.call.duration") + defer endTimer() + defer span.End() + + handler := smithyhttp.NewClientHandlerWithOptions(options.HTTPClient, func(o *smithyhttp.ClientHandler) { + o.Meter = options.MeterProvider.Meter("github.com/aws/aws-sdk-go-v2/service/ecr") + }) + decorated := middleware.DecorateHandler(handler, stack) + result, metadata, err = decorated.Handle(ctx, params) if err != nil { + span.SetProperty("exception.type", fmt.Sprintf("%T", err)) + span.SetProperty("exception.message", err.Error()) + + var aerr smithy.APIError + if errors.As(err, &aerr) { + span.SetProperty("api.error_code", aerr.ErrorCode()) + span.SetProperty("api.error_message", aerr.ErrorMessage()) + span.SetProperty("api.error_fault", aerr.ErrorFault().String()) + } + err = &smithy.OperationError{ ServiceID: ServiceID, OperationName: opID, Err: err, } } + + span.SetProperty("error", err != nil) + if err == nil { + span.SetStatus(tracing.SpanStatusOK) + } else { + span.SetStatus(tracing.SpanStatusError) + } + return result, metadata, err } +type operationInputKey struct{} + +func setOperationInput(ctx context.Context, input interface{}) context.Context { + return middleware.WithStackValue(ctx, operationInputKey{}, input) +} + +func getOperationInput(ctx context.Context) interface{} { + return middleware.GetStackValue(ctx, operationInputKey{}) +} + +type setOperationInputMiddleware struct { +} + +func (*setOperationInputMiddleware) ID() string { + return "setOperationInput" +} + +func (m *setOperationInputMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + ctx = setOperationInput(ctx, in.Parameters) + return next.HandleSerialize(ctx, in) +} + +func addProtocolFinalizerMiddlewares(stack *middleware.Stack, options Options, operation string) error { + if err := stack.Finalize.Add(&resolveAuthSchemeMiddleware{operation: operation, options: options}, middleware.Before); err != nil { + return fmt.Errorf("add ResolveAuthScheme: %w", err) + } + if err := stack.Finalize.Insert(&getIdentityMiddleware{options: options}, "ResolveAuthScheme", middleware.After); err != nil { + return fmt.Errorf("add GetIdentity: %v", err) + } + if err := stack.Finalize.Insert(&resolveEndpointV2Middleware{options: options}, "GetIdentity", middleware.After); err != nil { + return fmt.Errorf("add ResolveEndpointV2: %v", err) + } + if err := stack.Finalize.Insert(&signRequestMiddleware{options: options}, "ResolveEndpointV2", middleware.After); err != nil { + return fmt.Errorf("add Signing: %w", err) + } + return nil +} +func resolveAuthSchemeResolver(options *Options) { + if options.AuthSchemeResolver == nil { + options.AuthSchemeResolver = &defaultAuthSchemeResolver{} + } +} + +func resolveAuthSchemes(options *Options) { + if options.AuthSchemes == nil { + options.AuthSchemes = []smithyhttp.AuthScheme{ + internalauth.NewHTTPAuthScheme("aws.auth#sigv4", &internalauthsmithy.V4SignerAdapter{ + Signer: options.HTTPSignerV4, + Logger: options.Logger, + LogSigning: options.ClientLogMode.IsSigning(), + }), + } + } +} + type noSmithyDocumentSerde = smithydocument.NoSerde type legacyEndpointContextSetter struct { @@ -296,6 +436,7 @@ func NewFromConfig(cfg aws.Config, optFns ...func(*Options)) *Client { resolveAWSEndpointResolver(cfg, &opts) resolveUseDualStackEndpoint(cfg, &opts) resolveUseFIPSEndpoint(cfg, &opts) + resolveBaseEndpoint(cfg, &opts) return New(opts, optFns...) } @@ -387,7 +528,15 @@ func resolveAWSRetryMaxAttempts(cfg aws.Config, o *Options) { o.RetryMaxAttempts = cfg.RetryMaxAttempts } -func finalizeRetryMaxAttemptOptions(o *Options, client Client) { +func finalizeRetryMaxAttempts(o *Options) { + if o.RetryMaxAttempts == 0 { + return + } + + o.Retryer = retry.AddWithMaxAttempts(o.Retryer, o.RetryMaxAttempts) +} + +func finalizeOperationRetryMaxAttempts(o *Options, client Client) { if v := o.RetryMaxAttempts; v == 0 || v == client.options.RetryMaxAttempts { return } @@ -403,24 +552,35 @@ func resolveAWSEndpointResolver(cfg aws.Config, o *Options) { } func addClientUserAgent(stack *middleware.Stack, options Options) error { - if err := awsmiddleware.AddSDKAgentKeyValue(awsmiddleware.APIMetadata, "ecr", goModuleVersion)(stack); err != nil { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { return err } + ua.AddSDKAgentKeyValue(awsmiddleware.APIMetadata, "ecr", goModuleVersion) if len(options.AppID) > 0 { - return awsmiddleware.AddSDKAgentKey(awsmiddleware.ApplicationIdentifier, options.AppID)(stack) + ua.AddSDKAgentKey(awsmiddleware.ApplicationIdentifier, options.AppID) } return nil } -func addHTTPSignerV4Middleware(stack *middleware.Stack, o Options) error { - mw := v4.NewSignHTTPRequestMiddleware(v4.SignHTTPRequestMiddlewareOptions{ - CredentialsProvider: o.Credentials, - Signer: o.HTTPSignerV4, - LogSigning: o.ClientLogMode.IsSigning(), - }) - return stack.Finalize.Add(mw, middleware.After) +func getOrAddRequestUserAgent(stack *middleware.Stack) (*awsmiddleware.RequestUserAgent, error) { + id := (*awsmiddleware.RequestUserAgent)(nil).ID() + mw, ok := stack.Build.Get(id) + if !ok { + mw = awsmiddleware.NewRequestUserAgent() + if err := stack.Build.Add(mw, middleware.After); err != nil { + return nil, err + } + } + + ua, ok := mw.(*awsmiddleware.RequestUserAgent) + if !ok { + return nil, fmt.Errorf("%T for %s middleware did not match expected type", mw, id) + } + + return ua, nil } type HTTPSignerV4 interface { @@ -441,12 +601,97 @@ func newDefaultV4Signer(o Options) *v4.Signer { }) } -func addRetryMiddlewares(stack *middleware.Stack, o Options) error { - mo := retry.AddRetryMiddlewaresOptions{ - Retryer: o.Retryer, - LogRetryAttempts: o.ClientLogMode.IsRetries(), +func addClientRequestID(stack *middleware.Stack) error { + return stack.Build.Add(&awsmiddleware.ClientRequestID{}, middleware.After) +} + +func addComputeContentLength(stack *middleware.Stack) error { + return stack.Build.Add(&smithyhttp.ComputeContentLength{}, middleware.After) +} + +func addRawResponseToMetadata(stack *middleware.Stack) error { + return stack.Deserialize.Add(&awsmiddleware.AddRawResponse{}, middleware.Before) +} + +func addRecordResponseTiming(stack *middleware.Stack) error { + return stack.Deserialize.Add(&awsmiddleware.RecordResponseTiming{}, middleware.After) +} + +func addSpanRetryLoop(stack *middleware.Stack, options Options) error { + return stack.Finalize.Insert(&spanRetryLoop{options: options}, "Retry", middleware.Before) +} + +type spanRetryLoop struct { + options Options +} + +func (*spanRetryLoop) ID() string { + return "spanRetryLoop" +} + +func (m *spanRetryLoop) HandleFinalize( + ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler, +) ( + middleware.FinalizeOutput, middleware.Metadata, error, +) { + tracer := operationTracer(m.options.TracerProvider) + ctx, span := tracer.StartSpan(ctx, "RetryLoop") + defer span.End() + + return next.HandleFinalize(ctx, in) +} +func addStreamingEventsPayload(stack *middleware.Stack) error { + return stack.Finalize.Add(&v4.StreamingEventsPayload{}, middleware.Before) +} + +func addUnsignedPayload(stack *middleware.Stack) error { + return stack.Finalize.Insert(&v4.UnsignedPayload{}, "ResolveEndpointV2", middleware.After) +} + +func addComputePayloadSHA256(stack *middleware.Stack) error { + return stack.Finalize.Insert(&v4.ComputePayloadSHA256{}, "ResolveEndpointV2", middleware.After) +} + +func addContentSHA256Header(stack *middleware.Stack) error { + return stack.Finalize.Insert(&v4.ContentSHA256Header{}, (*v4.ComputePayloadSHA256)(nil).ID(), middleware.After) +} + +func addIsWaiterUserAgent(o *Options) { + o.APIOptions = append(o.APIOptions, func(stack *middleware.Stack) error { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { + return err + } + + ua.AddUserAgentFeature(awsmiddleware.UserAgentFeatureWaiter) + return nil + }) +} + +func addIsPaginatorUserAgent(o *Options) { + o.APIOptions = append(o.APIOptions, func(stack *middleware.Stack) error { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { + return err + } + + ua.AddUserAgentFeature(awsmiddleware.UserAgentFeaturePaginator) + return nil + }) +} + +func addRetry(stack *middleware.Stack, o Options) error { + attempt := retry.NewAttemptMiddleware(o.Retryer, smithyhttp.RequestCloner, func(m *retry.Attempt) { + m.LogAttempts = o.ClientLogMode.IsRetries() + m.OperationMeter = o.MeterProvider.Meter("github.com/aws/aws-sdk-go-v2/service/ecr") + }) + if err := stack.Finalize.Insert(attempt, "ResolveAuthScheme", middleware.Before); err != nil { + return err + } + if err := stack.Finalize.Insert(&retry.MetricsHeader{}, attempt.ID(), middleware.After); err != nil { + return err } - return retry.AddRetryMiddlewares(stack, mo) + return nil } // resolves dual-stack endpoint configuration @@ -479,12 +724,68 @@ func resolveUseFIPSEndpoint(cfg aws.Config, o *Options) error { return nil } +func resolveAccountID(identity smithyauth.Identity, mode aws.AccountIDEndpointMode) *string { + if mode == aws.AccountIDEndpointModeDisabled { + return nil + } + + if ca, ok := identity.(*internalauthsmithy.CredentialsAdapter); ok && ca.Credentials.AccountID != "" { + return aws.String(ca.Credentials.AccountID) + } + + return nil +} + +func addTimeOffsetBuild(stack *middleware.Stack, c *Client) error { + mw := internalmiddleware.AddTimeOffsetMiddleware{Offset: c.timeOffset} + if err := stack.Build.Add(&mw, middleware.After); err != nil { + return err + } + return stack.Deserialize.Insert(&mw, "RecordResponseTiming", middleware.Before) +} +func initializeTimeOffsetResolver(c *Client) { + c.timeOffset = new(atomic.Int64) +} + +func addUserAgentRetryMode(stack *middleware.Stack, options Options) error { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { + return err + } + + switch options.Retryer.(type) { + case *retry.Standard: + ua.AddUserAgentFeature(awsmiddleware.UserAgentFeatureRetryModeStandard) + case *retry.AdaptiveMode: + ua.AddUserAgentFeature(awsmiddleware.UserAgentFeatureRetryModeAdaptive) + } + return nil +} + +func resolveTracerProvider(options *Options) { + if options.TracerProvider == nil { + options.TracerProvider = &tracing.NopTracerProvider{} + } +} + +func resolveMeterProvider(options *Options) { + if options.MeterProvider == nil { + options.MeterProvider = metrics.NopMeterProvider{} + } +} + +func addRecursionDetection(stack *middleware.Stack) error { + return stack.Build.Add(&awsmiddleware.RecursionDetection{}, middleware.After) +} + func addRequestIDRetrieverMiddleware(stack *middleware.Stack) error { - return awsmiddleware.AddRequestIDRetrieverMiddleware(stack) + return stack.Deserialize.Insert(&awsmiddleware.RequestIDRetriever{}, "OperationDeserializer", middleware.Before) + } func addResponseErrorMiddleware(stack *middleware.Stack) error { - return awshttp.AddResponseErrorMiddleware(stack) + return stack.Deserialize.Insert(&awshttp.ResponseErrorWrapper{}, "RequestIDRetriever", middleware.Before) + } func addRequestResponseLogging(stack *middleware.Stack, o Options) error { @@ -496,31 +797,117 @@ func addRequestResponseLogging(stack *middleware.Stack, o Options) error { }, middleware.After) } -type endpointDisableHTTPSMiddleware struct { - EndpointDisableHTTPS bool +type disableHTTPSMiddleware struct { + DisableHTTPS bool } -func (*endpointDisableHTTPSMiddleware) ID() string { - return "endpointDisableHTTPSMiddleware" +func (*disableHTTPSMiddleware) ID() string { + return "disableHTTPS" } -func (m *endpointDisableHTTPSMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, +func (m *disableHTTPSMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, ) { req, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) } - if m.EndpointDisableHTTPS && !smithyhttp.GetHostnameImmutable(ctx) { + if m.DisableHTTPS && !smithyhttp.GetHostnameImmutable(ctx) { req.URL.Scheme = "http" } + return next.HandleFinalize(ctx, in) +} + +func addDisableHTTPSMiddleware(stack *middleware.Stack, o Options) error { + return stack.Finalize.Insert(&disableHTTPSMiddleware{ + DisableHTTPS: o.EndpointOptions.DisableHTTPS, + }, "ResolveEndpointV2", middleware.After) +} + +type spanInitializeStart struct { +} + +func (*spanInitializeStart) ID() string { + return "spanInitializeStart" +} + +func (m *spanInitializeStart) HandleInitialize( + ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler, +) ( + middleware.InitializeOutput, middleware.Metadata, error, +) { + ctx, _ = tracing.StartSpan(ctx, "Initialize") + + return next.HandleInitialize(ctx, in) +} + +type spanInitializeEnd struct { +} + +func (*spanInitializeEnd) ID() string { + return "spanInitializeEnd" +} + +func (m *spanInitializeEnd) HandleInitialize( + ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler, +) ( + middleware.InitializeOutput, middleware.Metadata, error, +) { + ctx, span := tracing.PopSpan(ctx) + span.End() + + return next.HandleInitialize(ctx, in) +} + +type spanBuildRequestStart struct { +} + +func (*spanBuildRequestStart) ID() string { + return "spanBuildRequestStart" +} + +func (m *spanBuildRequestStart) HandleSerialize( + ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler, +) ( + middleware.SerializeOutput, middleware.Metadata, error, +) { + ctx, _ = tracing.StartSpan(ctx, "BuildRequest") + return next.HandleSerialize(ctx, in) +} + +type spanBuildRequestEnd struct { +} + +func (*spanBuildRequestEnd) ID() string { + return "spanBuildRequestEnd" +} + +func (m *spanBuildRequestEnd) HandleBuild( + ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler, +) ( + middleware.BuildOutput, middleware.Metadata, error, +) { + ctx, span := tracing.PopSpan(ctx) + span.End() + return next.HandleBuild(ctx, in) } -func addendpointDisableHTTPSMiddleware(stack *middleware.Stack, o Options) error { - return stack.Serialize.Insert(&endpointDisableHTTPSMiddleware{ - EndpointDisableHTTPS: o.EndpointOptions.DisableHTTPS, - }, "OperationSerializer", middleware.Before) + +func addSpanInitializeStart(stack *middleware.Stack) error { + return stack.Initialize.Add(&spanInitializeStart{}, middleware.Before) +} + +func addSpanInitializeEnd(stack *middleware.Stack) error { + return stack.Initialize.Add(&spanInitializeEnd{}, middleware.After) +} + +func addSpanBuildRequestStart(stack *middleware.Stack) error { + return stack.Serialize.Add(&spanBuildRequestStart{}, middleware.Before) +} + +func addSpanBuildRequestEnd(stack *middleware.Stack) error { + return stack.Build.Add(&spanBuildRequestEnd{}, middleware.After) } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_BatchCheckLayerAvailability.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_BatchCheckLayerAvailability.go index 8cc701c6f5..a0a36f6a6c 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_BatchCheckLayerAvailability.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_BatchCheckLayerAvailability.go @@ -4,21 +4,19 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) -// Checks the availability of one or more image layers in a repository. When an -// image is pushed to a repository, each image layer is checked to verify if it has -// been uploaded before. If it has been uploaded, then the image layer is skipped. +// Checks the availability of one or more image layers in a repository. +// +// When an image is pushed to a repository, each image layer is checked to verify +// if it has been uploaded before. If it has been uploaded, then the image layer is +// skipped. +// // This operation is used by the Amazon ECR proxy and is not generally used by // customers for pulling and pushing images. In most cases, you should use the // docker CLI to pull, tag, and push images. @@ -73,6 +71,9 @@ type BatchCheckLayerAvailabilityOutput struct { } func (c *Client) addOperationBatchCheckLayerAvailabilityMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpBatchCheckLayerAvailability{}, middleware.After) if err != nil { return err @@ -81,34 +82,38 @@ func (c *Client) addOperationBatchCheckLayerAvailabilityMiddlewares(stack *middl if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "BatchCheckLayerAvailability"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -120,7 +125,13 @@ func (c *Client) addOperationBatchCheckLayerAvailabilityMiddlewares(stack *middl if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addBatchCheckLayerAvailabilityResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpBatchCheckLayerAvailabilityValidationMiddleware(stack); err != nil { @@ -129,7 +140,7 @@ func (c *Client) addOperationBatchCheckLayerAvailabilityMiddlewares(stack *middl if err = stack.Initialize.Add(newServiceMetadataMiddleware_opBatchCheckLayerAvailability(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -141,7 +152,19 @@ func (c *Client) addOperationBatchCheckLayerAvailabilityMiddlewares(stack *middl if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -151,130 +174,6 @@ func newServiceMetadataMiddleware_opBatchCheckLayerAvailability(region string) * return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "BatchCheckLayerAvailability", } } - -type opBatchCheckLayerAvailabilityResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opBatchCheckLayerAvailabilityResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opBatchCheckLayerAvailabilityResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addBatchCheckLayerAvailabilityResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opBatchCheckLayerAvailabilityResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_BatchDeleteImage.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_BatchDeleteImage.go index 53816800dd..ea63234bbf 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_BatchDeleteImage.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_BatchDeleteImage.go @@ -4,23 +4,22 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Deletes a list of specified images within a repository. Images are specified -// with either an imageTag or imageDigest . You can remove a tag from an image by -// specifying the image's tag in your request. When you remove the last tag from an -// image, the image is deleted from your repository. You can completely delete an -// image (and all of its tags) by specifying the image's digest in your request. +// with either an imageTag or imageDigest . +// +// You can remove a tag from an image by specifying the image's tag in your +// request. When you remove the last tag from an image, the image is deleted from +// your repository. +// +// You can completely delete an image (and all of its tags) by specifying the +// image's digest in your request. func (c *Client) BatchDeleteImage(ctx context.Context, params *BatchDeleteImageInput, optFns ...func(*Options)) (*BatchDeleteImageOutput, error) { if params == nil { params = &BatchDeleteImageInput{} @@ -74,6 +73,9 @@ type BatchDeleteImageOutput struct { } func (c *Client) addOperationBatchDeleteImageMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpBatchDeleteImage{}, middleware.After) if err != nil { return err @@ -82,34 +84,38 @@ func (c *Client) addOperationBatchDeleteImageMiddlewares(stack *middleware.Stack if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "BatchDeleteImage"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -121,7 +127,13 @@ func (c *Client) addOperationBatchDeleteImageMiddlewares(stack *middleware.Stack if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addBatchDeleteImageResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpBatchDeleteImageValidationMiddleware(stack); err != nil { @@ -130,7 +142,7 @@ func (c *Client) addOperationBatchDeleteImageMiddlewares(stack *middleware.Stack if err = stack.Initialize.Add(newServiceMetadataMiddleware_opBatchDeleteImage(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -142,7 +154,19 @@ func (c *Client) addOperationBatchDeleteImageMiddlewares(stack *middleware.Stack if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -152,130 +176,6 @@ func newServiceMetadataMiddleware_opBatchDeleteImage(region string) *awsmiddlewa return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "BatchDeleteImage", } } - -type opBatchDeleteImageResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opBatchDeleteImageResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opBatchDeleteImageResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addBatchDeleteImageResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opBatchDeleteImageResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_BatchGetImage.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_BatchGetImage.go index d2f2d85f8e..5bff06008f 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_BatchGetImage.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_BatchGetImage.go @@ -4,21 +4,18 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Gets detailed information for an image. Images are specified with either an -// imageTag or imageDigest . When an image is pulled, the BatchGetImage API is -// called once to retrieve the image manifest. +// imageTag or imageDigest . +// +// When an image is pulled, the BatchGetImage API is called once to retrieve the +// image manifest. func (c *Client) BatchGetImage(ctx context.Context, params *BatchGetImageInput, optFns ...func(*Options)) (*BatchGetImageOutput, error) { if params == nil { params = &BatchGetImageInput{} @@ -47,8 +44,9 @@ type BatchGetImageInput struct { // This member is required. RepositoryName *string - // The accepted media types for the request. Valid values: - // application/vnd.docker.distribution.manifest.v1+json | + // The accepted media types for the request. + // + // Valid values: application/vnd.docker.distribution.manifest.v1+json | // application/vnd.docker.distribution.manifest.v2+json | // application/vnd.oci.image.manifest.v1+json AcceptedMediaTypes []string @@ -76,6 +74,9 @@ type BatchGetImageOutput struct { } func (c *Client) addOperationBatchGetImageMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpBatchGetImage{}, middleware.After) if err != nil { return err @@ -84,34 +85,38 @@ func (c *Client) addOperationBatchGetImageMiddlewares(stack *middleware.Stack, o if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "BatchGetImage"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -123,7 +128,13 @@ func (c *Client) addOperationBatchGetImageMiddlewares(stack *middleware.Stack, o if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addBatchGetImageResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpBatchGetImageValidationMiddleware(stack); err != nil { @@ -132,7 +143,7 @@ func (c *Client) addOperationBatchGetImageMiddlewares(stack *middleware.Stack, o if err = stack.Initialize.Add(newServiceMetadataMiddleware_opBatchGetImage(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -144,7 +155,19 @@ func (c *Client) addOperationBatchGetImageMiddlewares(stack *middleware.Stack, o if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -154,130 +177,6 @@ func newServiceMetadataMiddleware_opBatchGetImage(region string) *awsmiddleware. return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "BatchGetImage", } } - -type opBatchGetImageResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opBatchGetImageResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opBatchGetImageResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addBatchGetImageResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opBatchGetImageResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_BatchGetRepositoryScanningConfiguration.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_BatchGetRepositoryScanningConfiguration.go index 30591dcdf9..ba467c87b6 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_BatchGetRepositoryScanningConfiguration.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_BatchGetRepositoryScanningConfiguration.go @@ -4,14 +4,9 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -57,6 +52,9 @@ type BatchGetRepositoryScanningConfigurationOutput struct { } func (c *Client) addOperationBatchGetRepositoryScanningConfigurationMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpBatchGetRepositoryScanningConfiguration{}, middleware.After) if err != nil { return err @@ -65,34 +63,38 @@ func (c *Client) addOperationBatchGetRepositoryScanningConfigurationMiddlewares( if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "BatchGetRepositoryScanningConfiguration"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -104,7 +106,13 @@ func (c *Client) addOperationBatchGetRepositoryScanningConfigurationMiddlewares( if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addBatchGetRepositoryScanningConfigurationResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpBatchGetRepositoryScanningConfigurationValidationMiddleware(stack); err != nil { @@ -113,7 +121,7 @@ func (c *Client) addOperationBatchGetRepositoryScanningConfigurationMiddlewares( if err = stack.Initialize.Add(newServiceMetadataMiddleware_opBatchGetRepositoryScanningConfiguration(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -125,7 +133,19 @@ func (c *Client) addOperationBatchGetRepositoryScanningConfigurationMiddlewares( if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -135,130 +155,6 @@ func newServiceMetadataMiddleware_opBatchGetRepositoryScanningConfiguration(regi return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "BatchGetRepositoryScanningConfiguration", } } - -type opBatchGetRepositoryScanningConfigurationResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opBatchGetRepositoryScanningConfigurationResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opBatchGetRepositoryScanningConfigurationResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addBatchGetRepositoryScanningConfigurationResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opBatchGetRepositoryScanningConfigurationResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_CompleteLayerUpload.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_CompleteLayerUpload.go index ee896d53e7..3106abb294 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_CompleteLayerUpload.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_CompleteLayerUpload.go @@ -4,24 +4,22 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Informs Amazon ECR that the image layer upload has completed for a specified // registry, repository name, and upload ID. You can optionally provide a sha256 -// digest of the image layer for data validation purposes. When an image is pushed, -// the CompleteLayerUpload API is called once per each new image layer to verify -// that the upload has completed. This operation is used by the Amazon ECR proxy -// and is not generally used by customers for pulling and pushing images. In most -// cases, you should use the docker CLI to pull, tag, and push images. +// digest of the image layer for data validation purposes. +// +// When an image is pushed, the CompleteLayerUpload API is called once per each +// new image layer to verify that the upload has completed. +// +// This operation is used by the Amazon ECR proxy and is not generally used by +// customers for pulling and pushing images. In most cases, you should use the +// docker CLI to pull, tag, and push images. func (c *Client) CompleteLayerUpload(ctx context.Context, params *CompleteLayerUploadInput, optFns ...func(*Options)) (*CompleteLayerUploadOutput, error) { if params == nil { params = &CompleteLayerUploadInput{} @@ -49,8 +47,7 @@ type CompleteLayerUploadInput struct { // This member is required. RepositoryName *string - // The upload ID from a previous InitiateLayerUpload operation to associate with - // the image layer. + // The upload ID from a previous InitiateLayerUpload operation to associate with the image layer. // // This member is required. UploadId *string @@ -84,6 +81,9 @@ type CompleteLayerUploadOutput struct { } func (c *Client) addOperationCompleteLayerUploadMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpCompleteLayerUpload{}, middleware.After) if err != nil { return err @@ -92,34 +92,38 @@ func (c *Client) addOperationCompleteLayerUploadMiddlewares(stack *middleware.St if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "CompleteLayerUpload"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -131,7 +135,13 @@ func (c *Client) addOperationCompleteLayerUploadMiddlewares(stack *middleware.St if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addCompleteLayerUploadResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpCompleteLayerUploadValidationMiddleware(stack); err != nil { @@ -140,7 +150,7 @@ func (c *Client) addOperationCompleteLayerUploadMiddlewares(stack *middleware.St if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCompleteLayerUpload(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -152,7 +162,19 @@ func (c *Client) addOperationCompleteLayerUploadMiddlewares(stack *middleware.St if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -162,130 +184,6 @@ func newServiceMetadataMiddleware_opCompleteLayerUpload(region string) *awsmiddl return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "CompleteLayerUpload", } } - -type opCompleteLayerUploadResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opCompleteLayerUploadResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opCompleteLayerUploadResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addCompleteLayerUploadResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opCompleteLayerUploadResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_CreatePullThroughCacheRule.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_CreatePullThroughCacheRule.go index a31b8bb468..b7f4e1407f 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_CreatePullThroughCacheRule.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_CreatePullThroughCacheRule.go @@ -4,21 +4,20 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" + "github.com/aws/aws-sdk-go-v2/service/ecr/types" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" "time" ) // Creates a pull through cache rule. A pull through cache rule provides a way to -// cache images from an external public registry in your Amazon ECR private -// registry. +// cache images from an upstream registry source in your Amazon ECR private +// registry. For more information, see [Using pull through cache rules]in the Amazon Elastic Container Registry +// User Guide. +// +// [Using pull through cache rules]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/pull-through-cache.html func (c *Client) CreatePullThroughCacheRule(ctx context.Context, params *CreatePullThroughCacheRuleInput, optFns ...func(*Options)) (*CreatePullThroughCacheRuleOutput, error) { if params == nil { params = &CreatePullThroughCacheRuleInput{} @@ -42,16 +41,37 @@ type CreatePullThroughCacheRuleInput struct { EcrRepositoryPrefix *string // The registry URL of the upstream public registry to use as the source for the - // pull through cache rule. + // pull through cache rule. The following is the syntax to use for each supported + // upstream registry. + // + // - Amazon ECR Public ( ecr-public ) - public.ecr.aws + // + // - Docker Hub ( docker-hub ) - registry-1.docker.io + // + // - Quay ( quay ) - quay.io + // + // - Kubernetes ( k8s ) - registry.k8s.io + // + // - GitHub Container Registry ( github-container-registry ) - ghcr.io + // + // - Microsoft Azure Container Registry ( azure-container-registry ) - + // .azurecr.io // // This member is required. UpstreamRegistryUrl *string + // The Amazon Resource Name (ARN) of the Amazon Web Services Secrets Manager + // secret that identifies the credentials to authenticate to the upstream registry. + CredentialArn *string + // The Amazon Web Services account ID associated with the registry to create the // pull through cache rule for. If you do not specify a registry, the default // registry is assumed. RegistryId *string + // The name of the upstream registry. + UpstreamRegistry types.UpstreamRegistry + noSmithyDocumentSerde } @@ -61,12 +81,19 @@ type CreatePullThroughCacheRuleOutput struct { // was created. CreatedAt *time.Time + // The Amazon Resource Name (ARN) of the Amazon Web Services Secrets Manager + // secret associated with the pull through cache rule. + CredentialArn *string + // The Amazon ECR repository prefix associated with the pull through cache rule. EcrRepositoryPrefix *string // The registry ID associated with the request. RegistryId *string + // The name of the upstream registry associated with the pull through cache rule. + UpstreamRegistry types.UpstreamRegistry + // The upstream registry URL associated with the pull through cache rule. UpstreamRegistryUrl *string @@ -77,6 +104,9 @@ type CreatePullThroughCacheRuleOutput struct { } func (c *Client) addOperationCreatePullThroughCacheRuleMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreatePullThroughCacheRule{}, middleware.After) if err != nil { return err @@ -85,34 +115,38 @@ func (c *Client) addOperationCreatePullThroughCacheRuleMiddlewares(stack *middle if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "CreatePullThroughCacheRule"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -124,7 +158,13 @@ func (c *Client) addOperationCreatePullThroughCacheRuleMiddlewares(stack *middle if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addCreatePullThroughCacheRuleResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpCreatePullThroughCacheRuleValidationMiddleware(stack); err != nil { @@ -133,7 +173,7 @@ func (c *Client) addOperationCreatePullThroughCacheRuleMiddlewares(stack *middle if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreatePullThroughCacheRule(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -145,7 +185,19 @@ func (c *Client) addOperationCreatePullThroughCacheRuleMiddlewares(stack *middle if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -155,130 +207,6 @@ func newServiceMetadataMiddleware_opCreatePullThroughCacheRule(region string) *a return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "CreatePullThroughCacheRule", } } - -type opCreatePullThroughCacheRuleResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opCreatePullThroughCacheRuleResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opCreatePullThroughCacheRuleResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addCreatePullThroughCacheRuleResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opCreatePullThroughCacheRuleResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_CreateRepository.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_CreateRepository.go index 1fdf9b212b..b51da6915d 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_CreateRepository.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_CreateRepository.go @@ -4,20 +4,17 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) -// Creates a repository. For more information, see Amazon ECR repositories (https://docs.aws.amazon.com/AmazonECR/latest/userguide/Repositories.html) -// in the Amazon Elastic Container Registry User Guide. +// Creates a repository. For more information, see [Amazon ECR repositories] in the Amazon Elastic +// Container Registry User Guide. +// +// [Amazon ECR repositories]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/Repositories.html func (c *Client) CreateRepository(ctx context.Context, params *CreateRepositoryInput, optFns ...func(*Options)) (*CreateRepositoryOutput, error) { if params == nil { params = &CreateRepositoryInput{} @@ -37,9 +34,10 @@ type CreateRepositoryInput struct { // The name to use for the repository. The repository name may be specified on its // own (such as nginx-web-app ) or it can be prepended with a namespace to group - // the repository into a category (such as project-a/nginx-web-app ). The - // repository name must start with a letter and can only contain lowercase letters, - // numbers, hyphens, underscores, and forward slashes. + // the repository into a category (such as project-a/nginx-web-app ). + // + // The repository name must start with a letter and can only contain lowercase + // letters, numbers, hyphens, underscores, and forward slashes. // // This member is required. RepositoryName *string @@ -84,6 +82,9 @@ type CreateRepositoryOutput struct { } func (c *Client) addOperationCreateRepositoryMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateRepository{}, middleware.After) if err != nil { return err @@ -92,34 +93,38 @@ func (c *Client) addOperationCreateRepositoryMiddlewares(stack *middleware.Stack if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "CreateRepository"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -131,7 +136,13 @@ func (c *Client) addOperationCreateRepositoryMiddlewares(stack *middleware.Stack if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addCreateRepositoryResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpCreateRepositoryValidationMiddleware(stack); err != nil { @@ -140,7 +151,7 @@ func (c *Client) addOperationCreateRepositoryMiddlewares(stack *middleware.Stack if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateRepository(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -152,7 +163,19 @@ func (c *Client) addOperationCreateRepositoryMiddlewares(stack *middleware.Stack if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -162,130 +185,6 @@ func newServiceMetadataMiddleware_opCreateRepository(region string) *awsmiddlewa return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "CreateRepository", } } - -type opCreateRepositoryResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opCreateRepositoryResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opCreateRepositoryResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addCreateRepositoryResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opCreateRepositoryResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_CreateRepositoryCreationTemplate.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_CreateRepositoryCreationTemplate.go new file mode 100644 index 0000000000..5f94b037de --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_CreateRepositoryCreationTemplate.go @@ -0,0 +1,217 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package ecr + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/ecr/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Creates a repository creation template. This template is used to define the +// settings for repositories created by Amazon ECR on your behalf. For example, +// repositories created through pull through cache actions. For more information, +// see [Private repository creation templates]in the Amazon Elastic Container Registry User Guide. +// +// [Private repository creation templates]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-creation-templates.html +func (c *Client) CreateRepositoryCreationTemplate(ctx context.Context, params *CreateRepositoryCreationTemplateInput, optFns ...func(*Options)) (*CreateRepositoryCreationTemplateOutput, error) { + if params == nil { + params = &CreateRepositoryCreationTemplateInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "CreateRepositoryCreationTemplate", params, optFns, c.addOperationCreateRepositoryCreationTemplateMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*CreateRepositoryCreationTemplateOutput) + out.ResultMetadata = metadata + return out, nil +} + +type CreateRepositoryCreationTemplateInput struct { + + // A list of enumerable strings representing the Amazon ECR repository creation + // scenarios that this template will apply towards. The two supported scenarios are + // PULL_THROUGH_CACHE and REPLICATION + // + // This member is required. + AppliedFor []types.RCTAppliedFor + + // The repository namespace prefix to associate with the template. All + // repositories created using this namespace prefix will have the settings defined + // in this template applied. For example, a prefix of prod would apply to all + // repositories beginning with prod/ . Similarly, a prefix of prod/team would + // apply to all repositories beginning with prod/team/ . + // + // To apply a template to all repositories in your registry that don't have an + // associated creation template, you can use ROOT as the prefix. + // + // There is always an assumed / applied to the end of the prefix. If you specify + // ecr-public as the prefix, Amazon ECR treats that as ecr-public/ . When using a + // pull through cache rule, the repository prefix you specify during rule creation + // is what you should specify as your repository creation template prefix as well. + // + // This member is required. + Prefix *string + + // The ARN of the role to be assumed by Amazon ECR. This role must be in the same + // account as the registry that you are configuring. Amazon ECR will assume your + // supplied role when the customRoleArn is specified. When this field isn't + // specified, Amazon ECR will use the service-linked role for the repository + // creation template. + CustomRoleArn *string + + // A description for the repository creation template. + Description *string + + // The encryption configuration to use for repositories created using the template. + EncryptionConfiguration *types.EncryptionConfigurationForRepositoryCreationTemplate + + // The tag mutability setting for the repository. If this parameter is omitted, + // the default setting of MUTABLE will be used which will allow image tags to be + // overwritten. If IMMUTABLE is specified, all image tags within the repository + // will be immutable which will prevent them from being overwritten. + ImageTagMutability types.ImageTagMutability + + // The lifecycle policy to use for repositories created using the template. + LifecyclePolicy *string + + // The repository policy to apply to repositories created using the template. A + // repository policy is a permissions policy associated with a repository to + // control access permissions. + RepositoryPolicy *string + + // The metadata to apply to the repository to help you categorize and organize. + // Each tag consists of a key and an optional value, both of which you define. Tag + // keys can have a maximum character length of 128 characters, and tag values can + // have a maximum length of 256 characters. + ResourceTags []types.Tag + + noSmithyDocumentSerde +} + +type CreateRepositoryCreationTemplateOutput struct { + + // The registry ID associated with the request. + RegistryId *string + + // The details of the repository creation template associated with the request. + RepositoryCreationTemplate *types.RepositoryCreationTemplate + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationCreateRepositoryCreationTemplateMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateRepositoryCreationTemplate{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateRepositoryCreationTemplate{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "CreateRepositoryCreationTemplate"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addOpCreateRepositoryCreationTemplateValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateRepositoryCreationTemplate(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opCreateRepositoryCreationTemplate(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "CreateRepositoryCreationTemplate", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeleteLifecyclePolicy.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeleteLifecyclePolicy.go index 53c4d53277..73f3f88266 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeleteLifecyclePolicy.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeleteLifecyclePolicy.go @@ -4,13 +4,8 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" "time" @@ -68,6 +63,9 @@ type DeleteLifecyclePolicyOutput struct { } func (c *Client) addOperationDeleteLifecyclePolicyMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteLifecyclePolicy{}, middleware.After) if err != nil { return err @@ -76,34 +74,38 @@ func (c *Client) addOperationDeleteLifecyclePolicyMiddlewares(stack *middleware. if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteLifecyclePolicy"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -115,7 +117,13 @@ func (c *Client) addOperationDeleteLifecyclePolicyMiddlewares(stack *middleware. if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addDeleteLifecyclePolicyResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpDeleteLifecyclePolicyValidationMiddleware(stack); err != nil { @@ -124,7 +132,7 @@ func (c *Client) addOperationDeleteLifecyclePolicyMiddlewares(stack *middleware. if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteLifecyclePolicy(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -136,7 +144,19 @@ func (c *Client) addOperationDeleteLifecyclePolicyMiddlewares(stack *middleware. if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -146,130 +166,6 @@ func newServiceMetadataMiddleware_opDeleteLifecyclePolicy(region string) *awsmid return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "DeleteLifecyclePolicy", } } - -type opDeleteLifecyclePolicyResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opDeleteLifecyclePolicyResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opDeleteLifecyclePolicyResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addDeleteLifecyclePolicyResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opDeleteLifecyclePolicyResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeletePullThroughCacheRule.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeletePullThroughCacheRule.go index 658c314c6a..8fabe7584d 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeletePullThroughCacheRule.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeletePullThroughCacheRule.go @@ -4,13 +4,8 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" "time" @@ -53,6 +48,10 @@ type DeletePullThroughCacheRuleOutput struct { // The timestamp associated with the pull through cache rule. CreatedAt *time.Time + // The Amazon Resource Name (ARN) of the Amazon Web Services Secrets Manager + // secret associated with the pull through cache rule. + CredentialArn *string + // The Amazon ECR repository prefix associated with the request. EcrRepositoryPrefix *string @@ -69,6 +68,9 @@ type DeletePullThroughCacheRuleOutput struct { } func (c *Client) addOperationDeletePullThroughCacheRuleMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeletePullThroughCacheRule{}, middleware.After) if err != nil { return err @@ -77,34 +79,38 @@ func (c *Client) addOperationDeletePullThroughCacheRuleMiddlewares(stack *middle if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "DeletePullThroughCacheRule"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -116,7 +122,13 @@ func (c *Client) addOperationDeletePullThroughCacheRuleMiddlewares(stack *middle if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addDeletePullThroughCacheRuleResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpDeletePullThroughCacheRuleValidationMiddleware(stack); err != nil { @@ -125,7 +137,7 @@ func (c *Client) addOperationDeletePullThroughCacheRuleMiddlewares(stack *middle if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeletePullThroughCacheRule(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -137,7 +149,19 @@ func (c *Client) addOperationDeletePullThroughCacheRuleMiddlewares(stack *middle if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -147,130 +171,6 @@ func newServiceMetadataMiddleware_opDeletePullThroughCacheRule(region string) *a return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "DeletePullThroughCacheRule", } } - -type opDeletePullThroughCacheRuleResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opDeletePullThroughCacheRuleResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opDeletePullThroughCacheRuleResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addDeletePullThroughCacheRuleResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opDeletePullThroughCacheRuleResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeleteRegistryPolicy.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeleteRegistryPolicy.go index 2c1f886287..05405eee71 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeleteRegistryPolicy.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeleteRegistryPolicy.go @@ -4,13 +4,8 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -50,6 +45,9 @@ type DeleteRegistryPolicyOutput struct { } func (c *Client) addOperationDeleteRegistryPolicyMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteRegistryPolicy{}, middleware.After) if err != nil { return err @@ -58,34 +56,38 @@ func (c *Client) addOperationDeleteRegistryPolicyMiddlewares(stack *middleware.S if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteRegistryPolicy"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -97,13 +99,19 @@ func (c *Client) addOperationDeleteRegistryPolicyMiddlewares(stack *middleware.S if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addDeleteRegistryPolicyResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteRegistryPolicy(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -115,7 +123,19 @@ func (c *Client) addOperationDeleteRegistryPolicyMiddlewares(stack *middleware.S if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -125,130 +145,6 @@ func newServiceMetadataMiddleware_opDeleteRegistryPolicy(region string) *awsmidd return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "DeleteRegistryPolicy", } } - -type opDeleteRegistryPolicyResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opDeleteRegistryPolicyResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opDeleteRegistryPolicyResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addDeleteRegistryPolicyResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opDeleteRegistryPolicyResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeleteRepository.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeleteRepository.go index 622a861e11..feea5319fb 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeleteRepository.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeleteRepository.go @@ -4,20 +4,16 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) -// Deletes a repository. If the repository contains images, you must either delete -// all images in the repository or use the force option to delete the repository. +// Deletes a repository. If the repository isn't empty, you must either delete the +// contents of the repository or use the force option to delete the repository and +// have Amazon ECR delete all of its contents on your behalf. func (c *Client) DeleteRepository(ctx context.Context, params *DeleteRepositoryInput, optFns ...func(*Options)) (*DeleteRepositoryOutput, error) { if params == nil { params = &DeleteRepositoryInput{} @@ -40,7 +36,8 @@ type DeleteRepositoryInput struct { // This member is required. RepositoryName *string - // If a repository contains images, forces the deletion. + // If true, deleting the repository force deletes the contents of the repository. + // If false, the repository must be empty before attempting to delete it. Force bool // The Amazon Web Services account ID associated with the registry that contains @@ -63,6 +60,9 @@ type DeleteRepositoryOutput struct { } func (c *Client) addOperationDeleteRepositoryMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteRepository{}, middleware.After) if err != nil { return err @@ -71,34 +71,38 @@ func (c *Client) addOperationDeleteRepositoryMiddlewares(stack *middleware.Stack if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteRepository"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -110,7 +114,13 @@ func (c *Client) addOperationDeleteRepositoryMiddlewares(stack *middleware.Stack if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addDeleteRepositoryResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpDeleteRepositoryValidationMiddleware(stack); err != nil { @@ -119,7 +129,7 @@ func (c *Client) addOperationDeleteRepositoryMiddlewares(stack *middleware.Stack if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteRepository(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -131,7 +141,19 @@ func (c *Client) addOperationDeleteRepositoryMiddlewares(stack *middleware.Stack if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -141,130 +163,6 @@ func newServiceMetadataMiddleware_opDeleteRepository(region string) *awsmiddlewa return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "DeleteRepository", } } - -type opDeleteRepositoryResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opDeleteRepositoryResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opDeleteRepositoryResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addDeleteRepositoryResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opDeleteRepositoryResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeleteRepositoryCreationTemplate.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeleteRepositoryCreationTemplate.go new file mode 100644 index 0000000000..98fa1cd10a --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeleteRepositoryCreationTemplate.go @@ -0,0 +1,161 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package ecr + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/ecr/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Deletes a repository creation template. +func (c *Client) DeleteRepositoryCreationTemplate(ctx context.Context, params *DeleteRepositoryCreationTemplateInput, optFns ...func(*Options)) (*DeleteRepositoryCreationTemplateOutput, error) { + if params == nil { + params = &DeleteRepositoryCreationTemplateInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DeleteRepositoryCreationTemplate", params, optFns, c.addOperationDeleteRepositoryCreationTemplateMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DeleteRepositoryCreationTemplateOutput) + out.ResultMetadata = metadata + return out, nil +} + +type DeleteRepositoryCreationTemplateInput struct { + + // The repository namespace prefix associated with the repository creation + // template. + // + // This member is required. + Prefix *string + + noSmithyDocumentSerde +} + +type DeleteRepositoryCreationTemplateOutput struct { + + // The registry ID associated with the request. + RegistryId *string + + // The details of the repository creation template that was deleted. + RepositoryCreationTemplate *types.RepositoryCreationTemplate + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDeleteRepositoryCreationTemplateMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteRepositoryCreationTemplate{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteRepositoryCreationTemplate{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteRepositoryCreationTemplate"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addOpDeleteRepositoryCreationTemplateValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteRepositoryCreationTemplate(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDeleteRepositoryCreationTemplate(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DeleteRepositoryCreationTemplate", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeleteRepositoryPolicy.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeleteRepositoryPolicy.go index 6b7fb0bcf8..9ad27321f1 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeleteRepositoryPolicy.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DeleteRepositoryPolicy.go @@ -4,13 +4,8 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -65,6 +60,9 @@ type DeleteRepositoryPolicyOutput struct { } func (c *Client) addOperationDeleteRepositoryPolicyMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteRepositoryPolicy{}, middleware.After) if err != nil { return err @@ -73,34 +71,38 @@ func (c *Client) addOperationDeleteRepositoryPolicyMiddlewares(stack *middleware if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteRepositoryPolicy"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -112,7 +114,13 @@ func (c *Client) addOperationDeleteRepositoryPolicyMiddlewares(stack *middleware if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addDeleteRepositoryPolicyResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpDeleteRepositoryPolicyValidationMiddleware(stack); err != nil { @@ -121,7 +129,7 @@ func (c *Client) addOperationDeleteRepositoryPolicyMiddlewares(stack *middleware if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteRepositoryPolicy(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -133,7 +141,19 @@ func (c *Client) addOperationDeleteRepositoryPolicyMiddlewares(stack *middleware if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -143,130 +163,6 @@ func newServiceMetadataMiddleware_opDeleteRepositoryPolicy(region string) *awsmi return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "DeleteRepositoryPolicy", } } - -type opDeleteRepositoryPolicyResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opDeleteRepositoryPolicyResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opDeleteRepositoryPolicyResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addDeleteRepositoryPolicyResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opDeleteRepositoryPolicyResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeImageReplicationStatus.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeImageReplicationStatus.go index ba73c5f8ce..f674ea0cbe 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeImageReplicationStatus.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeImageReplicationStatus.go @@ -4,14 +4,9 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -69,6 +64,9 @@ type DescribeImageReplicationStatusOutput struct { } func (c *Client) addOperationDescribeImageReplicationStatusMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeImageReplicationStatus{}, middleware.After) if err != nil { return err @@ -77,34 +75,38 @@ func (c *Client) addOperationDescribeImageReplicationStatusMiddlewares(stack *mi if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeImageReplicationStatus"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -116,7 +118,13 @@ func (c *Client) addOperationDescribeImageReplicationStatusMiddlewares(stack *mi if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addDescribeImageReplicationStatusResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpDescribeImageReplicationStatusValidationMiddleware(stack); err != nil { @@ -125,7 +133,7 @@ func (c *Client) addOperationDescribeImageReplicationStatusMiddlewares(stack *mi if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeImageReplicationStatus(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -137,7 +145,19 @@ func (c *Client) addOperationDescribeImageReplicationStatusMiddlewares(stack *mi if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -147,130 +167,6 @@ func newServiceMetadataMiddleware_opDescribeImageReplicationStatus(region string return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "DescribeImageReplicationStatus", } } - -type opDescribeImageReplicationStatusResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opDescribeImageReplicationStatusResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opDescribeImageReplicationStatusResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addDescribeImageReplicationStatusResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opDescribeImageReplicationStatusResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeImageScanFindings.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeImageScanFindings.go index 63464be1ca..b332e59383 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeImageScanFindings.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeImageScanFindings.go @@ -4,19 +4,13 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithytime "github.com/aws/smithy-go/time" smithyhttp "github.com/aws/smithy-go/transport/http" smithywaiter "github.com/aws/smithy-go/waiter" - "github.com/jmespath/go-jmespath" "time" ) @@ -103,6 +97,9 @@ type DescribeImageScanFindingsOutput struct { } func (c *Client) addOperationDescribeImageScanFindingsMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeImageScanFindings{}, middleware.After) if err != nil { return err @@ -111,34 +108,38 @@ func (c *Client) addOperationDescribeImageScanFindingsMiddlewares(stack *middlew if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeImageScanFindings"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -150,7 +151,13 @@ func (c *Client) addOperationDescribeImageScanFindingsMiddlewares(stack *middlew if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addDescribeImageScanFindingsResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpDescribeImageScanFindingsValidationMiddleware(stack); err != nil { @@ -159,7 +166,7 @@ func (c *Client) addOperationDescribeImageScanFindingsMiddlewares(stack *middlew if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeImageScanFindings(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -171,109 +178,22 @@ func (c *Client) addOperationDescribeImageScanFindingsMiddlewares(stack *middlew if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { return err } - return nil -} - -// DescribeImageScanFindingsAPIClient is a client that implements the -// DescribeImageScanFindings operation. -type DescribeImageScanFindingsAPIClient interface { - DescribeImageScanFindings(context.Context, *DescribeImageScanFindingsInput, ...func(*Options)) (*DescribeImageScanFindingsOutput, error) -} - -var _ DescribeImageScanFindingsAPIClient = (*Client)(nil) - -// DescribeImageScanFindingsPaginatorOptions is the paginator options for -// DescribeImageScanFindings -type DescribeImageScanFindingsPaginatorOptions struct { - // The maximum number of image scan results returned by DescribeImageScanFindings - // in paginated output. When this parameter is used, DescribeImageScanFindings - // only returns maxResults results in a single page along with a nextToken - // response element. The remaining results of the initial request can be seen by - // sending another DescribeImageScanFindings request with the returned nextToken - // value. This value can be between 1 and 1000. If this parameter is not used, then - // DescribeImageScanFindings returns up to 100 results and a nextToken value, if - // applicable. - Limit int32 - - // Set to true if pagination should stop if the service returns a pagination token - // that matches the most recent token provided to the service. - StopOnDuplicateToken bool -} - -// DescribeImageScanFindingsPaginator is a paginator for DescribeImageScanFindings -type DescribeImageScanFindingsPaginator struct { - options DescribeImageScanFindingsPaginatorOptions - client DescribeImageScanFindingsAPIClient - params *DescribeImageScanFindingsInput - nextToken *string - firstPage bool -} - -// NewDescribeImageScanFindingsPaginator returns a new -// DescribeImageScanFindingsPaginator -func NewDescribeImageScanFindingsPaginator(client DescribeImageScanFindingsAPIClient, params *DescribeImageScanFindingsInput, optFns ...func(*DescribeImageScanFindingsPaginatorOptions)) *DescribeImageScanFindingsPaginator { - if params == nil { - params = &DescribeImageScanFindingsInput{} - } - - options := DescribeImageScanFindingsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeImageScanFindingsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeImageScanFindingsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeImageScanFindings page. -func (p *DescribeImageScanFindingsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeImageScanFindingsOutput, error) { - if !p.HasMorePages() { - return nil, fmt.Errorf("no more pages available") + if err = addSpanInitializeStart(stack); err != nil { + return err } - - params := *p.params - params.NextToken = p.nextToken - - var limit *int32 - if p.options.Limit > 0 { - limit = &p.options.Limit + if err = addSpanInitializeEnd(stack); err != nil { + return err } - params.MaxResults = limit - - result, err := p.client.DescribeImageScanFindings(ctx, ¶ms, optFns...) - if err != nil { - return nil, err + if err = addSpanBuildRequestStart(stack); err != nil { + return err } - p.firstPage = false - - prevToken := p.nextToken - p.nextToken = result.NextToken - - if p.options.StopOnDuplicateToken && - prevToken != nil && - p.nextToken != nil && - *prevToken == *p.nextToken { - p.nextToken = nil + if err = addSpanBuildRequestEnd(stack); err != nil { + return err } - - return result, nil + return nil } // ImageScanCompleteWaiterOptions are waiter options for ImageScanCompleteWaiter @@ -282,8 +202,17 @@ type ImageScanCompleteWaiterOptions struct { // Set of options to modify how an operation is invoked. These apply to all // operations invoked for this client. Use functional options on operation call to // modify this list for per operation behavior. + // + // Passing options here is functionally equivalent to passing values to this + // config's ClientOptions field that extend the inner client's APIOptions directly. APIOptions []func(*middleware.Stack) error + // Functional options to be passed to all operations invoked by this client. + // + // Function values that modify the inner APIOptions are applied after the waiter + // config's own APIOptions modifiers. + ClientOptions []func(*Options) + // MinDelay is the minimum amount of time to delay between retries. If unset, // ImageScanCompleteWaiter will use default minimum delay of 5 seconds. Note that // MinDelay must resolve to a value lesser than or equal to the MaxDelay. @@ -299,12 +228,13 @@ type ImageScanCompleteWaiterOptions struct { // Retryable is function that can be used to override the service defined // waiter-behavior based on operation output, or returned error. This function is - // used by the waiter to decide if a state is retryable or a terminal state. By - // default service-modeled logic will populate this option. This option can thus be - // used to define a custom waiter state with fall-back to service-modeled waiter - // state mutators.The function returns an error in case of a failure state. In case - // of retry state, this function returns a bool value of true and nil error, while - // in case of success it returns a bool value of false and nil error. + // used by the waiter to decide if a state is retryable or a terminal state. + // + // By default service-modeled logic will populate this option. This option can + // thus be used to define a custom waiter state with fall-back to service-modeled + // waiter state mutators.The function returns an error in case of a failure state. + // In case of retry state, this function returns a bool value of true and nil + // error, while in case of success it returns a bool value of false and nil error. Retryable func(context.Context, *DescribeImageScanFindingsInput, *DescribeImageScanFindingsOutput, error) (bool, error) } @@ -381,7 +311,16 @@ func (w *ImageScanCompleteWaiter) WaitForOutput(ctx context.Context, params *Des } out, err := w.client.DescribeImageScanFindings(ctx, params, func(o *Options) { + baseOpts := []func(*Options){ + addIsWaiterUserAgent, + } o.APIOptions = append(o.APIOptions, apiOptions...) + for _, opt := range baseOpts { + opt(o) + } + for _, opt := range options.ClientOptions { + opt(o) + } }) retryable, err := options.Retryable(ctx, params, out, err) @@ -417,170 +356,147 @@ func (w *ImageScanCompleteWaiter) WaitForOutput(ctx context.Context, params *Des func imageScanCompleteStateRetryable(ctx context.Context, input *DescribeImageScanFindingsInput, output *DescribeImageScanFindingsOutput, err error) (bool, error) { if err == nil { - pathValue, err := jmespath.Search("imageScanStatus.status", output) - if err != nil { - return false, fmt.Errorf("error evaluating waiter state: %w", err) + v1 := output.ImageScanStatus + var v2 types.ScanStatus + if v1 != nil { + v3 := v1.Status + v2 = v3 } - expectedValue := "COMPLETE" - value, ok := pathValue.(types.ScanStatus) - if !ok { - return false, fmt.Errorf("waiter comparator expected types.ScanStatus value, got %T", pathValue) - } - - if string(value) == expectedValue { + var pathValue string + pathValue = string(v2) + if pathValue == expectedValue { return false, nil } } if err == nil { - pathValue, err := jmespath.Search("imageScanStatus.status", output) - if err != nil { - return false, fmt.Errorf("error evaluating waiter state: %w", err) + v1 := output.ImageScanStatus + var v2 types.ScanStatus + if v1 != nil { + v3 := v1.Status + v2 = v3 } - expectedValue := "FAILED" - value, ok := pathValue.(types.ScanStatus) - if !ok { - return false, fmt.Errorf("waiter comparator expected types.ScanStatus value, got %T", pathValue) - } - - if string(value) == expectedValue { + var pathValue string + pathValue = string(v2) + if pathValue == expectedValue { return false, fmt.Errorf("waiter state transitioned to Failure") } } + if err != nil { + return false, err + } return true, nil } -func newServiceMetadataMiddleware_opDescribeImageScanFindings(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - SigningName: "ecr", - OperationName: "DescribeImageScanFindings", - } -} +// DescribeImageScanFindingsPaginatorOptions is the paginator options for +// DescribeImageScanFindings +type DescribeImageScanFindingsPaginatorOptions struct { + // The maximum number of image scan results returned by DescribeImageScanFindings + // in paginated output. When this parameter is used, DescribeImageScanFindings + // only returns maxResults results in a single page along with a nextToken + // response element. The remaining results of the initial request can be seen by + // sending another DescribeImageScanFindings request with the returned nextToken + // value. This value can be between 1 and 1000. If this parameter is not used, then + // DescribeImageScanFindings returns up to 100 results and a nextToken value, if + // applicable. + Limit int32 -type opDescribeImageScanFindingsResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver + // Set to true if pagination should stop if the service returns a pagination token + // that matches the most recent token provided to the service. + StopOnDuplicateToken bool } -func (*opDescribeImageScanFindingsResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" +// DescribeImageScanFindingsPaginator is a paginator for DescribeImageScanFindings +type DescribeImageScanFindingsPaginator struct { + options DescribeImageScanFindingsPaginatorOptions + client DescribeImageScanFindingsAPIClient + params *DescribeImageScanFindingsInput + nextToken *string + firstPage bool } -func (m *opDescribeImageScanFindingsResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) +// NewDescribeImageScanFindingsPaginator returns a new +// DescribeImageScanFindingsPaginator +func NewDescribeImageScanFindingsPaginator(client DescribeImageScanFindingsAPIClient, params *DescribeImageScanFindingsInput, optFns ...func(*DescribeImageScanFindingsPaginatorOptions)) *DescribeImageScanFindingsPaginator { + if params == nil { + params = &DescribeImageScanFindingsInput{} } - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) + options := DescribeImageScanFindingsPaginatorOptions{} + if params.MaxResults != nil { + options.Limit = *params.MaxResults } - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") + for _, fn := range optFns { + fn(&options) } - params := EndpointParameters{} + return &DescribeImageScanFindingsPaginator{ + options: options, + client: client, + params: params, + firstPage: true, + nextToken: params.NextToken, + } +} - m.BuiltInResolver.ResolveBuiltIns(¶ms) +// HasMorePages returns a boolean indicating whether more pages are available +func (p *DescribeImageScanFindingsPaginator) HasMorePages() bool { + return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) +} - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) +// NextPage retrieves the next DescribeImageScanFindings page. +func (p *DescribeImageScanFindingsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeImageScanFindingsOutput, error) { + if !p.HasMorePages() { + return nil, fmt.Errorf("no more pages available") } - req.URL = &resolvedEndpoint.URI + params := *p.params + params.NextToken = p.nextToken - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) + var limit *int32 + if p.options.Limit > 0 { + limit = &p.options.Limit } + params.MaxResults = limit - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) + result, err := p.client.DescribeImageScanFindings(ctx, ¶ms, optFns...) if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } + return nil, err } + p.firstPage = false - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } + prevToken := p.nextToken + p.nextToken = result.NextToken + + if p.options.StopOnDuplicateToken && + prevToken != nil && + p.nextToken != nil && + *prevToken == *p.nextToken { + p.nextToken = nil } - return next.HandleSerialize(ctx, in) + return result, nil +} + +// DescribeImageScanFindingsAPIClient is a client that implements the +// DescribeImageScanFindings operation. +type DescribeImageScanFindingsAPIClient interface { + DescribeImageScanFindings(context.Context, *DescribeImageScanFindingsInput, ...func(*Options)) (*DescribeImageScanFindingsOutput, error) } -func addDescribeImageScanFindingsResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opDescribeImageScanFindingsResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) +var _ DescribeImageScanFindingsAPIClient = (*Client)(nil) + +func newServiceMetadataMiddleware_opDescribeImageScanFindings(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DescribeImageScanFindings", + } } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeImages.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeImages.go index 788c7665e4..7d7e1a705d 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeImages.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeImages.go @@ -4,23 +4,19 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) -// Returns metadata about the images in a repository. Beginning with Docker -// version 1.9, the Docker client compresses image layers before pushing them to a -// V2 Docker registry. The output of the docker images command shows the -// uncompressed image size, so it may return a larger image size than the image -// sizes returned by DescribeImages . +// Returns metadata about the images in a repository. +// +// Beginning with Docker version 1.9, the Docker client compresses image layers +// before pushing them to a V2 Docker registry. The output of the docker images +// command shows the uncompressed image size, so it may return a larger image size +// than the image sizes returned by DescribeImages. func (c *Client) DescribeImages(ctx context.Context, params *DescribeImagesInput, optFns ...func(*Options)) (*DescribeImagesOutput, error) { if params == nil { params = &DescribeImagesInput{} @@ -92,6 +88,9 @@ type DescribeImagesOutput struct { } func (c *Client) addOperationDescribeImagesMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeImages{}, middleware.After) if err != nil { return err @@ -100,34 +99,38 @@ func (c *Client) addOperationDescribeImagesMiddlewares(stack *middleware.Stack, if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeImages"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -139,7 +142,13 @@ func (c *Client) addOperationDescribeImagesMiddlewares(stack *middleware.Stack, if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addDescribeImagesResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpDescribeImagesValidationMiddleware(stack); err != nil { @@ -148,7 +157,7 @@ func (c *Client) addOperationDescribeImagesMiddlewares(stack *middleware.Stack, if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeImages(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -160,20 +169,24 @@ func (c *Client) addOperationDescribeImagesMiddlewares(stack *middleware.Stack, if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil } -// DescribeImagesAPIClient is a client that implements the DescribeImages -// operation. -type DescribeImagesAPIClient interface { - DescribeImages(context.Context, *DescribeImagesInput, ...func(*Options)) (*DescribeImagesOutput, error) -} - -var _ DescribeImagesAPIClient = (*Client)(nil) - // DescribeImagesPaginatorOptions is the paginator options for DescribeImages type DescribeImagesPaginatorOptions struct { // The maximum number of repository results returned by DescribeImages in @@ -244,6 +257,9 @@ func (p *DescribeImagesPaginator) NextPage(ctx context.Context, optFns ...func(* } params.MaxResults = limit + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) result, err := p.client.DescribeImages(ctx, ¶ms, optFns...) if err != nil { return nil, err @@ -263,134 +279,18 @@ func (p *DescribeImagesPaginator) NextPage(ctx context.Context, optFns ...func(* return result, nil } +// DescribeImagesAPIClient is a client that implements the DescribeImages +// operation. +type DescribeImagesAPIClient interface { + DescribeImages(context.Context, *DescribeImagesInput, ...func(*Options)) (*DescribeImagesOutput, error) +} + +var _ DescribeImagesAPIClient = (*Client)(nil) + func newServiceMetadataMiddleware_opDescribeImages(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "DescribeImages", } } - -type opDescribeImagesResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opDescribeImagesResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opDescribeImagesResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addDescribeImagesResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opDescribeImagesResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribePullThroughCacheRules.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribePullThroughCacheRules.go index 85d4842bde..95933334e0 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribePullThroughCacheRules.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribePullThroughCacheRules.go @@ -4,14 +4,9 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -83,6 +78,9 @@ type DescribePullThroughCacheRulesOutput struct { } func (c *Client) addOperationDescribePullThroughCacheRulesMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribePullThroughCacheRules{}, middleware.After) if err != nil { return err @@ -91,34 +89,38 @@ func (c *Client) addOperationDescribePullThroughCacheRulesMiddlewares(stack *mid if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "DescribePullThroughCacheRules"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -130,13 +132,19 @@ func (c *Client) addOperationDescribePullThroughCacheRulesMiddlewares(stack *mid if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addDescribePullThroughCacheRulesResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribePullThroughCacheRules(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -148,20 +156,24 @@ func (c *Client) addOperationDescribePullThroughCacheRulesMiddlewares(stack *mid if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil } -// DescribePullThroughCacheRulesAPIClient is a client that implements the -// DescribePullThroughCacheRules operation. -type DescribePullThroughCacheRulesAPIClient interface { - DescribePullThroughCacheRules(context.Context, *DescribePullThroughCacheRulesInput, ...func(*Options)) (*DescribePullThroughCacheRulesOutput, error) -} - -var _ DescribePullThroughCacheRulesAPIClient = (*Client)(nil) - // DescribePullThroughCacheRulesPaginatorOptions is the paginator options for // DescribePullThroughCacheRules type DescribePullThroughCacheRulesPaginatorOptions struct { @@ -236,6 +248,9 @@ func (p *DescribePullThroughCacheRulesPaginator) NextPage(ctx context.Context, o } params.MaxResults = limit + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) result, err := p.client.DescribePullThroughCacheRules(ctx, ¶ms, optFns...) if err != nil { return nil, err @@ -255,134 +270,18 @@ func (p *DescribePullThroughCacheRulesPaginator) NextPage(ctx context.Context, o return result, nil } +// DescribePullThroughCacheRulesAPIClient is a client that implements the +// DescribePullThroughCacheRules operation. +type DescribePullThroughCacheRulesAPIClient interface { + DescribePullThroughCacheRules(context.Context, *DescribePullThroughCacheRulesInput, ...func(*Options)) (*DescribePullThroughCacheRulesOutput, error) +} + +var _ DescribePullThroughCacheRulesAPIClient = (*Client)(nil) + func newServiceMetadataMiddleware_opDescribePullThroughCacheRules(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "DescribePullThroughCacheRules", } } - -type opDescribePullThroughCacheRulesResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opDescribePullThroughCacheRulesResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opDescribePullThroughCacheRulesResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addDescribePullThroughCacheRulesResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opDescribePullThroughCacheRulesResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeRegistry.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeRegistry.go index e231a8f77c..5d5620ec0c 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeRegistry.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeRegistry.go @@ -4,21 +4,15 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Describes the settings for a registry. The replication configuration for a -// repository can be created or updated with the PutReplicationConfiguration API -// action. +// repository can be created or updated with the PutReplicationConfigurationAPI action. func (c *Client) DescribeRegistry(ctx context.Context, params *DescribeRegistryInput, optFns ...func(*Options)) (*DescribeRegistryOutput, error) { if params == nil { params = &DescribeRegistryInput{} @@ -40,7 +34,7 @@ type DescribeRegistryInput struct { type DescribeRegistryOutput struct { - // The ID of the registry. + // The registry ID associated with the request. RegistryId *string // The replication configuration for the registry. @@ -53,6 +47,9 @@ type DescribeRegistryOutput struct { } func (c *Client) addOperationDescribeRegistryMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeRegistry{}, middleware.After) if err != nil { return err @@ -61,34 +58,38 @@ func (c *Client) addOperationDescribeRegistryMiddlewares(stack *middleware.Stack if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeRegistry"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -100,13 +101,19 @@ func (c *Client) addOperationDescribeRegistryMiddlewares(stack *middleware.Stack if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addDescribeRegistryResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeRegistry(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -118,7 +125,19 @@ func (c *Client) addOperationDescribeRegistryMiddlewares(stack *middleware.Stack if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -128,130 +147,6 @@ func newServiceMetadataMiddleware_opDescribeRegistry(region string) *awsmiddlewa return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "DescribeRegistry", } } - -type opDescribeRegistryResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opDescribeRegistryResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opDescribeRegistryResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addDescribeRegistryResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opDescribeRegistryResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeRepositories.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeRepositories.go index 71fcebce6f..dc23fd0fb4 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeRepositories.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeRepositories.go @@ -4,14 +4,9 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -50,9 +45,10 @@ type DescribeRepositoriesInput struct { // parameter. Pagination continues from the end of the previous results that // returned the nextToken value. This value is null when there are no more results // to return. This option cannot be used when you specify repositories with - // repositoryNames . This token should be treated as an opaque identifier that is - // only used to retrieve the next items in a list and not for other programmatic - // purposes. + // repositoryNames . + // + // This token should be treated as an opaque identifier that is only used to + // retrieve the next items in a list and not for other programmatic purposes. NextToken *string // The Amazon Web Services account ID associated with the registry that contains @@ -85,6 +81,9 @@ type DescribeRepositoriesOutput struct { } func (c *Client) addOperationDescribeRepositoriesMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeRepositories{}, middleware.After) if err != nil { return err @@ -93,34 +92,38 @@ func (c *Client) addOperationDescribeRepositoriesMiddlewares(stack *middleware.S if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeRepositories"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -132,13 +135,19 @@ func (c *Client) addOperationDescribeRepositoriesMiddlewares(stack *middleware.S if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addDescribeRepositoriesResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeRepositories(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -150,20 +159,24 @@ func (c *Client) addOperationDescribeRepositoriesMiddlewares(stack *middleware.S if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil } -// DescribeRepositoriesAPIClient is a client that implements the -// DescribeRepositories operation. -type DescribeRepositoriesAPIClient interface { - DescribeRepositories(context.Context, *DescribeRepositoriesInput, ...func(*Options)) (*DescribeRepositoriesOutput, error) -} - -var _ DescribeRepositoriesAPIClient = (*Client)(nil) - // DescribeRepositoriesPaginatorOptions is the paginator options for // DescribeRepositories type DescribeRepositoriesPaginatorOptions struct { @@ -236,6 +249,9 @@ func (p *DescribeRepositoriesPaginator) NextPage(ctx context.Context, optFns ... } params.MaxResults = limit + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) result, err := p.client.DescribeRepositories(ctx, ¶ms, optFns...) if err != nil { return nil, err @@ -255,134 +271,18 @@ func (p *DescribeRepositoriesPaginator) NextPage(ctx context.Context, optFns ... return result, nil } +// DescribeRepositoriesAPIClient is a client that implements the +// DescribeRepositories operation. +type DescribeRepositoriesAPIClient interface { + DescribeRepositories(context.Context, *DescribeRepositoriesInput, ...func(*Options)) (*DescribeRepositoriesOutput, error) +} + +var _ DescribeRepositoriesAPIClient = (*Client)(nil) + func newServiceMetadataMiddleware_opDescribeRepositories(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "DescribeRepositories", } } - -type opDescribeRepositoriesResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opDescribeRepositoriesResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opDescribeRepositoriesResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addDescribeRepositoriesResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opDescribeRepositoriesResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeRepositoryCreationTemplates.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeRepositoryCreationTemplates.go new file mode 100644 index 0000000000..a5b6cd7086 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_DescribeRepositoryCreationTemplates.go @@ -0,0 +1,290 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package ecr + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/ecr/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Returns details about the repository creation templates in a registry. The +// prefixes request parameter can be used to return the details for a specific +// repository creation template. +func (c *Client) DescribeRepositoryCreationTemplates(ctx context.Context, params *DescribeRepositoryCreationTemplatesInput, optFns ...func(*Options)) (*DescribeRepositoryCreationTemplatesOutput, error) { + if params == nil { + params = &DescribeRepositoryCreationTemplatesInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DescribeRepositoryCreationTemplates", params, optFns, c.addOperationDescribeRepositoryCreationTemplatesMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DescribeRepositoryCreationTemplatesOutput) + out.ResultMetadata = metadata + return out, nil +} + +type DescribeRepositoryCreationTemplatesInput struct { + + // The maximum number of repository results returned by + // DescribeRepositoryCreationTemplatesRequest in paginated output. When this + // parameter is used, DescribeRepositoryCreationTemplatesRequest only returns + // maxResults results in a single page along with a nextToken response element. + // The remaining results of the initial request can be seen by sending another + // DescribeRepositoryCreationTemplatesRequest request with the returned nextToken + // value. This value can be between 1 and 1000. If this parameter is not used, then + // DescribeRepositoryCreationTemplatesRequest returns up to 100 results and a + // nextToken value, if applicable. + MaxResults *int32 + + // The nextToken value returned from a previous paginated + // DescribeRepositoryCreationTemplates request where maxResults was used and the + // results exceeded the value of that parameter. Pagination continues from the end + // of the previous results that returned the nextToken value. This value is null + // when there are no more results to return. + // + // This token should be treated as an opaque identifier that is only used to + // retrieve the next items in a list and not for other programmatic purposes. + NextToken *string + + // The repository namespace prefixes associated with the repository creation + // templates to describe. If this value is not specified, all repository creation + // templates are returned. + Prefixes []string + + noSmithyDocumentSerde +} + +type DescribeRepositoryCreationTemplatesOutput struct { + + // The nextToken value to include in a future DescribeRepositoryCreationTemplates + // request. When the results of a DescribeRepositoryCreationTemplates request + // exceed maxResults , this value can be used to retrieve the next page of results. + // This value is null when there are no more results to return. + NextToken *string + + // The registry ID associated with the request. + RegistryId *string + + // The details of the repository creation templates. + RepositoryCreationTemplates []types.RepositoryCreationTemplate + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDescribeRepositoryCreationTemplatesMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeRepositoryCreationTemplates{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeRepositoryCreationTemplates{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeRepositoryCreationTemplates"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeRepositoryCreationTemplates(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +// DescribeRepositoryCreationTemplatesPaginatorOptions is the paginator options +// for DescribeRepositoryCreationTemplates +type DescribeRepositoryCreationTemplatesPaginatorOptions struct { + // The maximum number of repository results returned by + // DescribeRepositoryCreationTemplatesRequest in paginated output. When this + // parameter is used, DescribeRepositoryCreationTemplatesRequest only returns + // maxResults results in a single page along with a nextToken response element. + // The remaining results of the initial request can be seen by sending another + // DescribeRepositoryCreationTemplatesRequest request with the returned nextToken + // value. This value can be between 1 and 1000. If this parameter is not used, then + // DescribeRepositoryCreationTemplatesRequest returns up to 100 results and a + // nextToken value, if applicable. + Limit int32 + + // Set to true if pagination should stop if the service returns a pagination token + // that matches the most recent token provided to the service. + StopOnDuplicateToken bool +} + +// DescribeRepositoryCreationTemplatesPaginator is a paginator for +// DescribeRepositoryCreationTemplates +type DescribeRepositoryCreationTemplatesPaginator struct { + options DescribeRepositoryCreationTemplatesPaginatorOptions + client DescribeRepositoryCreationTemplatesAPIClient + params *DescribeRepositoryCreationTemplatesInput + nextToken *string + firstPage bool +} + +// NewDescribeRepositoryCreationTemplatesPaginator returns a new +// DescribeRepositoryCreationTemplatesPaginator +func NewDescribeRepositoryCreationTemplatesPaginator(client DescribeRepositoryCreationTemplatesAPIClient, params *DescribeRepositoryCreationTemplatesInput, optFns ...func(*DescribeRepositoryCreationTemplatesPaginatorOptions)) *DescribeRepositoryCreationTemplatesPaginator { + if params == nil { + params = &DescribeRepositoryCreationTemplatesInput{} + } + + options := DescribeRepositoryCreationTemplatesPaginatorOptions{} + if params.MaxResults != nil { + options.Limit = *params.MaxResults + } + + for _, fn := range optFns { + fn(&options) + } + + return &DescribeRepositoryCreationTemplatesPaginator{ + options: options, + client: client, + params: params, + firstPage: true, + nextToken: params.NextToken, + } +} + +// HasMorePages returns a boolean indicating whether more pages are available +func (p *DescribeRepositoryCreationTemplatesPaginator) HasMorePages() bool { + return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) +} + +// NextPage retrieves the next DescribeRepositoryCreationTemplates page. +func (p *DescribeRepositoryCreationTemplatesPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeRepositoryCreationTemplatesOutput, error) { + if !p.HasMorePages() { + return nil, fmt.Errorf("no more pages available") + } + + params := *p.params + params.NextToken = p.nextToken + + var limit *int32 + if p.options.Limit > 0 { + limit = &p.options.Limit + } + params.MaxResults = limit + + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) + result, err := p.client.DescribeRepositoryCreationTemplates(ctx, ¶ms, optFns...) + if err != nil { + return nil, err + } + p.firstPage = false + + prevToken := p.nextToken + p.nextToken = result.NextToken + + if p.options.StopOnDuplicateToken && + prevToken != nil && + p.nextToken != nil && + *prevToken == *p.nextToken { + p.nextToken = nil + } + + return result, nil +} + +// DescribeRepositoryCreationTemplatesAPIClient is a client that implements the +// DescribeRepositoryCreationTemplates operation. +type DescribeRepositoryCreationTemplatesAPIClient interface { + DescribeRepositoryCreationTemplates(context.Context, *DescribeRepositoryCreationTemplatesInput, ...func(*Options)) (*DescribeRepositoryCreationTemplatesOutput, error) +} + +var _ DescribeRepositoryCreationTemplatesAPIClient = (*Client)(nil) + +func newServiceMetadataMiddleware_opDescribeRepositoryCreationTemplates(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DescribeRepositoryCreationTemplates", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetAccountSetting.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetAccountSetting.go new file mode 100644 index 0000000000..81d103ae23 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetAccountSetting.go @@ -0,0 +1,162 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package ecr + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Retrieves the account setting value for the specified setting name. +func (c *Client) GetAccountSetting(ctx context.Context, params *GetAccountSettingInput, optFns ...func(*Options)) (*GetAccountSettingOutput, error) { + if params == nil { + params = &GetAccountSettingInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetAccountSetting", params, optFns, c.addOperationGetAccountSettingMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetAccountSettingOutput) + out.ResultMetadata = metadata + return out, nil +} + +type GetAccountSettingInput struct { + + // The name of the account setting, such as BASIC_SCAN_TYPE_VERSION or + // REGISTRY_POLICY_SCOPE . + // + // This member is required. + Name *string + + noSmithyDocumentSerde +} + +type GetAccountSettingOutput struct { + + // Retrieves the name of the account setting. + Name *string + + // The setting value for the setting name. The following are valid values for the + // basic scan type being used: AWS_NATIVE or CLAIR . The following are valid values + // for the registry policy scope being used: V1 or V2 . + Value *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetAccountSettingMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetAccountSetting{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetAccountSetting{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetAccountSetting"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addOpGetAccountSettingValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetAccountSetting(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetAccountSetting(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetAccountSetting", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetAuthorizationToken.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetAuthorizationToken.go index f630eef052..c29ba7b44e 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetAuthorizationToken.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetAuthorizationToken.go @@ -4,14 +4,9 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -19,11 +14,14 @@ import ( // Retrieves an authorization token. An authorization token represents your IAM // authentication credentials and can be used to access any Amazon ECR registry // that your IAM principal has access to. The authorization token is valid for 12 -// hours. The authorizationToken returned is a base64 encoded string that can be -// decoded and used in a docker login command to authenticate to a registry. The -// CLI offers an get-login-password command that simplifies the login process. For -// more information, see Registry authentication (https://docs.aws.amazon.com/AmazonECR/latest/userguide/Registries.html#registry_auth) -// in the Amazon Elastic Container Registry User Guide. +// hours. +// +// The authorizationToken returned is a base64 encoded string that can be decoded +// and used in a docker login command to authenticate to a registry. The CLI +// offers an get-login-password command that simplifies the login process. For +// more information, see [Registry authentication]in the Amazon Elastic Container Registry User Guide. +// +// [Registry authentication]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/Registries.html#registry_auth func (c *Client) GetAuthorizationToken(ctx context.Context, params *GetAuthorizationTokenInput, optFns ...func(*Options)) (*GetAuthorizationTokenOutput, error) { if params == nil { params = &GetAuthorizationTokenInput{} @@ -67,6 +65,9 @@ type GetAuthorizationTokenOutput struct { } func (c *Client) addOperationGetAuthorizationTokenMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetAuthorizationToken{}, middleware.After) if err != nil { return err @@ -75,34 +76,38 @@ func (c *Client) addOperationGetAuthorizationTokenMiddlewares(stack *middleware. if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetAuthorizationToken"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -114,13 +119,19 @@ func (c *Client) addOperationGetAuthorizationTokenMiddlewares(stack *middleware. if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addGetAuthorizationTokenResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetAuthorizationToken(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -132,7 +143,19 @@ func (c *Client) addOperationGetAuthorizationTokenMiddlewares(stack *middleware. if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -142,130 +165,6 @@ func newServiceMetadataMiddleware_opGetAuthorizationToken(region string) *awsmid return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "GetAuthorizationToken", } } - -type opGetAuthorizationTokenResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opGetAuthorizationTokenResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opGetAuthorizationTokenResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addGetAuthorizationTokenResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opGetAuthorizationTokenResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetDownloadUrlForLayer.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetDownloadUrlForLayer.go index 26bb7b9f53..891045572e 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetDownloadUrlForLayer.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetDownloadUrlForLayer.go @@ -4,23 +4,21 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Retrieves the pre-signed Amazon S3 download URL corresponding to an image // layer. You can only get URLs for image layers that are referenced in an image. -// When an image is pulled, the GetDownloadUrlForLayer API is called once per image -// layer that is not already cached. This operation is used by the Amazon ECR proxy -// and is not generally used by customers for pulling and pushing images. In most -// cases, you should use the docker CLI to pull, tag, and push images. +// +// When an image is pulled, the GetDownloadUrlForLayer API is called once per +// image layer that is not already cached. +// +// This operation is used by the Amazon ECR proxy and is not generally used by +// customers for pulling and pushing images. In most cases, you should use the +// docker CLI to pull, tag, and push images. func (c *Client) GetDownloadUrlForLayer(ctx context.Context, params *GetDownloadUrlForLayerInput, optFns ...func(*Options)) (*GetDownloadUrlForLayerOutput, error) { if params == nil { params = &GetDownloadUrlForLayerInput{} @@ -71,6 +69,9 @@ type GetDownloadUrlForLayerOutput struct { } func (c *Client) addOperationGetDownloadUrlForLayerMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetDownloadUrlForLayer{}, middleware.After) if err != nil { return err @@ -79,34 +80,38 @@ func (c *Client) addOperationGetDownloadUrlForLayerMiddlewares(stack *middleware if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetDownloadUrlForLayer"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -118,7 +123,13 @@ func (c *Client) addOperationGetDownloadUrlForLayerMiddlewares(stack *middleware if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addGetDownloadUrlForLayerResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpGetDownloadUrlForLayerValidationMiddleware(stack); err != nil { @@ -127,7 +138,7 @@ func (c *Client) addOperationGetDownloadUrlForLayerMiddlewares(stack *middleware if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetDownloadUrlForLayer(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -139,7 +150,19 @@ func (c *Client) addOperationGetDownloadUrlForLayerMiddlewares(stack *middleware if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -149,130 +172,6 @@ func newServiceMetadataMiddleware_opGetDownloadUrlForLayer(region string) *awsmi return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "GetDownloadUrlForLayer", } } - -type opGetDownloadUrlForLayerResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opGetDownloadUrlForLayerResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opGetDownloadUrlForLayerResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addGetDownloadUrlForLayerResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opGetDownloadUrlForLayerResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetLifecyclePolicy.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetLifecyclePolicy.go index ee6b4b6f66..408a61534d 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetLifecyclePolicy.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetLifecyclePolicy.go @@ -4,13 +4,8 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" "time" @@ -68,6 +63,9 @@ type GetLifecyclePolicyOutput struct { } func (c *Client) addOperationGetLifecyclePolicyMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetLifecyclePolicy{}, middleware.After) if err != nil { return err @@ -76,34 +74,38 @@ func (c *Client) addOperationGetLifecyclePolicyMiddlewares(stack *middleware.Sta if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetLifecyclePolicy"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -115,7 +117,13 @@ func (c *Client) addOperationGetLifecyclePolicyMiddlewares(stack *middleware.Sta if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addGetLifecyclePolicyResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpGetLifecyclePolicyValidationMiddleware(stack); err != nil { @@ -124,7 +132,7 @@ func (c *Client) addOperationGetLifecyclePolicyMiddlewares(stack *middleware.Sta if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetLifecyclePolicy(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -136,7 +144,19 @@ func (c *Client) addOperationGetLifecyclePolicyMiddlewares(stack *middleware.Sta if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -146,130 +166,6 @@ func newServiceMetadataMiddleware_opGetLifecyclePolicy(region string) *awsmiddle return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "GetLifecyclePolicy", } } - -type opGetLifecyclePolicyResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opGetLifecyclePolicyResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opGetLifecyclePolicyResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addGetLifecyclePolicyResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opGetLifecyclePolicyResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetLifecyclePolicyPreview.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetLifecyclePolicyPreview.go index 5de6abc4f8..482152df72 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetLifecyclePolicyPreview.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetLifecyclePolicyPreview.go @@ -4,19 +4,13 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithytime "github.com/aws/smithy-go/time" smithyhttp "github.com/aws/smithy-go/transport/http" smithywaiter "github.com/aws/smithy-go/waiter" - "github.com/jmespath/go-jmespath" "time" ) @@ -112,6 +106,9 @@ type GetLifecyclePolicyPreviewOutput struct { } func (c *Client) addOperationGetLifecyclePolicyPreviewMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetLifecyclePolicyPreview{}, middleware.After) if err != nil { return err @@ -120,34 +117,38 @@ func (c *Client) addOperationGetLifecyclePolicyPreviewMiddlewares(stack *middlew if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetLifecyclePolicyPreview"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -159,7 +160,13 @@ func (c *Client) addOperationGetLifecyclePolicyPreviewMiddlewares(stack *middlew if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addGetLifecyclePolicyPreviewResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpGetLifecyclePolicyPreviewValidationMiddleware(stack); err != nil { @@ -168,7 +175,7 @@ func (c *Client) addOperationGetLifecyclePolicyPreviewMiddlewares(stack *middlew if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetLifecyclePolicyPreview(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -180,111 +187,22 @@ func (c *Client) addOperationGetLifecyclePolicyPreviewMiddlewares(stack *middlew if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { return err } - return nil -} - -// GetLifecyclePolicyPreviewAPIClient is a client that implements the -// GetLifecyclePolicyPreview operation. -type GetLifecyclePolicyPreviewAPIClient interface { - GetLifecyclePolicyPreview(context.Context, *GetLifecyclePolicyPreviewInput, ...func(*Options)) (*GetLifecyclePolicyPreviewOutput, error) -} - -var _ GetLifecyclePolicyPreviewAPIClient = (*Client)(nil) - -// GetLifecyclePolicyPreviewPaginatorOptions is the paginator options for -// GetLifecyclePolicyPreview -type GetLifecyclePolicyPreviewPaginatorOptions struct { - // The maximum number of repository results returned by - // GetLifecyclePolicyPreviewRequest in
 paginated output. When this parameter is - // used, GetLifecyclePolicyPreviewRequest only returns
 maxResults results in a - // single page along with a nextToken 
 response element. The remaining results of - // the initial request can be seen by sending
 another - // GetLifecyclePolicyPreviewRequest request with the returned nextToken 
 value. - // This value can be between 1 and 1000. If this
 parameter is not used, then - // GetLifecyclePolicyPreviewRequest returns up to
 100 results and a nextToken - // value, if
 applicable. This option cannot be used when you specify images with - // imageIds . - Limit int32 - - // Set to true if pagination should stop if the service returns a pagination token - // that matches the most recent token provided to the service. - StopOnDuplicateToken bool -} - -// GetLifecyclePolicyPreviewPaginator is a paginator for GetLifecyclePolicyPreview -type GetLifecyclePolicyPreviewPaginator struct { - options GetLifecyclePolicyPreviewPaginatorOptions - client GetLifecyclePolicyPreviewAPIClient - params *GetLifecyclePolicyPreviewInput - nextToken *string - firstPage bool -} - -// NewGetLifecyclePolicyPreviewPaginator returns a new -// GetLifecyclePolicyPreviewPaginator -func NewGetLifecyclePolicyPreviewPaginator(client GetLifecyclePolicyPreviewAPIClient, params *GetLifecyclePolicyPreviewInput, optFns ...func(*GetLifecyclePolicyPreviewPaginatorOptions)) *GetLifecyclePolicyPreviewPaginator { - if params == nil { - params = &GetLifecyclePolicyPreviewInput{} - } - - options := GetLifecyclePolicyPreviewPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &GetLifecyclePolicyPreviewPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *GetLifecyclePolicyPreviewPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next GetLifecyclePolicyPreview page. -func (p *GetLifecyclePolicyPreviewPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*GetLifecyclePolicyPreviewOutput, error) { - if !p.HasMorePages() { - return nil, fmt.Errorf("no more pages available") + if err = addSpanInitializeStart(stack); err != nil { + return err } - - params := *p.params - params.NextToken = p.nextToken - - var limit *int32 - if p.options.Limit > 0 { - limit = &p.options.Limit + if err = addSpanInitializeEnd(stack); err != nil { + return err } - params.MaxResults = limit - - result, err := p.client.GetLifecyclePolicyPreview(ctx, ¶ms, optFns...) - if err != nil { - return nil, err + if err = addSpanBuildRequestStart(stack); err != nil { + return err } - p.firstPage = false - - prevToken := p.nextToken - p.nextToken = result.NextToken - - if p.options.StopOnDuplicateToken && - prevToken != nil && - p.nextToken != nil && - *prevToken == *p.nextToken { - p.nextToken = nil + if err = addSpanBuildRequestEnd(stack); err != nil { + return err } - - return result, nil + return nil } // LifecyclePolicyPreviewCompleteWaiterOptions are waiter options for @@ -294,8 +212,17 @@ type LifecyclePolicyPreviewCompleteWaiterOptions struct { // Set of options to modify how an operation is invoked. These apply to all // operations invoked for this client. Use functional options on operation call to // modify this list for per operation behavior. + // + // Passing options here is functionally equivalent to passing values to this + // config's ClientOptions field that extend the inner client's APIOptions directly. APIOptions []func(*middleware.Stack) error + // Functional options to be passed to all operations invoked by this client. + // + // Function values that modify the inner APIOptions are applied after the waiter + // config's own APIOptions modifiers. + ClientOptions []func(*Options) + // MinDelay is the minimum amount of time to delay between retries. If unset, // LifecyclePolicyPreviewCompleteWaiter will use default minimum delay of 5 // seconds. Note that MinDelay must resolve to a value lesser than or equal to the @@ -313,12 +240,13 @@ type LifecyclePolicyPreviewCompleteWaiterOptions struct { // Retryable is function that can be used to override the service defined // waiter-behavior based on operation output, or returned error. This function is - // used by the waiter to decide if a state is retryable or a terminal state. By - // default service-modeled logic will populate this option. This option can thus be - // used to define a custom waiter state with fall-back to service-modeled waiter - // state mutators.The function returns an error in case of a failure state. In case - // of retry state, this function returns a bool value of true and nil error, while - // in case of success it returns a bool value of false and nil error. + // used by the waiter to decide if a state is retryable or a terminal state. + // + // By default service-modeled logic will populate this option. This option can + // thus be used to define a custom waiter state with fall-back to service-modeled + // waiter state mutators.The function returns an error in case of a failure state. + // In case of retry state, this function returns a bool value of true and nil + // error, while in case of success it returns a bool value of false and nil error. Retryable func(context.Context, *GetLifecyclePolicyPreviewInput, *GetLifecyclePolicyPreviewOutput, error) (bool, error) } @@ -397,7 +325,16 @@ func (w *LifecyclePolicyPreviewCompleteWaiter) WaitForOutput(ctx context.Context } out, err := w.client.GetLifecyclePolicyPreview(ctx, params, func(o *Options) { + baseOpts := []func(*Options){ + addIsWaiterUserAgent, + } o.APIOptions = append(o.APIOptions, apiOptions...) + for _, opt := range baseOpts { + opt(o) + } + for _, opt := range options.ClientOptions { + opt(o) + } }) retryable, err := options.Retryable(ctx, params, out, err) @@ -433,170 +370,139 @@ func (w *LifecyclePolicyPreviewCompleteWaiter) WaitForOutput(ctx context.Context func lifecyclePolicyPreviewCompleteStateRetryable(ctx context.Context, input *GetLifecyclePolicyPreviewInput, output *GetLifecyclePolicyPreviewOutput, err error) (bool, error) { if err == nil { - pathValue, err := jmespath.Search("status", output) - if err != nil { - return false, fmt.Errorf("error evaluating waiter state: %w", err) - } - + v1 := output.Status expectedValue := "COMPLETE" - value, ok := pathValue.(types.LifecyclePolicyPreviewStatus) - if !ok { - return false, fmt.Errorf("waiter comparator expected types.LifecyclePolicyPreviewStatus value, got %T", pathValue) - } - - if string(value) == expectedValue { + var pathValue string + pathValue = string(v1) + if pathValue == expectedValue { return false, nil } } if err == nil { - pathValue, err := jmespath.Search("status", output) - if err != nil { - return false, fmt.Errorf("error evaluating waiter state: %w", err) - } - + v1 := output.Status expectedValue := "FAILED" - value, ok := pathValue.(types.LifecyclePolicyPreviewStatus) - if !ok { - return false, fmt.Errorf("waiter comparator expected types.LifecyclePolicyPreviewStatus value, got %T", pathValue) - } - - if string(value) == expectedValue { + var pathValue string + pathValue = string(v1) + if pathValue == expectedValue { return false, fmt.Errorf("waiter state transitioned to Failure") } } + if err != nil { + return false, err + } return true, nil } -func newServiceMetadataMiddleware_opGetLifecyclePolicyPreview(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - SigningName: "ecr", - OperationName: "GetLifecyclePolicyPreview", - } -} +// GetLifecyclePolicyPreviewPaginatorOptions is the paginator options for +// GetLifecyclePolicyPreview +type GetLifecyclePolicyPreviewPaginatorOptions struct { + // The maximum number of repository results returned by + // GetLifecyclePolicyPreviewRequest in
 paginated output. When this parameter is + // used, GetLifecyclePolicyPreviewRequest only returns
 maxResults results in a + // single page along with a nextToken 
 response element. The remaining results of + // the initial request can be seen by sending
 another + // GetLifecyclePolicyPreviewRequest request with the returned nextToken 
 value. + // This value can be between 1 and 1000. If this
 parameter is not used, then + // GetLifecyclePolicyPreviewRequest returns up to
 100 results and a nextToken + // value, if
 applicable. This option cannot be used when you specify images with + // imageIds . + Limit int32 -type opGetLifecyclePolicyPreviewResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver + // Set to true if pagination should stop if the service returns a pagination token + // that matches the most recent token provided to the service. + StopOnDuplicateToken bool } -func (*opGetLifecyclePolicyPreviewResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" +// GetLifecyclePolicyPreviewPaginator is a paginator for GetLifecyclePolicyPreview +type GetLifecyclePolicyPreviewPaginator struct { + options GetLifecyclePolicyPreviewPaginatorOptions + client GetLifecyclePolicyPreviewAPIClient + params *GetLifecyclePolicyPreviewInput + nextToken *string + firstPage bool } -func (m *opGetLifecyclePolicyPreviewResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) +// NewGetLifecyclePolicyPreviewPaginator returns a new +// GetLifecyclePolicyPreviewPaginator +func NewGetLifecyclePolicyPreviewPaginator(client GetLifecyclePolicyPreviewAPIClient, params *GetLifecyclePolicyPreviewInput, optFns ...func(*GetLifecyclePolicyPreviewPaginatorOptions)) *GetLifecyclePolicyPreviewPaginator { + if params == nil { + params = &GetLifecyclePolicyPreviewInput{} } - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) + options := GetLifecyclePolicyPreviewPaginatorOptions{} + if params.MaxResults != nil { + options.Limit = *params.MaxResults } - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") + for _, fn := range optFns { + fn(&options) } - params := EndpointParameters{} + return &GetLifecyclePolicyPreviewPaginator{ + options: options, + client: client, + params: params, + firstPage: true, + nextToken: params.NextToken, + } +} - m.BuiltInResolver.ResolveBuiltIns(¶ms) +// HasMorePages returns a boolean indicating whether more pages are available +func (p *GetLifecyclePolicyPreviewPaginator) HasMorePages() bool { + return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) +} - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) +// NextPage retrieves the next GetLifecyclePolicyPreview page. +func (p *GetLifecyclePolicyPreviewPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*GetLifecyclePolicyPreviewOutput, error) { + if !p.HasMorePages() { + return nil, fmt.Errorf("no more pages available") } - req.URL = &resolvedEndpoint.URI + params := *p.params + params.NextToken = p.nextToken - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) + var limit *int32 + if p.options.Limit > 0 { + limit = &p.options.Limit } + params.MaxResults = limit - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) + result, err := p.client.GetLifecyclePolicyPreview(ctx, ¶ms, optFns...) if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } + return nil, err } + p.firstPage = false - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } + prevToken := p.nextToken + p.nextToken = result.NextToken + + if p.options.StopOnDuplicateToken && + prevToken != nil && + p.nextToken != nil && + *prevToken == *p.nextToken { + p.nextToken = nil } - return next.HandleSerialize(ctx, in) + return result, nil } -func addGetLifecyclePolicyPreviewResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opGetLifecyclePolicyPreviewResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) +// GetLifecyclePolicyPreviewAPIClient is a client that implements the +// GetLifecyclePolicyPreview operation. +type GetLifecyclePolicyPreviewAPIClient interface { + GetLifecyclePolicyPreview(context.Context, *GetLifecyclePolicyPreviewInput, ...func(*Options)) (*GetLifecyclePolicyPreviewOutput, error) +} + +var _ GetLifecyclePolicyPreviewAPIClient = (*Client)(nil) + +func newServiceMetadataMiddleware_opGetLifecyclePolicyPreview(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetLifecyclePolicyPreview", + } } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetRegistryPolicy.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetRegistryPolicy.go index 23c0a5788b..420344e663 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetRegistryPolicy.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetRegistryPolicy.go @@ -4,13 +4,8 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -40,7 +35,7 @@ type GetRegistryPolicyOutput struct { // The JSON text of the permissions policy for a registry. PolicyText *string - // The ID of the registry. + // The registry ID associated with the request. RegistryId *string // Metadata pertaining to the operation's result. @@ -50,6 +45,9 @@ type GetRegistryPolicyOutput struct { } func (c *Client) addOperationGetRegistryPolicyMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetRegistryPolicy{}, middleware.After) if err != nil { return err @@ -58,34 +56,38 @@ func (c *Client) addOperationGetRegistryPolicyMiddlewares(stack *middleware.Stac if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetRegistryPolicy"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -97,13 +99,19 @@ func (c *Client) addOperationGetRegistryPolicyMiddlewares(stack *middleware.Stac if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addGetRegistryPolicyResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetRegistryPolicy(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -115,7 +123,19 @@ func (c *Client) addOperationGetRegistryPolicyMiddlewares(stack *middleware.Stac if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -125,130 +145,6 @@ func newServiceMetadataMiddleware_opGetRegistryPolicy(region string) *awsmiddlew return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "GetRegistryPolicy", } } - -type opGetRegistryPolicyResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opGetRegistryPolicyResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opGetRegistryPolicyResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addGetRegistryPolicyResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opGetRegistryPolicyResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetRegistryScanningConfiguration.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetRegistryScanningConfiguration.go index 822c88c09a..5955ff467e 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetRegistryScanningConfiguration.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetRegistryScanningConfiguration.go @@ -4,14 +4,9 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -38,7 +33,7 @@ type GetRegistryScanningConfigurationInput struct { type GetRegistryScanningConfigurationOutput struct { - // The ID of the registry. + // The registry ID associated with the request. RegistryId *string // The scanning configuration for the registry. @@ -51,6 +46,9 @@ type GetRegistryScanningConfigurationOutput struct { } func (c *Client) addOperationGetRegistryScanningConfigurationMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetRegistryScanningConfiguration{}, middleware.After) if err != nil { return err @@ -59,34 +57,38 @@ func (c *Client) addOperationGetRegistryScanningConfigurationMiddlewares(stack * if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetRegistryScanningConfiguration"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -98,13 +100,19 @@ func (c *Client) addOperationGetRegistryScanningConfigurationMiddlewares(stack * if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addGetRegistryScanningConfigurationResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetRegistryScanningConfiguration(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -116,7 +124,19 @@ func (c *Client) addOperationGetRegistryScanningConfigurationMiddlewares(stack * if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -126,130 +146,6 @@ func newServiceMetadataMiddleware_opGetRegistryScanningConfiguration(region stri return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "GetRegistryScanningConfiguration", } } - -type opGetRegistryScanningConfigurationResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opGetRegistryScanningConfigurationResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opGetRegistryScanningConfigurationResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addGetRegistryScanningConfigurationResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opGetRegistryScanningConfigurationResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetRepositoryPolicy.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetRepositoryPolicy.go index f5c6bb6246..a7325987f8 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetRepositoryPolicy.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_GetRepositoryPolicy.go @@ -4,13 +4,8 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -64,6 +59,9 @@ type GetRepositoryPolicyOutput struct { } func (c *Client) addOperationGetRepositoryPolicyMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetRepositoryPolicy{}, middleware.After) if err != nil { return err @@ -72,34 +70,38 @@ func (c *Client) addOperationGetRepositoryPolicyMiddlewares(stack *middleware.St if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetRepositoryPolicy"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -111,7 +113,13 @@ func (c *Client) addOperationGetRepositoryPolicyMiddlewares(stack *middleware.St if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addGetRepositoryPolicyResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpGetRepositoryPolicyValidationMiddleware(stack); err != nil { @@ -120,7 +128,7 @@ func (c *Client) addOperationGetRepositoryPolicyMiddlewares(stack *middleware.St if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetRepositoryPolicy(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -132,7 +140,19 @@ func (c *Client) addOperationGetRepositoryPolicyMiddlewares(stack *middleware.St if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -142,130 +162,6 @@ func newServiceMetadataMiddleware_opGetRepositoryPolicy(region string) *awsmiddl return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "GetRepositoryPolicy", } } - -type opGetRepositoryPolicyResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opGetRepositoryPolicyResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opGetRepositoryPolicyResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addGetRepositoryPolicyResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opGetRepositoryPolicyResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_InitiateLayerUpload.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_InitiateLayerUpload.go index dba5e3cce1..f5b62d505e 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_InitiateLayerUpload.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_InitiateLayerUpload.go @@ -4,24 +4,21 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) -// Notifies Amazon ECR that you intend to upload an image layer. When an image is -// pushed, the InitiateLayerUpload API is called once per image layer that has not -// already been uploaded. Whether or not an image layer has been uploaded is -// determined by the BatchCheckLayerAvailability API action. This operation is used -// by the Amazon ECR proxy and is not generally used by customers for pulling and -// pushing images. In most cases, you should use the docker CLI to pull, tag, and -// push images. +// Notifies Amazon ECR that you intend to upload an image layer. +// +// When an image is pushed, the InitiateLayerUpload API is called once per image +// layer that has not already been uploaded. Whether or not an image layer has been +// uploaded is determined by the BatchCheckLayerAvailability API action. +// +// This operation is used by the Amazon ECR proxy and is not generally used by +// customers for pulling and pushing images. In most cases, you should use the +// docker CLI to pull, tag, and push images. func (c *Client) InitiateLayerUpload(ctx context.Context, params *InitiateLayerUploadInput, optFns ...func(*Options)) (*InitiateLayerUploadOutput, error) { if params == nil { params = &InitiateLayerUploadInput{} @@ -57,8 +54,8 @@ type InitiateLayerUploadOutput struct { // The size, in bytes, that Amazon ECR expects future layer part uploads to be. PartSize *int64 - // The upload ID for the layer upload. This parameter is passed to further - // UploadLayerPart and CompleteLayerUpload operations. + // The upload ID for the layer upload. This parameter is passed to further UploadLayerPart and CompleteLayerUpload + // operations. UploadId *string // Metadata pertaining to the operation's result. @@ -68,6 +65,9 @@ type InitiateLayerUploadOutput struct { } func (c *Client) addOperationInitiateLayerUploadMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpInitiateLayerUpload{}, middleware.After) if err != nil { return err @@ -76,34 +76,38 @@ func (c *Client) addOperationInitiateLayerUploadMiddlewares(stack *middleware.St if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "InitiateLayerUpload"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -115,7 +119,13 @@ func (c *Client) addOperationInitiateLayerUploadMiddlewares(stack *middleware.St if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addInitiateLayerUploadResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpInitiateLayerUploadValidationMiddleware(stack); err != nil { @@ -124,7 +134,7 @@ func (c *Client) addOperationInitiateLayerUploadMiddlewares(stack *middleware.St if err = stack.Initialize.Add(newServiceMetadataMiddleware_opInitiateLayerUpload(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -136,7 +146,19 @@ func (c *Client) addOperationInitiateLayerUploadMiddlewares(stack *middleware.St if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -146,130 +168,6 @@ func newServiceMetadataMiddleware_opInitiateLayerUpload(region string) *awsmiddl return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "InitiateLayerUpload", } } - -type opInitiateLayerUploadResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opInitiateLayerUploadResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opInitiateLayerUploadResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addInitiateLayerUploadResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opInitiateLayerUploadResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_ListImages.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_ListImages.go index 785e83adc5..09f0f065a3 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_ListImages.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_ListImages.go @@ -4,24 +4,20 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) -// Lists all the image IDs for the specified repository. You can filter images -// based on whether or not they are tagged by using the tagStatus filter and -// specifying either TAGGED , UNTAGGED or ANY . For example, you can filter your -// results to return only UNTAGGED images and then pipe that result to a -// BatchDeleteImage operation to delete them. Or, you can filter your results to -// return only TAGGED images to list all of the tags in your repository. +// Lists all the image IDs for the specified repository. +// +// You can filter images based on whether or not they are tagged by using the +// tagStatus filter and specifying either TAGGED , UNTAGGED or ANY . For example, +// you can filter your results to return only UNTAGGED images and then pipe that +// result to a BatchDeleteImageoperation to delete them. Or, you can filter your results to return +// only TAGGED images to list all of the tags in your repository. func (c *Client) ListImages(ctx context.Context, params *ListImagesInput, optFns ...func(*Options)) (*ListImagesOutput, error) { if params == nil { params = &ListImagesInput{} @@ -60,6 +56,7 @@ type ListImagesInput struct { // maxResults was used and the results exceeded the value of that parameter. // Pagination continues from the end of the previous results that returned the // nextToken value. This value is null when there are no more results to return. + // // This token should be treated as an opaque identifier that is only used to // retrieve the next items in a list and not for other programmatic purposes. NextToken *string @@ -90,6 +87,9 @@ type ListImagesOutput struct { } func (c *Client) addOperationListImagesMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpListImages{}, middleware.After) if err != nil { return err @@ -98,34 +98,38 @@ func (c *Client) addOperationListImagesMiddlewares(stack *middleware.Stack, opti if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "ListImages"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -137,7 +141,13 @@ func (c *Client) addOperationListImagesMiddlewares(stack *middleware.Stack, opti if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addListImagesResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpListImagesValidationMiddleware(stack); err != nil { @@ -146,7 +156,7 @@ func (c *Client) addOperationListImagesMiddlewares(stack *middleware.Stack, opti if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListImages(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -158,19 +168,24 @@ func (c *Client) addOperationListImagesMiddlewares(stack *middleware.Stack, opti if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil } -// ListImagesAPIClient is a client that implements the ListImages operation. -type ListImagesAPIClient interface { - ListImages(context.Context, *ListImagesInput, ...func(*Options)) (*ListImagesOutput, error) -} - -var _ ListImagesAPIClient = (*Client)(nil) - // ListImagesPaginatorOptions is the paginator options for ListImages type ListImagesPaginatorOptions struct { // The maximum number of image results returned by ListImages in paginated output. @@ -240,6 +255,9 @@ func (p *ListImagesPaginator) NextPage(ctx context.Context, optFns ...func(*Opti } params.MaxResults = limit + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) result, err := p.client.ListImages(ctx, ¶ms, optFns...) if err != nil { return nil, err @@ -259,134 +277,17 @@ func (p *ListImagesPaginator) NextPage(ctx context.Context, optFns ...func(*Opti return result, nil } +// ListImagesAPIClient is a client that implements the ListImages operation. +type ListImagesAPIClient interface { + ListImages(context.Context, *ListImagesInput, ...func(*Options)) (*ListImagesOutput, error) +} + +var _ ListImagesAPIClient = (*Client)(nil) + func newServiceMetadataMiddleware_opListImages(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "ListImages", } } - -type opListImagesResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opListImagesResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opListImagesResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addListImagesResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opListImagesResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_ListTagsForResource.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_ListTagsForResource.go index 80147049f0..00ecd807f1 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_ListTagsForResource.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_ListTagsForResource.go @@ -4,14 +4,9 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -55,6 +50,9 @@ type ListTagsForResourceOutput struct { } func (c *Client) addOperationListTagsForResourceMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpListTagsForResource{}, middleware.After) if err != nil { return err @@ -63,34 +61,38 @@ func (c *Client) addOperationListTagsForResourceMiddlewares(stack *middleware.St if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "ListTagsForResource"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -102,7 +104,13 @@ func (c *Client) addOperationListTagsForResourceMiddlewares(stack *middleware.St if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addListTagsForResourceResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpListTagsForResourceValidationMiddleware(stack); err != nil { @@ -111,7 +119,7 @@ func (c *Client) addOperationListTagsForResourceMiddlewares(stack *middleware.St if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListTagsForResource(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -123,7 +131,19 @@ func (c *Client) addOperationListTagsForResourceMiddlewares(stack *middleware.St if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -133,130 +153,6 @@ func newServiceMetadataMiddleware_opListTagsForResource(region string) *awsmiddl return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "ListTagsForResource", } } - -type opListTagsForResourceResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opListTagsForResourceResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opListTagsForResourceResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addListTagsForResourceResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opListTagsForResourceResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutAccountSetting.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutAccountSetting.go new file mode 100644 index 0000000000..2075a4127e --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutAccountSetting.go @@ -0,0 +1,167 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package ecr + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Allows you to change the basic scan type version or registry policy scope. +func (c *Client) PutAccountSetting(ctx context.Context, params *PutAccountSettingInput, optFns ...func(*Options)) (*PutAccountSettingOutput, error) { + if params == nil { + params = &PutAccountSettingInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "PutAccountSetting", params, optFns, c.addOperationPutAccountSettingMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*PutAccountSettingOutput) + out.ResultMetadata = metadata + return out, nil +} + +type PutAccountSettingInput struct { + + // The name of the account setting, such as BASIC_SCAN_TYPE_VERSION or + // REGISTRY_POLICY_SCOPE . + // + // This member is required. + Name *string + + // Setting value that is specified. The following are valid values for the basic + // scan type being used: AWS_NATIVE or CLAIR . The following are valid values for + // the registry policy scope being used: V1 or V2 . + // + // This member is required. + Value *string + + noSmithyDocumentSerde +} + +type PutAccountSettingOutput struct { + + // Retrieves the name of the account setting. + Name *string + + // Retrieves the value of the specified account setting. + Value *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationPutAccountSettingMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpPutAccountSetting{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpPutAccountSetting{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "PutAccountSetting"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addOpPutAccountSettingValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opPutAccountSetting(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opPutAccountSetting(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "PutAccountSetting", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutImage.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutImage.go index 104ac9d2e2..d63228f6d1 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutImage.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutImage.go @@ -4,24 +4,22 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) -// Creates or updates the image manifest and tags associated with an image. When -// an image is pushed and all new image layers have been uploaded, the PutImage API -// is called once to create or update the image manifest and the tags associated -// with the image. This operation is used by the Amazon ECR proxy and is not -// generally used by customers for pulling and pushing images. In most cases, you -// should use the docker CLI to pull, tag, and push images. +// Creates or updates the image manifest and tags associated with an image. +// +// When an image is pushed and all new image layers have been uploaded, the +// PutImage API is called once to create or update the image manifest and the tags +// associated with the image. +// +// This operation is used by the Amazon ECR proxy and is not generally used by +// customers for pulling and pushing images. In most cases, you should use the +// docker CLI to pull, tag, and push images. func (c *Client) PutImage(ctx context.Context, params *PutImageInput, optFns ...func(*Options)) (*PutImageOutput, error) { if params == nil { params = &PutImageInput{} @@ -82,6 +80,9 @@ type PutImageOutput struct { } func (c *Client) addOperationPutImageMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpPutImage{}, middleware.After) if err != nil { return err @@ -90,34 +91,38 @@ func (c *Client) addOperationPutImageMiddlewares(stack *middleware.Stack, option if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "PutImage"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -129,7 +134,13 @@ func (c *Client) addOperationPutImageMiddlewares(stack *middleware.Stack, option if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addPutImageResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpPutImageValidationMiddleware(stack); err != nil { @@ -138,7 +149,7 @@ func (c *Client) addOperationPutImageMiddlewares(stack *middleware.Stack, option if err = stack.Initialize.Add(newServiceMetadataMiddleware_opPutImage(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -150,7 +161,19 @@ func (c *Client) addOperationPutImageMiddlewares(stack *middleware.Stack, option if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -160,130 +183,6 @@ func newServiceMetadataMiddleware_opPutImage(region string) *awsmiddleware.Regis return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "PutImage", } } - -type opPutImageResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opPutImageResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opPutImageResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addPutImageResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opPutImageResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutImageScanningConfiguration.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutImageScanningConfiguration.go index cd0dd68d72..322c84dae0 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutImageScanningConfiguration.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutImageScanningConfiguration.go @@ -4,22 +4,18 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // The PutImageScanningConfiguration API is being deprecated, in favor of // specifying the image scanning configuration at the registry level. For more -// information, see PutRegistryScanningConfiguration . Updates the image scanning -// configuration for the specified repository. +// information, see PutRegistryScanningConfiguration. +// +// Updates the image scanning configuration for the specified repository. func (c *Client) PutImageScanningConfiguration(ctx context.Context, params *PutImageScanningConfigurationInput, optFns ...func(*Options)) (*PutImageScanningConfigurationOutput, error) { if params == nil { params = &PutImageScanningConfigurationInput{} @@ -76,6 +72,9 @@ type PutImageScanningConfigurationOutput struct { } func (c *Client) addOperationPutImageScanningConfigurationMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpPutImageScanningConfiguration{}, middleware.After) if err != nil { return err @@ -84,34 +83,38 @@ func (c *Client) addOperationPutImageScanningConfigurationMiddlewares(stack *mid if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "PutImageScanningConfiguration"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -123,7 +126,13 @@ func (c *Client) addOperationPutImageScanningConfigurationMiddlewares(stack *mid if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addPutImageScanningConfigurationResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpPutImageScanningConfigurationValidationMiddleware(stack); err != nil { @@ -132,7 +141,7 @@ func (c *Client) addOperationPutImageScanningConfigurationMiddlewares(stack *mid if err = stack.Initialize.Add(newServiceMetadataMiddleware_opPutImageScanningConfiguration(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -144,7 +153,19 @@ func (c *Client) addOperationPutImageScanningConfigurationMiddlewares(stack *mid if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -154,130 +175,6 @@ func newServiceMetadataMiddleware_opPutImageScanningConfiguration(region string) return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "PutImageScanningConfiguration", } } - -type opPutImageScanningConfigurationResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opPutImageScanningConfigurationResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opPutImageScanningConfigurationResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addPutImageScanningConfigurationResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opPutImageScanningConfigurationResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutImageTagMutability.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutImageTagMutability.go index 4e0ed7e179..e1b4c3c93e 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutImageTagMutability.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutImageTagMutability.go @@ -4,21 +4,17 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Updates the image tag mutability settings for the specified repository. For -// more information, see Image tag mutability (https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-tag-mutability.html) -// in the Amazon Elastic Container Registry User Guide. +// more information, see [Image tag mutability]in the Amazon Elastic Container Registry User Guide. +// +// [Image tag mutability]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-tag-mutability.html func (c *Client) PutImageTagMutability(ctx context.Context, params *PutImageTagMutabilityInput, optFns ...func(*Options)) (*PutImageTagMutabilityOutput, error) { if params == nil { params = &PutImageTagMutabilityInput{} @@ -74,6 +70,9 @@ type PutImageTagMutabilityOutput struct { } func (c *Client) addOperationPutImageTagMutabilityMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpPutImageTagMutability{}, middleware.After) if err != nil { return err @@ -82,34 +81,38 @@ func (c *Client) addOperationPutImageTagMutabilityMiddlewares(stack *middleware. if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "PutImageTagMutability"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -121,7 +124,13 @@ func (c *Client) addOperationPutImageTagMutabilityMiddlewares(stack *middleware. if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addPutImageTagMutabilityResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpPutImageTagMutabilityValidationMiddleware(stack); err != nil { @@ -130,7 +139,7 @@ func (c *Client) addOperationPutImageTagMutabilityMiddlewares(stack *middleware. if err = stack.Initialize.Add(newServiceMetadataMiddleware_opPutImageTagMutability(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -142,7 +151,19 @@ func (c *Client) addOperationPutImageTagMutabilityMiddlewares(stack *middleware. if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -152,130 +173,6 @@ func newServiceMetadataMiddleware_opPutImageTagMutability(region string) *awsmid return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "PutImageTagMutability", } } - -type opPutImageTagMutabilityResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opPutImageTagMutabilityResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opPutImageTagMutabilityResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addPutImageTagMutabilityResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opPutImageTagMutabilityResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutLifecyclePolicy.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutLifecyclePolicy.go index e1d71358d1..4e8121861b 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutLifecyclePolicy.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutLifecyclePolicy.go @@ -4,20 +4,16 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Creates or updates the lifecycle policy for the specified repository. For more -// information, see Lifecycle policy template (https://docs.aws.amazon.com/AmazonECR/latest/userguide/LifecyclePolicies.html) -// . +// information, see [Lifecycle policy template]. +// +// [Lifecycle policy template]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/LifecyclePolicies.html func (c *Client) PutLifecyclePolicy(ctx context.Context, params *PutLifecyclePolicyInput, optFns ...func(*Options)) (*PutLifecyclePolicyOutput, error) { if params == nil { params = &PutLifecyclePolicyInput{} @@ -71,6 +67,9 @@ type PutLifecyclePolicyOutput struct { } func (c *Client) addOperationPutLifecyclePolicyMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpPutLifecyclePolicy{}, middleware.After) if err != nil { return err @@ -79,34 +78,38 @@ func (c *Client) addOperationPutLifecyclePolicyMiddlewares(stack *middleware.Sta if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "PutLifecyclePolicy"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -118,7 +121,13 @@ func (c *Client) addOperationPutLifecyclePolicyMiddlewares(stack *middleware.Sta if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addPutLifecyclePolicyResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpPutLifecyclePolicyValidationMiddleware(stack); err != nil { @@ -127,7 +136,7 @@ func (c *Client) addOperationPutLifecyclePolicyMiddlewares(stack *middleware.Sta if err = stack.Initialize.Add(newServiceMetadataMiddleware_opPutLifecyclePolicy(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -139,7 +148,19 @@ func (c *Client) addOperationPutLifecyclePolicyMiddlewares(stack *middleware.Sta if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -149,130 +170,6 @@ func newServiceMetadataMiddleware_opPutLifecyclePolicy(region string) *awsmiddle return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "PutLifecyclePolicy", } } - -type opPutLifecyclePolicyResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opPutLifecyclePolicyResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opPutLifecyclePolicyResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addPutLifecyclePolicyResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opPutLifecyclePolicyResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutRegistryPolicy.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutRegistryPolicy.go index bbbba97642..c806dbf572 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutRegistryPolicy.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutRegistryPolicy.go @@ -4,22 +4,19 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) -// Creates or updates the permissions policy for your registry. A registry policy -// is used to specify permissions for another Amazon Web Services account and is -// used when configuring cross-account replication. For more information, see -// Registry permissions (https://docs.aws.amazon.com/AmazonECR/latest/userguide/registry-permissions.html) -// in the Amazon Elastic Container Registry User Guide. +// Creates or updates the permissions policy for your registry. +// +// A registry policy is used to specify permissions for another Amazon Web +// Services account and is used when configuring cross-account replication. For +// more information, see [Registry permissions]in the Amazon Elastic Container Registry User Guide. +// +// [Registry permissions]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/registry-permissions.html func (c *Client) PutRegistryPolicy(ctx context.Context, params *PutRegistryPolicyInput, optFns ...func(*Options)) (*PutRegistryPolicyOutput, error) { if params == nil { params = &PutRegistryPolicyInput{} @@ -38,8 +35,10 @@ func (c *Client) PutRegistryPolicy(ctx context.Context, params *PutRegistryPolic type PutRegistryPolicyInput struct { // The JSON policy text to apply to your registry. The policy text follows the - // same format as IAM policy text. For more information, see Registry permissions (https://docs.aws.amazon.com/AmazonECR/latest/userguide/registry-permissions.html) - // in the Amazon Elastic Container Registry User Guide. + // same format as IAM policy text. For more information, see [Registry permissions]in the Amazon Elastic + // Container Registry User Guide. + // + // [Registry permissions]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/registry-permissions.html // // This member is required. PolicyText *string @@ -52,7 +51,7 @@ type PutRegistryPolicyOutput struct { // The JSON policy text for your registry. PolicyText *string - // The registry ID. + // The registry ID associated with the request. RegistryId *string // Metadata pertaining to the operation's result. @@ -62,6 +61,9 @@ type PutRegistryPolicyOutput struct { } func (c *Client) addOperationPutRegistryPolicyMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpPutRegistryPolicy{}, middleware.After) if err != nil { return err @@ -70,34 +72,38 @@ func (c *Client) addOperationPutRegistryPolicyMiddlewares(stack *middleware.Stac if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "PutRegistryPolicy"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -109,7 +115,13 @@ func (c *Client) addOperationPutRegistryPolicyMiddlewares(stack *middleware.Stac if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addPutRegistryPolicyResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpPutRegistryPolicyValidationMiddleware(stack); err != nil { @@ -118,7 +130,7 @@ func (c *Client) addOperationPutRegistryPolicyMiddlewares(stack *middleware.Stac if err = stack.Initialize.Add(newServiceMetadataMiddleware_opPutRegistryPolicy(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -130,7 +142,19 @@ func (c *Client) addOperationPutRegistryPolicyMiddlewares(stack *middleware.Stac if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -140,130 +164,6 @@ func newServiceMetadataMiddleware_opPutRegistryPolicy(region string) *awsmiddlew return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "PutRegistryPolicy", } } - -type opPutRegistryPolicyResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opPutRegistryPolicyResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opPutRegistryPolicyResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addPutRegistryPolicyResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opPutRegistryPolicyResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutRegistryScanningConfiguration.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutRegistryScanningConfiguration.go index 7261c89af4..c57f87d7d5 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutRegistryScanningConfiguration.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutRegistryScanningConfiguration.go @@ -4,14 +4,9 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -39,15 +34,18 @@ type PutRegistryScanningConfigurationInput struct { // occur. Rules []types.RegistryScanningRule - // The scanning type to set for the registry. When a registry scanning - // configuration is not defined, by default the BASIC scan type is used. When - // basic scanning is used, you may specify filters to determine which individual - // repositories, or all repositories, are scanned when new images are pushed to - // those repositories. Alternatively, you can do manual scans of images with basic - // scanning. When the ENHANCED scan type is set, Amazon Inspector provides - // automated vulnerability scanning. You may choose between continuous scanning or - // scan on push and you may specify filters to determine which individual - // repositories, or all repositories, are scanned. + // The scanning type to set for the registry. + // + // When a registry scanning configuration is not defined, by default the BASIC + // scan type is used. When basic scanning is used, you may specify filters to + // determine which individual repositories, or all repositories, are scanned when + // new images are pushed to those repositories. Alternatively, you can do manual + // scans of images with basic scanning. + // + // When the ENHANCED scan type is set, Amazon Inspector provides automated + // vulnerability scanning. You may choose between continuous scanning or scan on + // push and you may specify filters to determine which individual repositories, or + // all repositories, are scanned. ScanType types.ScanType noSmithyDocumentSerde @@ -65,6 +63,9 @@ type PutRegistryScanningConfigurationOutput struct { } func (c *Client) addOperationPutRegistryScanningConfigurationMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpPutRegistryScanningConfiguration{}, middleware.After) if err != nil { return err @@ -73,34 +74,38 @@ func (c *Client) addOperationPutRegistryScanningConfigurationMiddlewares(stack * if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "PutRegistryScanningConfiguration"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -112,7 +117,13 @@ func (c *Client) addOperationPutRegistryScanningConfigurationMiddlewares(stack * if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addPutRegistryScanningConfigurationResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpPutRegistryScanningConfigurationValidationMiddleware(stack); err != nil { @@ -121,7 +132,7 @@ func (c *Client) addOperationPutRegistryScanningConfigurationMiddlewares(stack * if err = stack.Initialize.Add(newServiceMetadataMiddleware_opPutRegistryScanningConfiguration(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -133,7 +144,19 @@ func (c *Client) addOperationPutRegistryScanningConfigurationMiddlewares(stack * if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -143,130 +166,6 @@ func newServiceMetadataMiddleware_opPutRegistryScanningConfiguration(region stri return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "PutRegistryScanningConfiguration", } } - -type opPutRegistryScanningConfigurationResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opPutRegistryScanningConfigurationResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opPutRegistryScanningConfigurationResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addPutRegistryScanningConfigurationResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opPutRegistryScanningConfigurationResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutReplicationConfiguration.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutReplicationConfiguration.go index dc230e8127..24fd26d696 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutReplicationConfiguration.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_PutReplicationConfiguration.go @@ -4,28 +4,26 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Creates or updates the replication configuration for a registry. The existing -// replication configuration for a repository can be retrieved with the -// DescribeRegistry API action. The first time the PutReplicationConfiguration API -// is called, a service-linked IAM role is created in your account for the -// replication process. For more information, see Using service-linked roles for -// Amazon ECR (https://docs.aws.amazon.com/AmazonECR/latest/userguide/using-service-linked-roles.html) -// in the Amazon Elastic Container Registry User Guide. When configuring -// cross-account replication, the destination account must grant the source account -// permission to replicate. This permission is controlled using a registry -// permissions policy. For more information, see PutRegistryPolicy . +// replication configuration for a repository can be retrieved with the DescribeRegistryAPI +// action. The first time the PutReplicationConfiguration API is called, a +// service-linked IAM role is created in your account for the replication process. +// For more information, see [Using service-linked roles for Amazon ECR]in the Amazon Elastic Container Registry User Guide. +// For more information on the custom role for replication, see [Creating an IAM role for replication]. +// +// When configuring cross-account replication, the destination account must grant +// the source account permission to replicate. This permission is controlled using +// a registry permissions policy. For more information, see PutRegistryPolicy. +// +// [Creating an IAM role for replication]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/replication-creation-templates.html#roles-creatingrole-user-console +// [Using service-linked roles for Amazon ECR]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/using-service-linked-roles.html func (c *Client) PutReplicationConfiguration(ctx context.Context, params *PutReplicationConfigurationInput, optFns ...func(*Options)) (*PutReplicationConfigurationOutput, error) { if params == nil { params = &PutReplicationConfigurationInput{} @@ -63,6 +61,9 @@ type PutReplicationConfigurationOutput struct { } func (c *Client) addOperationPutReplicationConfigurationMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpPutReplicationConfiguration{}, middleware.After) if err != nil { return err @@ -71,34 +72,38 @@ func (c *Client) addOperationPutReplicationConfigurationMiddlewares(stack *middl if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "PutReplicationConfiguration"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -110,7 +115,13 @@ func (c *Client) addOperationPutReplicationConfigurationMiddlewares(stack *middl if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addPutReplicationConfigurationResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpPutReplicationConfigurationValidationMiddleware(stack); err != nil { @@ -119,7 +130,7 @@ func (c *Client) addOperationPutReplicationConfigurationMiddlewares(stack *middl if err = stack.Initialize.Add(newServiceMetadataMiddleware_opPutReplicationConfiguration(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -131,7 +142,19 @@ func (c *Client) addOperationPutReplicationConfigurationMiddlewares(stack *middl if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -141,130 +164,6 @@ func newServiceMetadataMiddleware_opPutReplicationConfiguration(region string) * return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "PutReplicationConfiguration", } } - -type opPutReplicationConfigurationResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opPutReplicationConfigurationResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opPutReplicationConfigurationResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addPutReplicationConfigurationResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opPutReplicationConfigurationResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_SetRepositoryPolicy.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_SetRepositoryPolicy.go index 209df6c2d6..36a788b70a 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_SetRepositoryPolicy.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_SetRepositoryPolicy.go @@ -4,20 +4,17 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Applies a repository policy to the specified repository to control access -// permissions. For more information, see Amazon ECR Repository policies (https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-policies.html) -// in the Amazon Elastic Container Registry User Guide. +// permissions. For more information, see [Amazon ECR Repository policies]in the Amazon Elastic Container Registry +// User Guide. +// +// [Amazon ECR Repository policies]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-policies.html func (c *Client) SetRepositoryPolicy(ctx context.Context, params *SetRepositoryPolicyInput, optFns ...func(*Options)) (*SetRepositoryPolicyOutput, error) { if params == nil { params = &SetRepositoryPolicyInput{} @@ -36,8 +33,9 @@ func (c *Client) SetRepositoryPolicy(ctx context.Context, params *SetRepositoryP type SetRepositoryPolicyInput struct { // The JSON repository policy text to apply to the repository. For more - // information, see Amazon ECR repository policies (https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-policy-examples.html) - // in the Amazon Elastic Container Registry User Guide. + // information, see [Amazon ECR repository policies]in the Amazon Elastic Container Registry User Guide. + // + // [Amazon ECR repository policies]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-policy-examples.html // // This member is required. PolicyText *string @@ -48,9 +46,8 @@ type SetRepositoryPolicyInput struct { RepositoryName *string // If the policy you are attempting to set on a repository policy would prevent - // you from setting another policy in the future, you must force the - // SetRepositoryPolicy operation. This is intended to prevent accidental repository - // lock outs. + // you from setting another policy in the future, you must force the SetRepositoryPolicyoperation. + // This is intended to prevent accidental repository lock outs. Force bool // The Amazon Web Services account ID associated with the registry that contains @@ -79,6 +76,9 @@ type SetRepositoryPolicyOutput struct { } func (c *Client) addOperationSetRepositoryPolicyMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpSetRepositoryPolicy{}, middleware.After) if err != nil { return err @@ -87,34 +87,38 @@ func (c *Client) addOperationSetRepositoryPolicyMiddlewares(stack *middleware.St if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "SetRepositoryPolicy"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -126,7 +130,13 @@ func (c *Client) addOperationSetRepositoryPolicyMiddlewares(stack *middleware.St if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addSetRepositoryPolicyResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpSetRepositoryPolicyValidationMiddleware(stack); err != nil { @@ -135,7 +145,7 @@ func (c *Client) addOperationSetRepositoryPolicyMiddlewares(stack *middleware.St if err = stack.Initialize.Add(newServiceMetadataMiddleware_opSetRepositoryPolicy(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -147,7 +157,19 @@ func (c *Client) addOperationSetRepositoryPolicyMiddlewares(stack *middleware.St if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -157,130 +179,6 @@ func newServiceMetadataMiddleware_opSetRepositoryPolicy(region string) *awsmiddl return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "SetRepositoryPolicy", } } - -type opSetRepositoryPolicyResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opSetRepositoryPolicyResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opSetRepositoryPolicyResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addSetRepositoryPolicyResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opSetRepositoryPolicyResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_StartImageScan.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_StartImageScan.go index b1dc74c730..1f3e794e84 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_StartImageScan.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_StartImageScan.go @@ -4,22 +4,19 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Starts an image vulnerability scan. An image scan can only be started once per // 24 hours on an individual image. This limit includes if an image was scanned on -// initial push. For more information, see Image scanning (https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-scanning.html) -// in the Amazon Elastic Container Registry User Guide. +// initial push. For more information, see [Image scanning]in the Amazon Elastic Container +// Registry User Guide. +// +// [Image scanning]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-scanning.html func (c *Client) StartImageScan(ctx context.Context, params *StartImageScanInput, optFns ...func(*Options)) (*StartImageScanOutput, error) { if params == nil { params = &StartImageScanInput{} @@ -76,6 +73,9 @@ type StartImageScanOutput struct { } func (c *Client) addOperationStartImageScanMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpStartImageScan{}, middleware.After) if err != nil { return err @@ -84,34 +84,38 @@ func (c *Client) addOperationStartImageScanMiddlewares(stack *middleware.Stack, if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "StartImageScan"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -123,7 +127,13 @@ func (c *Client) addOperationStartImageScanMiddlewares(stack *middleware.Stack, if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addStartImageScanResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpStartImageScanValidationMiddleware(stack); err != nil { @@ -132,7 +142,7 @@ func (c *Client) addOperationStartImageScanMiddlewares(stack *middleware.Stack, if err = stack.Initialize.Add(newServiceMetadataMiddleware_opStartImageScan(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -144,7 +154,19 @@ func (c *Client) addOperationStartImageScanMiddlewares(stack *middleware.Stack, if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -154,130 +176,6 @@ func newServiceMetadataMiddleware_opStartImageScan(region string) *awsmiddleware return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "StartImageScan", } } - -type opStartImageScanResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opStartImageScanResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opStartImageScanResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addStartImageScanResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opStartImageScanResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_StartLifecyclePolicyPreview.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_StartLifecyclePolicyPreview.go index 753970eae0..a2b2bb1b44 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_StartLifecyclePolicyPreview.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_StartLifecyclePolicyPreview.go @@ -4,14 +4,9 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -74,6 +69,9 @@ type StartLifecyclePolicyPreviewOutput struct { } func (c *Client) addOperationStartLifecyclePolicyPreviewMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpStartLifecyclePolicyPreview{}, middleware.After) if err != nil { return err @@ -82,34 +80,38 @@ func (c *Client) addOperationStartLifecyclePolicyPreviewMiddlewares(stack *middl if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "StartLifecyclePolicyPreview"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -121,7 +123,13 @@ func (c *Client) addOperationStartLifecyclePolicyPreviewMiddlewares(stack *middl if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addStartLifecyclePolicyPreviewResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpStartLifecyclePolicyPreviewValidationMiddleware(stack); err != nil { @@ -130,7 +138,7 @@ func (c *Client) addOperationStartLifecyclePolicyPreviewMiddlewares(stack *middl if err = stack.Initialize.Add(newServiceMetadataMiddleware_opStartLifecyclePolicyPreview(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -142,7 +150,19 @@ func (c *Client) addOperationStartLifecyclePolicyPreviewMiddlewares(stack *middl if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -152,130 +172,6 @@ func newServiceMetadataMiddleware_opStartLifecyclePolicyPreview(region string) * return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "StartLifecyclePolicyPreview", } } - -type opStartLifecyclePolicyPreviewResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opStartLifecyclePolicyPreviewResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opStartLifecyclePolicyPreviewResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addStartLifecyclePolicyPreviewResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opStartLifecyclePolicyPreviewResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_TagResource.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_TagResource.go index cee2132685..3974ab0268 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_TagResource.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_TagResource.go @@ -4,14 +4,9 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecr/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -59,6 +54,9 @@ type TagResourceOutput struct { } func (c *Client) addOperationTagResourceMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpTagResource{}, middleware.After) if err != nil { return err @@ -67,34 +65,38 @@ func (c *Client) addOperationTagResourceMiddlewares(stack *middleware.Stack, opt if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "TagResource"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -106,7 +108,13 @@ func (c *Client) addOperationTagResourceMiddlewares(stack *middleware.Stack, opt if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addTagResourceResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpTagResourceValidationMiddleware(stack); err != nil { @@ -115,7 +123,7 @@ func (c *Client) addOperationTagResourceMiddlewares(stack *middleware.Stack, opt if err = stack.Initialize.Add(newServiceMetadataMiddleware_opTagResource(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -127,7 +135,19 @@ func (c *Client) addOperationTagResourceMiddlewares(stack *middleware.Stack, opt if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -137,130 +157,6 @@ func newServiceMetadataMiddleware_opTagResource(region string) *awsmiddleware.Re return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "TagResource", } } - -type opTagResourceResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opTagResourceResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opTagResourceResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addTagResourceResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opTagResourceResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_UntagResource.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_UntagResource.go index 74f12ad403..e28d0d0182 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_UntagResource.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_UntagResource.go @@ -4,13 +4,8 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -55,6 +50,9 @@ type UntagResourceOutput struct { } func (c *Client) addOperationUntagResourceMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpUntagResource{}, middleware.After) if err != nil { return err @@ -63,34 +61,38 @@ func (c *Client) addOperationUntagResourceMiddlewares(stack *middleware.Stack, o if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "UntagResource"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -102,7 +104,13 @@ func (c *Client) addOperationUntagResourceMiddlewares(stack *middleware.Stack, o if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addUntagResourceResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpUntagResourceValidationMiddleware(stack); err != nil { @@ -111,7 +119,7 @@ func (c *Client) addOperationUntagResourceMiddlewares(stack *middleware.Stack, o if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUntagResource(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -123,7 +131,19 @@ func (c *Client) addOperationUntagResourceMiddlewares(stack *middleware.Stack, o if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -133,130 +153,6 @@ func newServiceMetadataMiddleware_opUntagResource(region string) *awsmiddleware. return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "UntagResource", } } - -type opUntagResourceResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opUntagResourceResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opUntagResourceResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addUntagResourceResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opUntagResourceResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_UpdatePullThroughCacheRule.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_UpdatePullThroughCacheRule.go new file mode 100644 index 0000000000..d40712e4f6 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_UpdatePullThroughCacheRule.go @@ -0,0 +1,179 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package ecr + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" + "time" +) + +// Updates an existing pull through cache rule. +func (c *Client) UpdatePullThroughCacheRule(ctx context.Context, params *UpdatePullThroughCacheRuleInput, optFns ...func(*Options)) (*UpdatePullThroughCacheRuleOutput, error) { + if params == nil { + params = &UpdatePullThroughCacheRuleInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "UpdatePullThroughCacheRule", params, optFns, c.addOperationUpdatePullThroughCacheRuleMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*UpdatePullThroughCacheRuleOutput) + out.ResultMetadata = metadata + return out, nil +} + +type UpdatePullThroughCacheRuleInput struct { + + // The Amazon Resource Name (ARN) of the Amazon Web Services Secrets Manager + // secret that identifies the credentials to authenticate to the upstream registry. + // + // This member is required. + CredentialArn *string + + // The repository name prefix to use when caching images from the source registry. + // + // This member is required. + EcrRepositoryPrefix *string + + // The Amazon Web Services account ID associated with the registry associated with + // the pull through cache rule. If you do not specify a registry, the default + // registry is assumed. + RegistryId *string + + noSmithyDocumentSerde +} + +type UpdatePullThroughCacheRuleOutput struct { + + // The Amazon Resource Name (ARN) of the Amazon Web Services Secrets Manager + // secret associated with the pull through cache rule. + CredentialArn *string + + // The Amazon ECR repository prefix associated with the pull through cache rule. + EcrRepositoryPrefix *string + + // The registry ID associated with the request. + RegistryId *string + + // The date and time, in JavaScript date format, when the pull through cache rule + // was updated. + UpdatedAt *time.Time + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationUpdatePullThroughCacheRuleMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdatePullThroughCacheRule{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdatePullThroughCacheRule{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "UpdatePullThroughCacheRule"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addOpUpdatePullThroughCacheRuleValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdatePullThroughCacheRule(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opUpdatePullThroughCacheRule(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "UpdatePullThroughCacheRule", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_UpdateRepositoryCreationTemplate.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_UpdateRepositoryCreationTemplate.go new file mode 100644 index 0000000000..1371216054 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_UpdateRepositoryCreationTemplate.go @@ -0,0 +1,206 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package ecr + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/ecr/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Updates an existing repository creation template. +func (c *Client) UpdateRepositoryCreationTemplate(ctx context.Context, params *UpdateRepositoryCreationTemplateInput, optFns ...func(*Options)) (*UpdateRepositoryCreationTemplateOutput, error) { + if params == nil { + params = &UpdateRepositoryCreationTemplateInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "UpdateRepositoryCreationTemplate", params, optFns, c.addOperationUpdateRepositoryCreationTemplateMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*UpdateRepositoryCreationTemplateOutput) + out.ResultMetadata = metadata + return out, nil +} + +type UpdateRepositoryCreationTemplateInput struct { + + // The repository namespace prefix that matches an existing repository creation + // template in the registry. All repositories created using this namespace prefix + // will have the settings defined in this template applied. For example, a prefix + // of prod would apply to all repositories beginning with prod/ . This includes a + // repository named prod/team1 as well as a repository named prod/repository1 . + // + // To apply a template to all repositories in your registry that don't have an + // associated creation template, you can use ROOT as the prefix. + // + // This member is required. + Prefix *string + + // Updates the list of enumerable strings representing the Amazon ECR repository + // creation scenarios that this template will apply towards. The two supported + // scenarios are PULL_THROUGH_CACHE and REPLICATION + AppliedFor []types.RCTAppliedFor + + // The ARN of the role to be assumed by Amazon ECR. This role must be in the same + // account as the registry that you are configuring. Amazon ECR will assume your + // supplied role when the customRoleArn is specified. When this field isn't + // specified, Amazon ECR will use the service-linked role for the repository + // creation template. + CustomRoleArn *string + + // A description for the repository creation template. + Description *string + + // The encryption configuration to associate with the repository creation template. + EncryptionConfiguration *types.EncryptionConfigurationForRepositoryCreationTemplate + + // Updates the tag mutability setting for the repository. If this parameter is + // omitted, the default setting of MUTABLE will be used which will allow image + // tags to be overwritten. If IMMUTABLE is specified, all image tags within the + // repository will be immutable which will prevent them from being overwritten. + ImageTagMutability types.ImageTagMutability + + // Updates the lifecycle policy associated with the specified repository creation + // template. + LifecyclePolicy *string + + // Updates the repository policy created using the template. A repository policy + // is a permissions policy associated with a repository to control access + // permissions. + RepositoryPolicy *string + + // The metadata to apply to the repository to help you categorize and organize. + // Each tag consists of a key and an optional value, both of which you define. Tag + // keys can have a maximum character length of 128 characters, and tag values can + // have a maximum length of 256 characters. + ResourceTags []types.Tag + + noSmithyDocumentSerde +} + +type UpdateRepositoryCreationTemplateOutput struct { + + // The registry ID associated with the request. + RegistryId *string + + // The details of the repository creation template associated with the request. + RepositoryCreationTemplate *types.RepositoryCreationTemplate + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationUpdateRepositoryCreationTemplateMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateRepositoryCreationTemplate{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateRepositoryCreationTemplate{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateRepositoryCreationTemplate"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addOpUpdateRepositoryCreationTemplateValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateRepositoryCreationTemplate(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opUpdateRepositoryCreationTemplate(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "UpdateRepositoryCreationTemplate", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_UploadLayerPart.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_UploadLayerPart.go index feb56bf09c..acfbd50e25 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_UploadLayerPart.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_UploadLayerPart.go @@ -4,23 +4,21 @@ package ecr import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) -// Uploads an image layer part to Amazon ECR. When an image is pushed, each new -// image layer is uploaded in parts. The maximum size of each image layer part can -// be 20971520 bytes (or about 20MB). The UploadLayerPart API is called once per -// each new image layer part. This operation is used by the Amazon ECR proxy and is -// not generally used by customers for pulling and pushing images. In most cases, -// you should use the docker CLI to pull, tag, and push images. +// Uploads an image layer part to Amazon ECR. +// +// When an image is pushed, each new image layer is uploaded in parts. The maximum +// size of each image layer part can be 20971520 bytes (or about 20MB). The +// UploadLayerPart API is called once per each new image layer part. +// +// This operation is used by the Amazon ECR proxy and is not generally used by +// customers for pulling and pushing images. In most cases, you should use the +// docker CLI to pull, tag, and push images. func (c *Client) UploadLayerPart(ctx context.Context, params *UploadLayerPartInput, optFns ...func(*Options)) (*UploadLayerPartOutput, error) { if params == nil { params = &UploadLayerPartInput{} @@ -58,8 +56,8 @@ type UploadLayerPartInput struct { // This member is required. RepositoryName *string - // The upload ID from a previous InitiateLayerUpload operation to associate with - // the layer part upload. + // The upload ID from a previous InitiateLayerUpload operation to associate with the layer part + // upload. // // This member is required. UploadId *string @@ -93,6 +91,9 @@ type UploadLayerPartOutput struct { } func (c *Client) addOperationUploadLayerPartMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpUploadLayerPart{}, middleware.After) if err != nil { return err @@ -101,34 +102,38 @@ func (c *Client) addOperationUploadLayerPartMiddlewares(stack *middleware.Stack, if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "UploadLayerPart"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -140,7 +145,13 @@ func (c *Client) addOperationUploadLayerPartMiddlewares(stack *middleware.Stack, if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addUploadLayerPartResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpUploadLayerPartValidationMiddleware(stack); err != nil { @@ -149,7 +160,7 @@ func (c *Client) addOperationUploadLayerPartMiddlewares(stack *middleware.Stack, if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUploadLayerPart(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -161,7 +172,19 @@ func (c *Client) addOperationUploadLayerPartMiddlewares(stack *middleware.Stack, if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -171,130 +194,6 @@ func newServiceMetadataMiddleware_opUploadLayerPart(region string) *awsmiddlewar return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr", OperationName: "UploadLayerPart", } } - -type opUploadLayerPartResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opUploadLayerPartResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opUploadLayerPartResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addUploadLayerPartResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opUploadLayerPartResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_ValidatePullThroughCacheRule.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_ValidatePullThroughCacheRule.go new file mode 100644 index 0000000000..34eeb8959c --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/api_op_ValidatePullThroughCacheRule.go @@ -0,0 +1,185 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package ecr + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Validates an existing pull through cache rule for an upstream registry that +// requires authentication. This will retrieve the contents of the Amazon Web +// Services Secrets Manager secret, verify the syntax, and then validate that +// authentication to the upstream registry is successful. +func (c *Client) ValidatePullThroughCacheRule(ctx context.Context, params *ValidatePullThroughCacheRuleInput, optFns ...func(*Options)) (*ValidatePullThroughCacheRuleOutput, error) { + if params == nil { + params = &ValidatePullThroughCacheRuleInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ValidatePullThroughCacheRule", params, optFns, c.addOperationValidatePullThroughCacheRuleMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ValidatePullThroughCacheRuleOutput) + out.ResultMetadata = metadata + return out, nil +} + +type ValidatePullThroughCacheRuleInput struct { + + // The repository name prefix associated with the pull through cache rule. + // + // This member is required. + EcrRepositoryPrefix *string + + // The registry ID associated with the pull through cache rule. If you do not + // specify a registry, the default registry is assumed. + RegistryId *string + + noSmithyDocumentSerde +} + +type ValidatePullThroughCacheRuleOutput struct { + + // The Amazon Resource Name (ARN) of the Amazon Web Services Secrets Manager + // secret associated with the pull through cache rule. + CredentialArn *string + + // The Amazon ECR repository prefix associated with the pull through cache rule. + EcrRepositoryPrefix *string + + // The reason the validation failed. For more details about possible causes and + // how to address them, see [Using pull through cache rules]in the Amazon Elastic Container Registry User Guide. + // + // [Using pull through cache rules]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/pull-through-cache.html + Failure *string + + // Whether or not the pull through cache rule was validated. If true , Amazon ECR + // was able to reach the upstream registry and authentication was successful. If + // false , there was an issue and validation failed. The failure reason indicates + // the cause. + IsValid bool + + // The registry ID associated with the request. + RegistryId *string + + // The upstream registry URL associated with the pull through cache rule. + UpstreamRegistryUrl *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationValidatePullThroughCacheRuleMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpValidatePullThroughCacheRule{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpValidatePullThroughCacheRule{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ValidatePullThroughCacheRule"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addOpValidatePullThroughCacheRuleValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opValidatePullThroughCacheRule(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opValidatePullThroughCacheRule(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ValidatePullThroughCacheRule", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/auth.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/auth.go new file mode 100644 index 0000000000..a542aa8f1a --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/auth.go @@ -0,0 +1,313 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package ecr + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + smithy "github.com/aws/smithy-go" + smithyauth "github.com/aws/smithy-go/auth" + "github.com/aws/smithy-go/metrics" + "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +func bindAuthParamsRegion(_ interface{}, params *AuthResolverParameters, _ interface{}, options Options) { + params.Region = options.Region +} + +type setLegacyContextSigningOptionsMiddleware struct { +} + +func (*setLegacyContextSigningOptionsMiddleware) ID() string { + return "setLegacyContextSigningOptions" +} + +func (m *setLegacyContextSigningOptionsMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + rscheme := getResolvedAuthScheme(ctx) + schemeID := rscheme.Scheme.SchemeID() + + if sn := awsmiddleware.GetSigningName(ctx); sn != "" { + if schemeID == "aws.auth#sigv4" { + smithyhttp.SetSigV4SigningName(&rscheme.SignerProperties, sn) + } else if schemeID == "aws.auth#sigv4a" { + smithyhttp.SetSigV4ASigningName(&rscheme.SignerProperties, sn) + } + } + + if sr := awsmiddleware.GetSigningRegion(ctx); sr != "" { + if schemeID == "aws.auth#sigv4" { + smithyhttp.SetSigV4SigningRegion(&rscheme.SignerProperties, sr) + } else if schemeID == "aws.auth#sigv4a" { + smithyhttp.SetSigV4ASigningRegions(&rscheme.SignerProperties, []string{sr}) + } + } + + return next.HandleFinalize(ctx, in) +} + +func addSetLegacyContextSigningOptionsMiddleware(stack *middleware.Stack) error { + return stack.Finalize.Insert(&setLegacyContextSigningOptionsMiddleware{}, "Signing", middleware.Before) +} + +type withAnonymous struct { + resolver AuthSchemeResolver +} + +var _ AuthSchemeResolver = (*withAnonymous)(nil) + +func (v *withAnonymous) ResolveAuthSchemes(ctx context.Context, params *AuthResolverParameters) ([]*smithyauth.Option, error) { + opts, err := v.resolver.ResolveAuthSchemes(ctx, params) + if err != nil { + return nil, err + } + + opts = append(opts, &smithyauth.Option{ + SchemeID: smithyauth.SchemeIDAnonymous, + }) + return opts, nil +} + +func wrapWithAnonymousAuth(options *Options) { + if _, ok := options.AuthSchemeResolver.(*defaultAuthSchemeResolver); !ok { + return + } + + options.AuthSchemeResolver = &withAnonymous{ + resolver: options.AuthSchemeResolver, + } +} + +// AuthResolverParameters contains the set of inputs necessary for auth scheme +// resolution. +type AuthResolverParameters struct { + // The name of the operation being invoked. + Operation string + + // The region in which the operation is being invoked. + Region string +} + +func bindAuthResolverParams(ctx context.Context, operation string, input interface{}, options Options) *AuthResolverParameters { + params := &AuthResolverParameters{ + Operation: operation, + } + + bindAuthParamsRegion(ctx, params, input, options) + + return params +} + +// AuthSchemeResolver returns a set of possible authentication options for an +// operation. +type AuthSchemeResolver interface { + ResolveAuthSchemes(context.Context, *AuthResolverParameters) ([]*smithyauth.Option, error) +} + +type defaultAuthSchemeResolver struct{} + +var _ AuthSchemeResolver = (*defaultAuthSchemeResolver)(nil) + +func (*defaultAuthSchemeResolver) ResolveAuthSchemes(ctx context.Context, params *AuthResolverParameters) ([]*smithyauth.Option, error) { + if overrides, ok := operationAuthOptions[params.Operation]; ok { + return overrides(params), nil + } + return serviceAuthOptions(params), nil +} + +var operationAuthOptions = map[string]func(*AuthResolverParameters) []*smithyauth.Option{} + +func serviceAuthOptions(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + { + SchemeID: smithyauth.SchemeIDSigV4, + SignerProperties: func() smithy.Properties { + var props smithy.Properties + smithyhttp.SetSigV4SigningName(&props, "ecr") + smithyhttp.SetSigV4SigningRegion(&props, params.Region) + return props + }(), + }, + } +} + +type resolveAuthSchemeMiddleware struct { + operation string + options Options +} + +func (*resolveAuthSchemeMiddleware) ID() string { + return "ResolveAuthScheme" +} + +func (m *resolveAuthSchemeMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "ResolveAuthScheme") + defer span.End() + + params := bindAuthResolverParams(ctx, m.operation, getOperationInput(ctx), m.options) + options, err := m.options.AuthSchemeResolver.ResolveAuthSchemes(ctx, params) + if err != nil { + return out, metadata, fmt.Errorf("resolve auth scheme: %w", err) + } + + scheme, ok := m.selectScheme(options) + if !ok { + return out, metadata, fmt.Errorf("could not select an auth scheme") + } + + ctx = setResolvedAuthScheme(ctx, scheme) + + span.SetProperty("auth.scheme_id", scheme.Scheme.SchemeID()) + span.End() + return next.HandleFinalize(ctx, in) +} + +func (m *resolveAuthSchemeMiddleware) selectScheme(options []*smithyauth.Option) (*resolvedAuthScheme, bool) { + for _, option := range options { + if option.SchemeID == smithyauth.SchemeIDAnonymous { + return newResolvedAuthScheme(smithyhttp.NewAnonymousScheme(), option), true + } + + for _, scheme := range m.options.AuthSchemes { + if scheme.SchemeID() != option.SchemeID { + continue + } + + if scheme.IdentityResolver(m.options) != nil { + return newResolvedAuthScheme(scheme, option), true + } + } + } + + return nil, false +} + +type resolvedAuthSchemeKey struct{} + +type resolvedAuthScheme struct { + Scheme smithyhttp.AuthScheme + IdentityProperties smithy.Properties + SignerProperties smithy.Properties +} + +func newResolvedAuthScheme(scheme smithyhttp.AuthScheme, option *smithyauth.Option) *resolvedAuthScheme { + return &resolvedAuthScheme{ + Scheme: scheme, + IdentityProperties: option.IdentityProperties, + SignerProperties: option.SignerProperties, + } +} + +func setResolvedAuthScheme(ctx context.Context, scheme *resolvedAuthScheme) context.Context { + return middleware.WithStackValue(ctx, resolvedAuthSchemeKey{}, scheme) +} + +func getResolvedAuthScheme(ctx context.Context) *resolvedAuthScheme { + v, _ := middleware.GetStackValue(ctx, resolvedAuthSchemeKey{}).(*resolvedAuthScheme) + return v +} + +type getIdentityMiddleware struct { + options Options +} + +func (*getIdentityMiddleware) ID() string { + return "GetIdentity" +} + +func (m *getIdentityMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + innerCtx, span := tracing.StartSpan(ctx, "GetIdentity") + defer span.End() + + rscheme := getResolvedAuthScheme(innerCtx) + if rscheme == nil { + return out, metadata, fmt.Errorf("no resolved auth scheme") + } + + resolver := rscheme.Scheme.IdentityResolver(m.options) + if resolver == nil { + return out, metadata, fmt.Errorf("no identity resolver") + } + + identity, err := timeOperationMetric(ctx, "client.call.resolve_identity_duration", + func() (smithyauth.Identity, error) { + return resolver.GetIdentity(innerCtx, rscheme.IdentityProperties) + }, + func(o *metrics.RecordMetricOptions) { + o.Properties.Set("auth.scheme_id", rscheme.Scheme.SchemeID()) + }) + if err != nil { + return out, metadata, fmt.Errorf("get identity: %w", err) + } + + ctx = setIdentity(ctx, identity) + + span.End() + return next.HandleFinalize(ctx, in) +} + +type identityKey struct{} + +func setIdentity(ctx context.Context, identity smithyauth.Identity) context.Context { + return middleware.WithStackValue(ctx, identityKey{}, identity) +} + +func getIdentity(ctx context.Context) smithyauth.Identity { + v, _ := middleware.GetStackValue(ctx, identityKey{}).(smithyauth.Identity) + return v +} + +type signRequestMiddleware struct { + options Options +} + +func (*signRequestMiddleware) ID() string { + return "Signing" +} + +func (m *signRequestMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "SignRequest") + defer span.End() + + req, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, fmt.Errorf("unexpected transport type %T", in.Request) + } + + rscheme := getResolvedAuthScheme(ctx) + if rscheme == nil { + return out, metadata, fmt.Errorf("no resolved auth scheme") + } + + identity := getIdentity(ctx) + if identity == nil { + return out, metadata, fmt.Errorf("no identity") + } + + signer := rscheme.Scheme.Signer() + if signer == nil { + return out, metadata, fmt.Errorf("no signer") + } + + _, err = timeOperationMetric(ctx, "client.call.signing_duration", func() (any, error) { + return nil, signer.SignRequest(ctx, req, identity, rscheme.SignerProperties) + }, func(o *metrics.RecordMetricOptions) { + o.Properties.Set("auth.scheme_id", rscheme.Scheme.SchemeID()) + }) + if err != nil { + return out, metadata, fmt.Errorf("sign request: %w", err) + } + + span.End() + return next.HandleFinalize(ctx, in) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/deserializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/deserializers.go index 7d849ef541..ac5093fcdb 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/deserializers.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/deserializers.go @@ -14,12 +14,22 @@ import ( "github.com/aws/smithy-go/middleware" "github.com/aws/smithy-go/ptr" smithytime "github.com/aws/smithy-go/time" + "github.com/aws/smithy-go/tracing" smithyhttp "github.com/aws/smithy-go/transport/http" "io" "math" "strings" + "time" ) +func deserializeS3Expires(v string) (*time.Time, error) { + t, err := smithytime.ParseHTTPDate(v) + if err != nil { + return nil, nil + } + return &t, nil +} + type awsAwsjson11_deserializeOpBatchCheckLayerAvailability struct { } @@ -35,6 +45,10 @@ func (m *awsAwsjson11_deserializeOpBatchCheckLayerAvailability) HandleDeserializ return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -88,9 +102,6 @@ func awsAwsjson11_deserializeOpErrorBatchCheckLayerAvailability(response *smithy errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -98,7 +109,7 @@ func awsAwsjson11_deserializeOpErrorBatchCheckLayerAvailability(response *smithy body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -110,13 +121,12 @@ func awsAwsjson11_deserializeOpErrorBatchCheckLayerAvailability(response *smithy } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -152,6 +162,10 @@ func (m *awsAwsjson11_deserializeOpBatchDeleteImage) HandleDeserialize(ctx conte return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -205,9 +219,6 @@ func awsAwsjson11_deserializeOpErrorBatchDeleteImage(response *smithyhttp.Respon errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -215,7 +226,7 @@ func awsAwsjson11_deserializeOpErrorBatchDeleteImage(response *smithyhttp.Respon body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -227,13 +238,12 @@ func awsAwsjson11_deserializeOpErrorBatchDeleteImage(response *smithyhttp.Respon } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -269,6 +279,10 @@ func (m *awsAwsjson11_deserializeOpBatchGetImage) HandleDeserialize(ctx context. return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -322,9 +336,6 @@ func awsAwsjson11_deserializeOpErrorBatchGetImage(response *smithyhttp.Response, errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -332,7 +343,7 @@ func awsAwsjson11_deserializeOpErrorBatchGetImage(response *smithyhttp.Response, body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -344,23 +355,28 @@ func awsAwsjson11_deserializeOpErrorBatchGetImage(response *smithyhttp.Response, } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + case strings.EqualFold("RepositoryNotFoundException", errorCode): return awsAwsjson11_deserializeErrorRepositoryNotFoundException(response, errorBody) case strings.EqualFold("ServerException", errorCode): return awsAwsjson11_deserializeErrorServerException(response, errorBody) + case strings.EqualFold("UnableToGetUpstreamImageException", errorCode): + return awsAwsjson11_deserializeErrorUnableToGetUpstreamImageException(response, errorBody) + default: genericError := &smithy.GenericAPIError{ Code: errorCode, @@ -386,6 +402,10 @@ func (m *awsAwsjson11_deserializeOpBatchGetRepositoryScanningConfiguration) Hand return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -439,9 +459,6 @@ func awsAwsjson11_deserializeOpErrorBatchGetRepositoryScanningConfiguration(resp errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -449,7 +466,7 @@ func awsAwsjson11_deserializeOpErrorBatchGetRepositoryScanningConfiguration(resp body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -461,13 +478,12 @@ func awsAwsjson11_deserializeOpErrorBatchGetRepositoryScanningConfiguration(resp } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -506,6 +522,10 @@ func (m *awsAwsjson11_deserializeOpCompleteLayerUpload) HandleDeserialize(ctx co return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -559,9 +579,6 @@ func awsAwsjson11_deserializeOpErrorCompleteLayerUpload(response *smithyhttp.Res errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -569,7 +586,7 @@ func awsAwsjson11_deserializeOpErrorCompleteLayerUpload(response *smithyhttp.Res body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -581,13 +598,12 @@ func awsAwsjson11_deserializeOpErrorCompleteLayerUpload(response *smithyhttp.Res } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("EmptyUploadException", errorCode): return awsAwsjson11_deserializeErrorEmptyUploadException(response, errorBody) @@ -641,6 +657,10 @@ func (m *awsAwsjson11_deserializeOpCreatePullThroughCacheRule) HandleDeserialize return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -694,9 +714,6 @@ func awsAwsjson11_deserializeOpErrorCreatePullThroughCacheRule(response *smithyh errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -704,7 +721,7 @@ func awsAwsjson11_deserializeOpErrorCreatePullThroughCacheRule(response *smithyh body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -716,13 +733,12 @@ func awsAwsjson11_deserializeOpErrorCreatePullThroughCacheRule(response *smithyh } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -733,9 +749,18 @@ func awsAwsjson11_deserializeOpErrorCreatePullThroughCacheRule(response *smithyh case strings.EqualFold("PullThroughCacheRuleAlreadyExistsException", errorCode): return awsAwsjson11_deserializeErrorPullThroughCacheRuleAlreadyExistsException(response, errorBody) + case strings.EqualFold("SecretNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorSecretNotFoundException(response, errorBody) + case strings.EqualFold("ServerException", errorCode): return awsAwsjson11_deserializeErrorServerException(response, errorBody) + case strings.EqualFold("UnableToAccessSecretException", errorCode): + return awsAwsjson11_deserializeErrorUnableToAccessSecretException(response, errorBody) + + case strings.EqualFold("UnableToDecryptSecretValueException", errorCode): + return awsAwsjson11_deserializeErrorUnableToDecryptSecretValueException(response, errorBody) + case strings.EqualFold("UnsupportedUpstreamRegistryException", errorCode): return awsAwsjson11_deserializeErrorUnsupportedUpstreamRegistryException(response, errorBody) @@ -767,6 +792,10 @@ func (m *awsAwsjson11_deserializeOpCreateRepository) HandleDeserialize(ctx conte return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -820,9 +849,6 @@ func awsAwsjson11_deserializeOpErrorCreateRepository(response *smithyhttp.Respon errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -830,7 +856,7 @@ func awsAwsjson11_deserializeOpErrorCreateRepository(response *smithyhttp.Respon body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -842,13 +868,12 @@ func awsAwsjson11_deserializeOpErrorCreateRepository(response *smithyhttp.Respon } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -881,6 +906,129 @@ func awsAwsjson11_deserializeOpErrorCreateRepository(response *smithyhttp.Respon } } +type awsAwsjson11_deserializeOpCreateRepositoryCreationTemplate struct { +} + +func (*awsAwsjson11_deserializeOpCreateRepositoryCreationTemplate) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpCreateRepositoryCreationTemplate) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorCreateRepositoryCreationTemplate(response, &metadata) + } + output := &CreateRepositoryCreationTemplateOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentCreateRepositoryCreationTemplateOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorCreateRepositoryCreationTemplate(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("ServerException", errorCode): + return awsAwsjson11_deserializeErrorServerException(response, errorBody) + + case strings.EqualFold("TemplateAlreadyExistsException", errorCode): + return awsAwsjson11_deserializeErrorTemplateAlreadyExistsException(response, errorBody) + + case strings.EqualFold("ValidationException", errorCode): + return awsAwsjson11_deserializeErrorValidationException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + type awsAwsjson11_deserializeOpDeleteLifecyclePolicy struct { } @@ -896,6 +1044,10 @@ func (m *awsAwsjson11_deserializeOpDeleteLifecyclePolicy) HandleDeserialize(ctx return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -949,9 +1101,6 @@ func awsAwsjson11_deserializeOpErrorDeleteLifecyclePolicy(response *smithyhttp.R errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -959,7 +1108,7 @@ func awsAwsjson11_deserializeOpErrorDeleteLifecyclePolicy(response *smithyhttp.R body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -971,13 +1120,12 @@ func awsAwsjson11_deserializeOpErrorDeleteLifecyclePolicy(response *smithyhttp.R } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -1019,6 +1167,10 @@ func (m *awsAwsjson11_deserializeOpDeletePullThroughCacheRule) HandleDeserialize return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -1072,9 +1224,6 @@ func awsAwsjson11_deserializeOpErrorDeletePullThroughCacheRule(response *smithyh errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -1082,7 +1231,7 @@ func awsAwsjson11_deserializeOpErrorDeletePullThroughCacheRule(response *smithyh body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1094,13 +1243,12 @@ func awsAwsjson11_deserializeOpErrorDeletePullThroughCacheRule(response *smithyh } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -1139,6 +1287,10 @@ func (m *awsAwsjson11_deserializeOpDeleteRegistryPolicy) HandleDeserialize(ctx c return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -1192,9 +1344,6 @@ func awsAwsjson11_deserializeOpErrorDeleteRegistryPolicy(response *smithyhttp.Re errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -1202,7 +1351,7 @@ func awsAwsjson11_deserializeOpErrorDeleteRegistryPolicy(response *smithyhttp.Re body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1214,13 +1363,12 @@ func awsAwsjson11_deserializeOpErrorDeleteRegistryPolicy(response *smithyhttp.Re } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -1259,6 +1407,10 @@ func (m *awsAwsjson11_deserializeOpDeleteRepository) HandleDeserialize(ctx conte return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -1312,9 +1464,6 @@ func awsAwsjson11_deserializeOpErrorDeleteRepository(response *smithyhttp.Respon errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -1322,7 +1471,7 @@ func awsAwsjson11_deserializeOpErrorDeleteRepository(response *smithyhttp.Respon body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1334,13 +1483,12 @@ func awsAwsjson11_deserializeOpErrorDeleteRepository(response *smithyhttp.Respon } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -1367,6 +1515,126 @@ func awsAwsjson11_deserializeOpErrorDeleteRepository(response *smithyhttp.Respon } } +type awsAwsjson11_deserializeOpDeleteRepositoryCreationTemplate struct { +} + +func (*awsAwsjson11_deserializeOpDeleteRepositoryCreationTemplate) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDeleteRepositoryCreationTemplate) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDeleteRepositoryCreationTemplate(response, &metadata) + } + output := &DeleteRepositoryCreationTemplateOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentDeleteRepositoryCreationTemplateOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDeleteRepositoryCreationTemplate(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("ServerException", errorCode): + return awsAwsjson11_deserializeErrorServerException(response, errorBody) + + case strings.EqualFold("TemplateNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorTemplateNotFoundException(response, errorBody) + + case strings.EqualFold("ValidationException", errorCode): + return awsAwsjson11_deserializeErrorValidationException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + type awsAwsjson11_deserializeOpDeleteRepositoryPolicy struct { } @@ -1382,6 +1650,10 @@ func (m *awsAwsjson11_deserializeOpDeleteRepositoryPolicy) HandleDeserialize(ctx return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -1435,9 +1707,6 @@ func awsAwsjson11_deserializeOpErrorDeleteRepositoryPolicy(response *smithyhttp. errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -1445,7 +1714,7 @@ func awsAwsjson11_deserializeOpErrorDeleteRepositoryPolicy(response *smithyhttp. body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1457,13 +1726,12 @@ func awsAwsjson11_deserializeOpErrorDeleteRepositoryPolicy(response *smithyhttp. } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -1502,6 +1770,10 @@ func (m *awsAwsjson11_deserializeOpDescribeImageReplicationStatus) HandleDeseria return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -1555,9 +1827,6 @@ func awsAwsjson11_deserializeOpErrorDescribeImageReplicationStatus(response *smi errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -1565,7 +1834,7 @@ func awsAwsjson11_deserializeOpErrorDescribeImageReplicationStatus(response *smi body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1577,13 +1846,12 @@ func awsAwsjson11_deserializeOpErrorDescribeImageReplicationStatus(response *smi } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("ImageNotFoundException", errorCode): return awsAwsjson11_deserializeErrorImageNotFoundException(response, errorBody) @@ -1625,6 +1893,10 @@ func (m *awsAwsjson11_deserializeOpDescribeImages) HandleDeserialize(ctx context return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -1678,9 +1950,6 @@ func awsAwsjson11_deserializeOpErrorDescribeImages(response *smithyhttp.Response errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -1688,7 +1957,7 @@ func awsAwsjson11_deserializeOpErrorDescribeImages(response *smithyhttp.Response body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1700,13 +1969,12 @@ func awsAwsjson11_deserializeOpErrorDescribeImages(response *smithyhttp.Response } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("ImageNotFoundException", errorCode): return awsAwsjson11_deserializeErrorImageNotFoundException(response, errorBody) @@ -1745,6 +2013,10 @@ func (m *awsAwsjson11_deserializeOpDescribeImageScanFindings) HandleDeserialize( return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -1798,9 +2070,6 @@ func awsAwsjson11_deserializeOpErrorDescribeImageScanFindings(response *smithyht errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -1808,7 +2077,7 @@ func awsAwsjson11_deserializeOpErrorDescribeImageScanFindings(response *smithyht body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1820,13 +2089,12 @@ func awsAwsjson11_deserializeOpErrorDescribeImageScanFindings(response *smithyht } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("ImageNotFoundException", errorCode): return awsAwsjson11_deserializeErrorImageNotFoundException(response, errorBody) @@ -1871,6 +2139,10 @@ func (m *awsAwsjson11_deserializeOpDescribePullThroughCacheRules) HandleDeserial return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -1924,9 +2196,6 @@ func awsAwsjson11_deserializeOpErrorDescribePullThroughCacheRules(response *smit errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -1934,7 +2203,7 @@ func awsAwsjson11_deserializeOpErrorDescribePullThroughCacheRules(response *smit body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1946,13 +2215,12 @@ func awsAwsjson11_deserializeOpErrorDescribePullThroughCacheRules(response *smit } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -1991,6 +2259,10 @@ func (m *awsAwsjson11_deserializeOpDescribeRegistry) HandleDeserialize(ctx conte return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -2044,9 +2316,6 @@ func awsAwsjson11_deserializeOpErrorDescribeRegistry(response *smithyhttp.Respon errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -2054,7 +2323,7 @@ func awsAwsjson11_deserializeOpErrorDescribeRegistry(response *smithyhttp.Respon body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -2066,13 +2335,12 @@ func awsAwsjson11_deserializeOpErrorDescribeRegistry(response *smithyhttp.Respon } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -2108,6 +2376,10 @@ func (m *awsAwsjson11_deserializeOpDescribeRepositories) HandleDeserialize(ctx c return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -2161,9 +2433,6 @@ func awsAwsjson11_deserializeOpErrorDescribeRepositories(response *smithyhttp.Re errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -2171,7 +2440,7 @@ func awsAwsjson11_deserializeOpErrorDescribeRepositories(response *smithyhttp.Re body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -2183,13 +2452,12 @@ func awsAwsjson11_deserializeOpErrorDescribeRepositories(response *smithyhttp.Re } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -2210,10 +2478,244 @@ func awsAwsjson11_deserializeOpErrorDescribeRepositories(response *smithyhttp.Re } } -type awsAwsjson11_deserializeOpGetAuthorizationToken struct { +type awsAwsjson11_deserializeOpDescribeRepositoryCreationTemplates struct { } -func (*awsAwsjson11_deserializeOpGetAuthorizationToken) ID() string { +func (*awsAwsjson11_deserializeOpDescribeRepositoryCreationTemplates) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDescribeRepositoryCreationTemplates) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDescribeRepositoryCreationTemplates(response, &metadata) + } + output := &DescribeRepositoryCreationTemplatesOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentDescribeRepositoryCreationTemplatesOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDescribeRepositoryCreationTemplates(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("ServerException", errorCode): + return awsAwsjson11_deserializeErrorServerException(response, errorBody) + + case strings.EqualFold("ValidationException", errorCode): + return awsAwsjson11_deserializeErrorValidationException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGetAccountSetting struct { +} + +func (*awsAwsjson11_deserializeOpGetAccountSetting) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpGetAccountSetting) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorGetAccountSetting(response, &metadata) + } + output := &GetAccountSettingOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentGetAccountSettingOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorGetAccountSetting(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("ServerException", errorCode): + return awsAwsjson11_deserializeErrorServerException(response, errorBody) + + case strings.EqualFold("ValidationException", errorCode): + return awsAwsjson11_deserializeErrorValidationException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGetAuthorizationToken struct { +} + +func (*awsAwsjson11_deserializeOpGetAuthorizationToken) ID() string { return "OperationDeserializer" } @@ -2225,6 +2727,10 @@ func (m *awsAwsjson11_deserializeOpGetAuthorizationToken) HandleDeserialize(ctx return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -2278,9 +2784,6 @@ func awsAwsjson11_deserializeOpErrorGetAuthorizationToken(response *smithyhttp.R errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -2288,7 +2791,7 @@ func awsAwsjson11_deserializeOpErrorGetAuthorizationToken(response *smithyhttp.R body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -2300,13 +2803,12 @@ func awsAwsjson11_deserializeOpErrorGetAuthorizationToken(response *smithyhttp.R } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -2339,6 +2841,10 @@ func (m *awsAwsjson11_deserializeOpGetDownloadUrlForLayer) HandleDeserialize(ctx return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -2392,9 +2898,6 @@ func awsAwsjson11_deserializeOpErrorGetDownloadUrlForLayer(response *smithyhttp. errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -2402,7 +2905,7 @@ func awsAwsjson11_deserializeOpErrorGetDownloadUrlForLayer(response *smithyhttp. body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -2414,13 +2917,12 @@ func awsAwsjson11_deserializeOpErrorGetDownloadUrlForLayer(response *smithyhttp. } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -2437,6 +2939,9 @@ func awsAwsjson11_deserializeOpErrorGetDownloadUrlForLayer(response *smithyhttp. case strings.EqualFold("ServerException", errorCode): return awsAwsjson11_deserializeErrorServerException(response, errorBody) + case strings.EqualFold("UnableToGetUpstreamLayerException", errorCode): + return awsAwsjson11_deserializeErrorUnableToGetUpstreamLayerException(response, errorBody) + default: genericError := &smithy.GenericAPIError{ Code: errorCode, @@ -2462,6 +2967,10 @@ func (m *awsAwsjson11_deserializeOpGetLifecyclePolicy) HandleDeserialize(ctx con return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -2515,9 +3024,6 @@ func awsAwsjson11_deserializeOpErrorGetLifecyclePolicy(response *smithyhttp.Resp errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -2525,7 +3031,7 @@ func awsAwsjson11_deserializeOpErrorGetLifecyclePolicy(response *smithyhttp.Resp body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -2537,13 +3043,12 @@ func awsAwsjson11_deserializeOpErrorGetLifecyclePolicy(response *smithyhttp.Resp } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -2585,6 +3090,10 @@ func (m *awsAwsjson11_deserializeOpGetLifecyclePolicyPreview) HandleDeserialize( return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -2638,9 +3147,6 @@ func awsAwsjson11_deserializeOpErrorGetLifecyclePolicyPreview(response *smithyht errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -2648,7 +3154,7 @@ func awsAwsjson11_deserializeOpErrorGetLifecyclePolicyPreview(response *smithyht body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -2660,13 +3166,12 @@ func awsAwsjson11_deserializeOpErrorGetLifecyclePolicyPreview(response *smithyht } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -2708,6 +3213,10 @@ func (m *awsAwsjson11_deserializeOpGetRegistryPolicy) HandleDeserialize(ctx cont return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -2761,9 +3270,6 @@ func awsAwsjson11_deserializeOpErrorGetRegistryPolicy(response *smithyhttp.Respo errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -2771,7 +3277,7 @@ func awsAwsjson11_deserializeOpErrorGetRegistryPolicy(response *smithyhttp.Respo body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -2783,13 +3289,12 @@ func awsAwsjson11_deserializeOpErrorGetRegistryPolicy(response *smithyhttp.Respo } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -2828,6 +3333,10 @@ func (m *awsAwsjson11_deserializeOpGetRegistryScanningConfiguration) HandleDeser return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -2881,9 +3390,6 @@ func awsAwsjson11_deserializeOpErrorGetRegistryScanningConfiguration(response *s errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -2891,7 +3397,7 @@ func awsAwsjson11_deserializeOpErrorGetRegistryScanningConfiguration(response *s body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -2903,13 +3409,12 @@ func awsAwsjson11_deserializeOpErrorGetRegistryScanningConfiguration(response *s } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -2945,6 +3450,10 @@ func (m *awsAwsjson11_deserializeOpGetRepositoryPolicy) HandleDeserialize(ctx co return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -2998,9 +3507,6 @@ func awsAwsjson11_deserializeOpErrorGetRepositoryPolicy(response *smithyhttp.Res errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -3008,7 +3514,7 @@ func awsAwsjson11_deserializeOpErrorGetRepositoryPolicy(response *smithyhttp.Res body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -3020,13 +3526,12 @@ func awsAwsjson11_deserializeOpErrorGetRepositoryPolicy(response *smithyhttp.Res } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -3065,6 +3570,10 @@ func (m *awsAwsjson11_deserializeOpInitiateLayerUpload) HandleDeserialize(ctx co return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -3118,9 +3627,6 @@ func awsAwsjson11_deserializeOpErrorInitiateLayerUpload(response *smithyhttp.Res errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -3128,7 +3634,7 @@ func awsAwsjson11_deserializeOpErrorInitiateLayerUpload(response *smithyhttp.Res body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -3140,13 +3646,12 @@ func awsAwsjson11_deserializeOpErrorInitiateLayerUpload(response *smithyhttp.Res } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -3185,6 +3690,10 @@ func (m *awsAwsjson11_deserializeOpListImages) HandleDeserialize(ctx context.Con return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -3238,9 +3747,6 @@ func awsAwsjson11_deserializeOpErrorListImages(response *smithyhttp.Response, me errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -3248,7 +3754,7 @@ func awsAwsjson11_deserializeOpErrorListImages(response *smithyhttp.Response, me body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -3260,13 +3766,12 @@ func awsAwsjson11_deserializeOpErrorListImages(response *smithyhttp.Response, me } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -3302,6 +3807,10 @@ func (m *awsAwsjson11_deserializeOpListTagsForResource) HandleDeserialize(ctx co return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -3355,9 +3864,6 @@ func awsAwsjson11_deserializeOpErrorListTagsForResource(response *smithyhttp.Res errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -3365,7 +3871,7 @@ func awsAwsjson11_deserializeOpErrorListTagsForResource(response *smithyhttp.Res body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -3377,13 +3883,12 @@ func awsAwsjson11_deserializeOpErrorListTagsForResource(response *smithyhttp.Res } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -3404,14 +3909,14 @@ func awsAwsjson11_deserializeOpErrorListTagsForResource(response *smithyhttp.Res } } -type awsAwsjson11_deserializeOpPutImage struct { +type awsAwsjson11_deserializeOpPutAccountSetting struct { } -func (*awsAwsjson11_deserializeOpPutImage) ID() string { +func (*awsAwsjson11_deserializeOpPutAccountSetting) ID() string { return "OperationDeserializer" } -func (m *awsAwsjson11_deserializeOpPutImage) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( +func (m *awsAwsjson11_deserializeOpPutAccountSetting) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) @@ -3419,15 +3924,19 @@ func (m *awsAwsjson11_deserializeOpPutImage) HandleDeserialize(ctx context.Conte return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { - return out, metadata, awsAwsjson11_deserializeOpErrorPutImage(response, &metadata) + return out, metadata, awsAwsjson11_deserializeOpErrorPutAccountSetting(response, &metadata) } - output := &PutImageOutput{} + output := &PutAccountSettingOutput{} out.Result = output var buff [1024]byte @@ -3447,7 +3956,7 @@ func (m *awsAwsjson11_deserializeOpPutImage) HandleDeserialize(ctx context.Conte return out, metadata, err } - err = awsAwsjson11_deserializeOpDocumentPutImageOutput(&output, shape) + err = awsAwsjson11_deserializeOpDocumentPutAccountSettingOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -3461,7 +3970,7 @@ func (m *awsAwsjson11_deserializeOpPutImage) HandleDeserialize(ctx context.Conte return out, metadata, err } -func awsAwsjson11_deserializeOpErrorPutImage(response *smithyhttp.Response, metadata *middleware.Metadata) error { +func awsAwsjson11_deserializeOpErrorPutAccountSetting(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} @@ -3472,9 +3981,6 @@ func awsAwsjson11_deserializeOpErrorPutImage(response *smithyhttp.Response, meta errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -3482,7 +3988,7 @@ func awsAwsjson11_deserializeOpErrorPutImage(response *smithyhttp.Response, meta body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -3494,45 +4000,164 @@ func awsAwsjson11_deserializeOpErrorPutImage(response *smithyhttp.Response, meta } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { - case strings.EqualFold("ImageAlreadyExistsException", errorCode): - return awsAwsjson11_deserializeErrorImageAlreadyExistsException(response, errorBody) - - case strings.EqualFold("ImageDigestDoesNotMatchException", errorCode): - return awsAwsjson11_deserializeErrorImageDigestDoesNotMatchException(response, errorBody) - - case strings.EqualFold("ImageTagAlreadyExistsException", errorCode): - return awsAwsjson11_deserializeErrorImageTagAlreadyExistsException(response, errorBody) - case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - case strings.EqualFold("KmsException", errorCode): - return awsAwsjson11_deserializeErrorKmsException(response, errorBody) - - case strings.EqualFold("LayersNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorLayersNotFoundException(response, errorBody) - case strings.EqualFold("LimitExceededException", errorCode): return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) - case strings.EqualFold("ReferencedImagesNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorReferencedImagesNotFoundException(response, errorBody) - - case strings.EqualFold("RepositoryNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorRepositoryNotFoundException(response, errorBody) - case strings.EqualFold("ServerException", errorCode): return awsAwsjson11_deserializeErrorServerException(response, errorBody) - default: + case strings.EqualFold("ValidationException", errorCode): + return awsAwsjson11_deserializeErrorValidationException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpPutImage struct { +} + +func (*awsAwsjson11_deserializeOpPutImage) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpPutImage) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorPutImage(response, &metadata) + } + output := &PutImageOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentPutImageOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorPutImage(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ImageAlreadyExistsException", errorCode): + return awsAwsjson11_deserializeErrorImageAlreadyExistsException(response, errorBody) + + case strings.EqualFold("ImageDigestDoesNotMatchException", errorCode): + return awsAwsjson11_deserializeErrorImageDigestDoesNotMatchException(response, errorBody) + + case strings.EqualFold("ImageTagAlreadyExistsException", errorCode): + return awsAwsjson11_deserializeErrorImageTagAlreadyExistsException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("KmsException", errorCode): + return awsAwsjson11_deserializeErrorKmsException(response, errorBody) + + case strings.EqualFold("LayersNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorLayersNotFoundException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("ReferencedImagesNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorReferencedImagesNotFoundException(response, errorBody) + + case strings.EqualFold("RepositoryNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorRepositoryNotFoundException(response, errorBody) + + case strings.EqualFold("ServerException", errorCode): + return awsAwsjson11_deserializeErrorServerException(response, errorBody) + + default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, @@ -3557,6 +4182,10 @@ func (m *awsAwsjson11_deserializeOpPutImageScanningConfiguration) HandleDeserial return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -3610,9 +4239,6 @@ func awsAwsjson11_deserializeOpErrorPutImageScanningConfiguration(response *smit errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -3620,7 +4246,7 @@ func awsAwsjson11_deserializeOpErrorPutImageScanningConfiguration(response *smit body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -3632,13 +4258,12 @@ func awsAwsjson11_deserializeOpErrorPutImageScanningConfiguration(response *smit } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -3677,6 +4302,10 @@ func (m *awsAwsjson11_deserializeOpPutImageTagMutability) HandleDeserialize(ctx return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -3730,9 +4359,6 @@ func awsAwsjson11_deserializeOpErrorPutImageTagMutability(response *smithyhttp.R errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -3740,7 +4366,7 @@ func awsAwsjson11_deserializeOpErrorPutImageTagMutability(response *smithyhttp.R body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -3752,13 +4378,12 @@ func awsAwsjson11_deserializeOpErrorPutImageTagMutability(response *smithyhttp.R } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -3794,6 +4419,10 @@ func (m *awsAwsjson11_deserializeOpPutLifecyclePolicy) HandleDeserialize(ctx con return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -3847,9 +4476,6 @@ func awsAwsjson11_deserializeOpErrorPutLifecyclePolicy(response *smithyhttp.Resp errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -3857,7 +4483,7 @@ func awsAwsjson11_deserializeOpErrorPutLifecyclePolicy(response *smithyhttp.Resp body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -3869,13 +4495,12 @@ func awsAwsjson11_deserializeOpErrorPutLifecyclePolicy(response *smithyhttp.Resp } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -3914,6 +4539,10 @@ func (m *awsAwsjson11_deserializeOpPutRegistryPolicy) HandleDeserialize(ctx cont return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -3967,9 +4596,6 @@ func awsAwsjson11_deserializeOpErrorPutRegistryPolicy(response *smithyhttp.Respo errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -3977,7 +4603,7 @@ func awsAwsjson11_deserializeOpErrorPutRegistryPolicy(response *smithyhttp.Respo body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -3989,13 +4615,12 @@ func awsAwsjson11_deserializeOpErrorPutRegistryPolicy(response *smithyhttp.Respo } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -4031,6 +4656,10 @@ func (m *awsAwsjson11_deserializeOpPutRegistryScanningConfiguration) HandleDeser return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -4084,9 +4713,6 @@ func awsAwsjson11_deserializeOpErrorPutRegistryScanningConfiguration(response *s errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -4094,7 +4720,7 @@ func awsAwsjson11_deserializeOpErrorPutRegistryScanningConfiguration(response *s body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -4106,13 +4732,12 @@ func awsAwsjson11_deserializeOpErrorPutRegistryScanningConfiguration(response *s } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -4148,6 +4773,10 @@ func (m *awsAwsjson11_deserializeOpPutReplicationConfiguration) HandleDeserializ return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -4201,9 +4830,6 @@ func awsAwsjson11_deserializeOpErrorPutReplicationConfiguration(response *smithy errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -4211,7 +4837,7 @@ func awsAwsjson11_deserializeOpErrorPutReplicationConfiguration(response *smithy body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -4223,13 +4849,12 @@ func awsAwsjson11_deserializeOpErrorPutReplicationConfiguration(response *smithy } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -4265,6 +4890,10 @@ func (m *awsAwsjson11_deserializeOpSetRepositoryPolicy) HandleDeserialize(ctx co return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -4318,9 +4947,6 @@ func awsAwsjson11_deserializeOpErrorSetRepositoryPolicy(response *smithyhttp.Res errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -4328,7 +4954,7 @@ func awsAwsjson11_deserializeOpErrorSetRepositoryPolicy(response *smithyhttp.Res body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -4340,13 +4966,12 @@ func awsAwsjson11_deserializeOpErrorSetRepositoryPolicy(response *smithyhttp.Res } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -4382,6 +5007,10 @@ func (m *awsAwsjson11_deserializeOpStartImageScan) HandleDeserialize(ctx context return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -4435,9 +5064,6 @@ func awsAwsjson11_deserializeOpErrorStartImageScan(response *smithyhttp.Response errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -4445,7 +5071,7 @@ func awsAwsjson11_deserializeOpErrorStartImageScan(response *smithyhttp.Response body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -4457,13 +5083,12 @@ func awsAwsjson11_deserializeOpErrorStartImageScan(response *smithyhttp.Response } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("ImageNotFoundException", errorCode): return awsAwsjson11_deserializeErrorImageNotFoundException(response, errorBody) @@ -4511,6 +5136,10 @@ func (m *awsAwsjson11_deserializeOpStartLifecyclePolicyPreview) HandleDeserializ return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -4564,9 +5193,6 @@ func awsAwsjson11_deserializeOpErrorStartLifecyclePolicyPreview(response *smithy errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -4574,7 +5200,7 @@ func awsAwsjson11_deserializeOpErrorStartLifecyclePolicyPreview(response *smithy body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -4586,13 +5212,12 @@ func awsAwsjson11_deserializeOpErrorStartLifecyclePolicyPreview(response *smithy } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -4637,6 +5262,10 @@ func (m *awsAwsjson11_deserializeOpTagResource) HandleDeserialize(ctx context.Co return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -4690,9 +5319,6 @@ func awsAwsjson11_deserializeOpErrorTagResource(response *smithyhttp.Response, m errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -4700,7 +5326,7 @@ func awsAwsjson11_deserializeOpErrorTagResource(response *smithyhttp.Response, m body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -4712,13 +5338,12 @@ func awsAwsjson11_deserializeOpErrorTagResource(response *smithyhttp.Response, m } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -4760,6 +5385,10 @@ func (m *awsAwsjson11_deserializeOpUntagResource) HandleDeserialize(ctx context. return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -4813,9 +5442,6 @@ func awsAwsjson11_deserializeOpErrorUntagResource(response *smithyhttp.Response, errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -4823,7 +5449,7 @@ func awsAwsjson11_deserializeOpErrorUntagResource(response *smithyhttp.Response, body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -4835,13 +5461,12 @@ func awsAwsjson11_deserializeOpErrorUntagResource(response *smithyhttp.Response, } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -4868,14 +5493,14 @@ func awsAwsjson11_deserializeOpErrorUntagResource(response *smithyhttp.Response, } } -type awsAwsjson11_deserializeOpUploadLayerPart struct { +type awsAwsjson11_deserializeOpUpdatePullThroughCacheRule struct { } -func (*awsAwsjson11_deserializeOpUploadLayerPart) ID() string { +func (*awsAwsjson11_deserializeOpUpdatePullThroughCacheRule) ID() string { return "OperationDeserializer" } -func (m *awsAwsjson11_deserializeOpUploadLayerPart) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( +func (m *awsAwsjson11_deserializeOpUpdatePullThroughCacheRule) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) @@ -4883,15 +5508,19 @@ func (m *awsAwsjson11_deserializeOpUploadLayerPart) HandleDeserialize(ctx contex return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { - return out, metadata, awsAwsjson11_deserializeOpErrorUploadLayerPart(response, &metadata) + return out, metadata, awsAwsjson11_deserializeOpErrorUpdatePullThroughCacheRule(response, &metadata) } - output := &UploadLayerPartOutput{} + output := &UpdatePullThroughCacheRuleOutput{} out.Result = output var buff [1024]byte @@ -4911,7 +5540,7 @@ func (m *awsAwsjson11_deserializeOpUploadLayerPart) HandleDeserialize(ctx contex return out, metadata, err } - err = awsAwsjson11_deserializeOpDocumentUploadLayerPartOutput(&output, shape) + err = awsAwsjson11_deserializeOpDocumentUpdatePullThroughCacheRuleOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -4925,7 +5554,7 @@ func (m *awsAwsjson11_deserializeOpUploadLayerPart) HandleDeserialize(ctx contex return out, metadata, err } -func awsAwsjson11_deserializeOpErrorUploadLayerPart(response *smithyhttp.Response, metadata *middleware.Metadata) error { +func awsAwsjson11_deserializeOpErrorUpdatePullThroughCacheRule(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} @@ -4936,9 +5565,6 @@ func awsAwsjson11_deserializeOpErrorUploadLayerPart(response *smithyhttp.Respons errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -4946,7 +5572,7 @@ func awsAwsjson11_deserializeOpErrorUploadLayerPart(response *smithyhttp.Respons body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -4958,34 +5584,33 @@ func awsAwsjson11_deserializeOpErrorUploadLayerPart(response *smithyhttp.Respons } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { - case strings.EqualFold("InvalidLayerPartException", errorCode): - return awsAwsjson11_deserializeErrorInvalidLayerPartException(response, errorBody) - case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - case strings.EqualFold("KmsException", errorCode): - return awsAwsjson11_deserializeErrorKmsException(response, errorBody) - - case strings.EqualFold("LimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + case strings.EqualFold("PullThroughCacheRuleNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorPullThroughCacheRuleNotFoundException(response, errorBody) - case strings.EqualFold("RepositoryNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorRepositoryNotFoundException(response, errorBody) + case strings.EqualFold("SecretNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorSecretNotFoundException(response, errorBody) case strings.EqualFold("ServerException", errorCode): return awsAwsjson11_deserializeErrorServerException(response, errorBody) - case strings.EqualFold("UploadNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorUploadNotFoundException(response, errorBody) + case strings.EqualFold("UnableToAccessSecretException", errorCode): + return awsAwsjson11_deserializeErrorUnableToAccessSecretException(response, errorBody) + + case strings.EqualFold("UnableToDecryptSecretValueException", errorCode): + return awsAwsjson11_deserializeErrorUnableToDecryptSecretValueException(response, errorBody) + + case strings.EqualFold("ValidationException", errorCode): + return awsAwsjson11_deserializeErrorValidationException(response, errorBody) default: genericError := &smithy.GenericAPIError{ @@ -4997,46 +5622,40 @@ func awsAwsjson11_deserializeOpErrorUploadLayerPart(response *smithyhttp.Respons } } -func awsAwsjson11_deserializeErrorEmptyUploadException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } +type awsAwsjson11_deserializeOpUpdateRepositoryCreationTemplate struct { +} - output := &types.EmptyUploadException{} - err := awsAwsjson11_deserializeDocumentEmptyUploadException(&output, shape) +func (*awsAwsjson11_deserializeOpUpdateRepositoryCreationTemplate) ID() string { + return "OperationDeserializer" +} +func (m *awsAwsjson11_deserializeOpUpdateRepositoryCreationTemplate) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err + return out, metadata, err } - errorBody.Seek(0, io.SeekStart) - return output -} + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorUpdateRepositoryCreationTemplate(response, &metadata) + } + output := &UpdateRepositoryCreationTemplateOutput{} + out.Result = output -func awsAwsjson11_deserializeErrorImageAlreadyExistsException(response *smithyhttp.Response, errorBody *bytes.Reader) error { var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(errorBody, ringBuffer) + body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} @@ -5047,12 +5666,10 @@ func awsAwsjson11_deserializeErrorImageAlreadyExistsException(response *smithyht Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } - return err + return out, metadata, err } - output := &types.ImageAlreadyExistsException{} - err := awsAwsjson11_deserializeDocumentImageAlreadyExistsException(&output, shape) - + err = awsAwsjson11_deserializeOpDocumentUpdateRepositoryCreationTemplateOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -5060,22 +5677,32 @@ func awsAwsjson11_deserializeErrorImageAlreadyExistsException(response *smithyht Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } - return err + return out, metadata, err } - errorBody.Seek(0, io.SeekStart) - return output + return out, metadata, err } -func awsAwsjson11_deserializeErrorImageDigestDoesNotMatchException(response *smithyhttp.Response, errorBody *bytes.Reader) error { +func awsAwsjson11_deserializeOpErrorUpdateRepositoryCreationTemplate(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ @@ -5085,8 +5712,375 @@ func awsAwsjson11_deserializeErrorImageDigestDoesNotMatchException(response *smi return err } - output := &types.ImageDigestDoesNotMatchException{} - err := awsAwsjson11_deserializeDocumentImageDigestDoesNotMatchException(&output, shape) + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("ServerException", errorCode): + return awsAwsjson11_deserializeErrorServerException(response, errorBody) + + case strings.EqualFold("TemplateNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorTemplateNotFoundException(response, errorBody) + + case strings.EqualFold("ValidationException", errorCode): + return awsAwsjson11_deserializeErrorValidationException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpUploadLayerPart struct { +} + +func (*awsAwsjson11_deserializeOpUploadLayerPart) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpUploadLayerPart) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorUploadLayerPart(response, &metadata) + } + output := &UploadLayerPartOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentUploadLayerPartOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorUploadLayerPart(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InvalidLayerPartException", errorCode): + return awsAwsjson11_deserializeErrorInvalidLayerPartException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("KmsException", errorCode): + return awsAwsjson11_deserializeErrorKmsException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("RepositoryNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorRepositoryNotFoundException(response, errorBody) + + case strings.EqualFold("ServerException", errorCode): + return awsAwsjson11_deserializeErrorServerException(response, errorBody) + + case strings.EqualFold("UploadNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUploadNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpValidatePullThroughCacheRule struct { +} + +func (*awsAwsjson11_deserializeOpValidatePullThroughCacheRule) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpValidatePullThroughCacheRule) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorValidatePullThroughCacheRule(response, &metadata) + } + output := &ValidatePullThroughCacheRuleOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentValidatePullThroughCacheRuleOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorValidatePullThroughCacheRule(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("PullThroughCacheRuleNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorPullThroughCacheRuleNotFoundException(response, errorBody) + + case strings.EqualFold("ServerException", errorCode): + return awsAwsjson11_deserializeErrorServerException(response, errorBody) + + case strings.EqualFold("ValidationException", errorCode): + return awsAwsjson11_deserializeErrorValidationException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +func awsAwsjson11_deserializeErrorEmptyUploadException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.EmptyUploadException{} + err := awsAwsjson11_deserializeDocumentEmptyUploadException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorImageAlreadyExistsException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.ImageAlreadyExistsException{} + err := awsAwsjson11_deserializeDocumentImageAlreadyExistsException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorImageDigestDoesNotMatchException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.ImageDigestDoesNotMatchException{} + err := awsAwsjson11_deserializeDocumentImageDigestDoesNotMatchException(&output, shape) if err != nil { var snapshot bytes.Buffer @@ -5942,6 +6936,41 @@ func awsAwsjson11_deserializeErrorScanNotFoundException(response *smithyhttp.Res return output } +func awsAwsjson11_deserializeErrorSecretNotFoundException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.SecretNotFoundException{} + err := awsAwsjson11_deserializeDocumentSecretNotFoundException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + func awsAwsjson11_deserializeErrorServerException(response *smithyhttp.Response, errorBody *bytes.Reader) error { var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -5977,7 +7006,217 @@ func awsAwsjson11_deserializeErrorServerException(response *smithyhttp.Response, return output } -func awsAwsjson11_deserializeErrorTooManyTagsException(response *smithyhttp.Response, errorBody *bytes.Reader) error { +func awsAwsjson11_deserializeErrorTemplateAlreadyExistsException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.TemplateAlreadyExistsException{} + err := awsAwsjson11_deserializeDocumentTemplateAlreadyExistsException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorTemplateNotFoundException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.TemplateNotFoundException{} + err := awsAwsjson11_deserializeDocumentTemplateNotFoundException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorTooManyTagsException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.TooManyTagsException{} + err := awsAwsjson11_deserializeDocumentTooManyTagsException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorUnableToAccessSecretException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.UnableToAccessSecretException{} + err := awsAwsjson11_deserializeDocumentUnableToAccessSecretException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorUnableToDecryptSecretValueException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.UnableToDecryptSecretValueException{} + err := awsAwsjson11_deserializeDocumentUnableToDecryptSecretValueException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorUnableToGetUpstreamImageException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.UnableToGetUpstreamImageException{} + err := awsAwsjson11_deserializeDocumentUnableToGetUpstreamImageException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorUnableToGetUpstreamLayerException(response *smithyhttp.Response, errorBody *bytes.Reader) error { var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -5995,8 +7234,8 @@ func awsAwsjson11_deserializeErrorTooManyTagsException(response *smithyhttp.Resp return err } - output := &types.TooManyTagsException{} - err := awsAwsjson11_deserializeDocumentTooManyTagsException(&output, shape) + output := &types.UnableToGetUpstreamLayerException{} + err := awsAwsjson11_deserializeDocumentUnableToGetUpstreamLayerException(&output, shape) if err != nil { var snapshot bytes.Buffer @@ -6768,7 +8007,7 @@ func awsAwsjson11_deserializeDocumentEmptyUploadException(v **types.EmptyUploadE for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -6835,6 +8074,55 @@ func awsAwsjson11_deserializeDocumentEncryptionConfiguration(v **types.Encryptio return nil } +func awsAwsjson11_deserializeDocumentEncryptionConfigurationForRepositoryCreationTemplate(v **types.EncryptionConfigurationForRepositoryCreationTemplate, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.EncryptionConfigurationForRepositoryCreationTemplate + if *v == nil { + sv = &types.EncryptionConfigurationForRepositoryCreationTemplate{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "encryptionType": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected EncryptionType to be of type string, got %T instead", value) + } + sv.EncryptionType = types.EncryptionType(jtv) + } + + case "kmsKey": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected KmsKeyForRepositoryCreationTemplate to be of type string, got %T instead", value) + } + sv.KmsKey = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + func awsAwsjson11_deserializeDocumentEnhancedImageScanFinding(v **types.EnhancedImageScanFinding, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) @@ -6875,6 +8163,15 @@ func awsAwsjson11_deserializeDocumentEnhancedImageScanFinding(v **types.Enhanced sv.Description = ptr.String(jtv) } + case "exploitAvailable": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ExploitAvailable to be of type string, got %T instead", value) + } + sv.ExploitAvailable = ptr.String(jtv) + } + case "findingArn": if value != nil { jtv, ok := value.(string) @@ -6900,6 +8197,15 @@ func awsAwsjson11_deserializeDocumentEnhancedImageScanFinding(v **types.Enhanced } } + case "fixAvailable": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected FixAvailable to be of type string, got %T instead", value) + } + sv.FixAvailable = ptr.String(jtv) + } + case "lastObservedAt": if value != nil { switch jtv := value.(type) { @@ -7199,7 +8505,7 @@ func awsAwsjson11_deserializeDocumentImageAlreadyExistsException(v **types.Image for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -7409,7 +8715,7 @@ func awsAwsjson11_deserializeDocumentImageDigestDoesNotMatchException(v **types. for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -7654,7 +8960,7 @@ func awsAwsjson11_deserializeDocumentImageNotFoundException(v **types.ImageNotFo for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -8136,7 +9442,7 @@ func awsAwsjson11_deserializeDocumentImageTagAlreadyExistsException(v **types.Im for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -8248,7 +9554,7 @@ func awsAwsjson11_deserializeDocumentInvalidLayerException(v **types.InvalidLaye for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -8301,7 +9607,7 @@ func awsAwsjson11_deserializeDocumentInvalidLayerPartException(v **types.Invalid sv.LastValidByteReceived = ptr.Int64(i64) } - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -8368,7 +9674,7 @@ func awsAwsjson11_deserializeDocumentInvalidParameterException(v **types.Invalid for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -8408,7 +9714,7 @@ func awsAwsjson11_deserializeDocumentInvalidTagParameterException(v **types.Inva for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -8457,7 +9763,7 @@ func awsAwsjson11_deserializeDocumentKmsException(v **types.KmsException, value sv.KmsError = ptr.String(jtv) } - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -8568,7 +9874,7 @@ func awsAwsjson11_deserializeDocumentLayerAlreadyExistsException(v **types.Layer for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -8700,7 +10006,7 @@ func awsAwsjson11_deserializeDocumentLayerInaccessibleException(v **types.LayerI for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -8774,7 +10080,7 @@ func awsAwsjson11_deserializeDocumentLayerPartTooSmallException(v **types.LayerP for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -8814,7 +10120,7 @@ func awsAwsjson11_deserializeDocumentLayersNotFoundException(v **types.LayersNot for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -8854,7 +10160,7 @@ func awsAwsjson11_deserializeDocumentLifecyclePolicyNotFoundException(v **types. for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -8894,7 +10200,7 @@ func awsAwsjson11_deserializeDocumentLifecyclePolicyPreviewInProgressException(v for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -8934,7 +10240,7 @@ func awsAwsjson11_deserializeDocumentLifecyclePolicyPreviewNotFoundException(v * for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -9171,7 +10477,7 @@ func awsAwsjson11_deserializeDocumentLimitExceededException(v **types.LimitExcee for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -9346,6 +10652,15 @@ func awsAwsjson11_deserializeDocumentPullThroughCacheRule(v **types.PullThroughC } } + case "credentialArn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected CredentialArn to be of type string, got %T instead", value) + } + sv.CredentialArn = ptr.String(jtv) + } + case "ecrRepositoryPrefix": if value != nil { jtv, ok := value.(string) @@ -9364,6 +10679,31 @@ func awsAwsjson11_deserializeDocumentPullThroughCacheRule(v **types.PullThroughC sv.RegistryId = ptr.String(jtv) } + case "updatedAt": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.UpdatedAt = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected UpdatedTimestamp to be a JSON Number, got %T instead", value) + + } + } + + case "upstreamRegistry": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UpstreamRegistry to be of type string, got %T instead", value) + } + sv.UpstreamRegistry = types.UpstreamRegistry(jtv) + } + case "upstreamRegistryUrl": if value != nil { jtv, ok := value.(string) @@ -9404,7 +10744,7 @@ func awsAwsjson11_deserializeDocumentPullThroughCacheRuleAlreadyExistsException( for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -9478,7 +10818,7 @@ func awsAwsjson11_deserializeDocumentPullThroughCacheRuleNotFoundException(v **t for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -9496,6 +10836,42 @@ func awsAwsjson11_deserializeDocumentPullThroughCacheRuleNotFoundException(v **t return nil } +func awsAwsjson11_deserializeDocumentRCTAppliedForList(v *[]types.RCTAppliedFor, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.RCTAppliedFor + if *v == nil { + cv = []types.RCTAppliedFor{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.RCTAppliedFor + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected RCTAppliedFor to be of type string, got %T instead", value) + } + col = types.RCTAppliedFor(jtv) + } + cv = append(cv, col) + + } + *v = cv + return nil +} + func awsAwsjson11_deserializeDocumentRecommendation(v **types.Recommendation, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) @@ -9567,7 +10943,7 @@ func awsAwsjson11_deserializeDocumentReferencedImagesNotFoundException(v **types for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -9643,7 +11019,7 @@ func awsAwsjson11_deserializeDocumentRegistryPolicyNotFoundException(v **types.R for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -10175,7 +11551,7 @@ func awsAwsjson11_deserializeDocumentRepositoryAlreadyExistsException(v **types. for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -10189,7 +11565,173 @@ func awsAwsjson11_deserializeDocumentRepositoryAlreadyExistsException(v **types. } } - *v = sv + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentRepositoryCreationTemplate(v **types.RepositoryCreationTemplate, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.RepositoryCreationTemplate + if *v == nil { + sv = &types.RepositoryCreationTemplate{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "appliedFor": + if err := awsAwsjson11_deserializeDocumentRCTAppliedForList(&sv.AppliedFor, value); err != nil { + return err + } + + case "createdAt": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.CreatedAt = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected Date to be a JSON Number, got %T instead", value) + + } + } + + case "customRoleArn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected CustomRoleArn to be of type string, got %T instead", value) + } + sv.CustomRoleArn = ptr.String(jtv) + } + + case "description": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected RepositoryTemplateDescription to be of type string, got %T instead", value) + } + sv.Description = ptr.String(jtv) + } + + case "encryptionConfiguration": + if err := awsAwsjson11_deserializeDocumentEncryptionConfigurationForRepositoryCreationTemplate(&sv.EncryptionConfiguration, value); err != nil { + return err + } + + case "imageTagMutability": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ImageTagMutability to be of type string, got %T instead", value) + } + sv.ImageTagMutability = types.ImageTagMutability(jtv) + } + + case "lifecyclePolicy": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected LifecyclePolicyTextForRepositoryCreationTemplate to be of type string, got %T instead", value) + } + sv.LifecyclePolicy = ptr.String(jtv) + } + + case "prefix": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected Prefix to be of type string, got %T instead", value) + } + sv.Prefix = ptr.String(jtv) + } + + case "repositoryPolicy": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected RepositoryPolicyText to be of type string, got %T instead", value) + } + sv.RepositoryPolicy = ptr.String(jtv) + } + + case "resourceTags": + if err := awsAwsjson11_deserializeDocumentTagList(&sv.ResourceTags, value); err != nil { + return err + } + + case "updatedAt": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.UpdatedAt = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected Date to be a JSON Number, got %T instead", value) + + } + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentRepositoryCreationTemplateList(v *[]types.RepositoryCreationTemplate, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.RepositoryCreationTemplate + if *v == nil { + cv = []types.RepositoryCreationTemplate{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.RepositoryCreationTemplate + destAddr := &col + if err := awsAwsjson11_deserializeDocumentRepositoryCreationTemplate(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv return nil } @@ -10332,7 +11874,7 @@ func awsAwsjson11_deserializeDocumentRepositoryNotEmptyException(v **types.Repos for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -10372,7 +11914,7 @@ func awsAwsjson11_deserializeDocumentRepositoryNotFoundException(v **types.Repos for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -10412,7 +11954,7 @@ func awsAwsjson11_deserializeDocumentRepositoryPolicyNotFoundException(v **types for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -10862,7 +12404,7 @@ func awsAwsjson11_deserializeDocumentScanNotFoundException(v **types.ScanNotFoun for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -10916,6 +12458,46 @@ func awsAwsjson11_deserializeDocumentScoreDetails(v **types.ScoreDetails, value return nil } +func awsAwsjson11_deserializeDocumentSecretNotFoundException(v **types.SecretNotFoundException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.SecretNotFoundException + if *v == nil { + sv = &types.SecretNotFoundException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ExceptionMessage to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + func awsAwsjson11_deserializeDocumentServerException(v **types.ServerException, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) @@ -10938,7 +12520,7 @@ func awsAwsjson11_deserializeDocumentServerException(v **types.ServerException, for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -11020,26 +12602,262 @@ func awsAwsjson11_deserializeDocumentTagList(v *[]types.Tag, value interface{}) var cv []types.Tag if *v == nil { - cv = []types.Tag{} + cv = []types.Tag{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.Tag + destAddr := &col + if err := awsAwsjson11_deserializeDocumentTag(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentTags(v *map[string]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var mv map[string]string + if *v == nil { + mv = map[string]string{} + } else { + mv = *v + } + + for key, value := range shape { + var parsedVal string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected TagValue to be of type string, got %T instead", value) + } + parsedVal = jtv + } + mv[key] = parsedVal + + } + *v = mv + return nil +} + +func awsAwsjson11_deserializeDocumentTemplateAlreadyExistsException(v **types.TemplateAlreadyExistsException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.TemplateAlreadyExistsException + if *v == nil { + sv = &types.TemplateAlreadyExistsException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ExceptionMessage to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentTemplateNotFoundException(v **types.TemplateNotFoundException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.TemplateNotFoundException + if *v == nil { + sv = &types.TemplateNotFoundException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ExceptionMessage to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentTooManyTagsException(v **types.TooManyTagsException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.TooManyTagsException + if *v == nil { + sv = &types.TooManyTagsException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ExceptionMessage to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUnableToAccessSecretException(v **types.UnableToAccessSecretException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UnableToAccessSecretException + if *v == nil { + sv = &types.UnableToAccessSecretException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ExceptionMessage to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUnableToDecryptSecretValueException(v **types.UnableToDecryptSecretValueException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UnableToDecryptSecretValueException + if *v == nil { + sv = &types.UnableToDecryptSecretValueException{} } else { - cv = *v + sv = *v } - for _, value := range shape { - var col types.Tag - destAddr := &col - if err := awsAwsjson11_deserializeDocumentTag(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ExceptionMessage to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + default: + _, _ = key, value + + } } - *v = cv + *v = sv return nil } -func awsAwsjson11_deserializeDocumentTags(v *map[string]string, value interface{}) error { +func awsAwsjson11_deserializeDocumentUnableToGetUpstreamImageException(v **types.UnableToGetUpstreamImageException, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } @@ -11052,30 +12870,34 @@ func awsAwsjson11_deserializeDocumentTags(v *map[string]string, value interface{ return fmt.Errorf("unexpected JSON type %v", value) } - var mv map[string]string + var sv *types.UnableToGetUpstreamImageException if *v == nil { - mv = map[string]string{} + sv = &types.UnableToGetUpstreamImageException{} } else { - mv = *v + sv = *v } for key, value := range shape { - var parsedVal string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected TagValue to be of type string, got %T instead", value) + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ExceptionMessage to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) } - parsedVal = jtv - } - mv[key] = parsedVal + default: + _, _ = key, value + + } } - *v = mv + *v = sv return nil } -func awsAwsjson11_deserializeDocumentTooManyTagsException(v **types.TooManyTagsException, value interface{}) error { +func awsAwsjson11_deserializeDocumentUnableToGetUpstreamLayerException(v **types.UnableToGetUpstreamLayerException, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } @@ -11088,16 +12910,16 @@ func awsAwsjson11_deserializeDocumentTooManyTagsException(v **types.TooManyTagsE return fmt.Errorf("unexpected JSON type %v", value) } - var sv *types.TooManyTagsException + var sv *types.UnableToGetUpstreamLayerException if *v == nil { - sv = &types.TooManyTagsException{} + sv = &types.UnableToGetUpstreamLayerException{} } else { sv = *v } for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -11137,7 +12959,7 @@ func awsAwsjson11_deserializeDocumentUnsupportedImageTypeException(v **types.Uns for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -11177,7 +12999,7 @@ func awsAwsjson11_deserializeDocumentUnsupportedUpstreamRegistryException(v **ty for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -11217,7 +13039,7 @@ func awsAwsjson11_deserializeDocumentUploadNotFoundException(v **types.UploadNot for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -11257,7 +13079,7 @@ func awsAwsjson11_deserializeDocumentValidationException(v **types.ValidationExc for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -11328,6 +13150,15 @@ func awsAwsjson11_deserializeDocumentVulnerablePackage(v **types.VulnerablePacka sv.FilePath = ptr.String(jtv) } + case "fixedInVersion": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected FixedInVersion to be of type string, got %T instead", value) + } + sv.FixedInVersion = ptr.String(jtv) + } + case "name": if value != nil { jtv, ok := value.(string) @@ -11685,6 +13516,15 @@ func awsAwsjson11_deserializeOpDocumentCreatePullThroughCacheRuleOutput(v **Crea } } + case "credentialArn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected CredentialArn to be of type string, got %T instead", value) + } + sv.CredentialArn = ptr.String(jtv) + } + case "ecrRepositoryPrefix": if value != nil { jtv, ok := value.(string) @@ -11703,6 +13543,15 @@ func awsAwsjson11_deserializeOpDocumentCreatePullThroughCacheRuleOutput(v **Crea sv.RegistryId = ptr.String(jtv) } + case "upstreamRegistry": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UpstreamRegistry to be of type string, got %T instead", value) + } + sv.UpstreamRegistry = types.UpstreamRegistry(jtv) + } + case "upstreamRegistryUrl": if value != nil { jtv, ok := value.(string) @@ -11721,6 +13570,51 @@ func awsAwsjson11_deserializeOpDocumentCreatePullThroughCacheRuleOutput(v **Crea return nil } +func awsAwsjson11_deserializeOpDocumentCreateRepositoryCreationTemplateOutput(v **CreateRepositoryCreationTemplateOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *CreateRepositoryCreationTemplateOutput + if *v == nil { + sv = &CreateRepositoryCreationTemplateOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "registryId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected RegistryId to be of type string, got %T instead", value) + } + sv.RegistryId = ptr.String(jtv) + } + + case "repositoryCreationTemplate": + if err := awsAwsjson11_deserializeDocumentRepositoryCreationTemplate(&sv.RepositoryCreationTemplate, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + func awsAwsjson11_deserializeOpDocumentCreateRepositoryOutput(v **CreateRepositoryOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) @@ -11869,6 +13763,15 @@ func awsAwsjson11_deserializeOpDocumentDeletePullThroughCacheRuleOutput(v **Dele } } + case "credentialArn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected CredentialArn to be of type string, got %T instead", value) + } + sv.CredentialArn = ptr.String(jtv) + } + case "ecrRepositoryPrefix": if value != nil { jtv, ok := value.(string) @@ -11954,6 +13857,51 @@ func awsAwsjson11_deserializeOpDocumentDeleteRegistryPolicyOutput(v **DeleteRegi return nil } +func awsAwsjson11_deserializeOpDocumentDeleteRepositoryCreationTemplateOutput(v **DeleteRepositoryCreationTemplateOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *DeleteRepositoryCreationTemplateOutput + if *v == nil { + sv = &DeleteRepositoryCreationTemplateOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "registryId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected RegistryId to be of type string, got %T instead", value) + } + sv.RegistryId = ptr.String(jtv) + } + + case "repositoryCreationTemplate": + if err := awsAwsjson11_deserializeDocumentRepositoryCreationTemplate(&sv.RepositoryCreationTemplate, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + func awsAwsjson11_deserializeOpDocumentDeleteRepositoryOutput(v **DeleteRepositoryOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) @@ -12281,8 +14229,107 @@ func awsAwsjson11_deserializeOpDocumentDescribeRegistryOutput(v **DescribeRegist sv = *v } - for key, value := range shape { - switch key { + for key, value := range shape { + switch key { + case "registryId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected RegistryId to be of type string, got %T instead", value) + } + sv.RegistryId = ptr.String(jtv) + } + + case "replicationConfiguration": + if err := awsAwsjson11_deserializeDocumentReplicationConfiguration(&sv.ReplicationConfiguration, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentDescribeRepositoriesOutput(v **DescribeRepositoriesOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *DescribeRepositoriesOutput + if *v == nil { + sv = &DescribeRepositoriesOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "nextToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected NextToken to be of type string, got %T instead", value) + } + sv.NextToken = ptr.String(jtv) + } + + case "repositories": + if err := awsAwsjson11_deserializeDocumentRepositoryList(&sv.Repositories, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentDescribeRepositoryCreationTemplatesOutput(v **DescribeRepositoryCreationTemplatesOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *DescribeRepositoryCreationTemplatesOutput + if *v == nil { + sv = &DescribeRepositoryCreationTemplatesOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "nextToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected NextToken to be of type string, got %T instead", value) + } + sv.NextToken = ptr.String(jtv) + } + case "registryId": if value != nil { jtv, ok := value.(string) @@ -12292,8 +14339,8 @@ func awsAwsjson11_deserializeOpDocumentDescribeRegistryOutput(v **DescribeRegist sv.RegistryId = ptr.String(jtv) } - case "replicationConfiguration": - if err := awsAwsjson11_deserializeDocumentReplicationConfiguration(&sv.ReplicationConfiguration, value); err != nil { + case "repositoryCreationTemplates": + if err := awsAwsjson11_deserializeDocumentRepositoryCreationTemplateList(&sv.RepositoryCreationTemplates, value); err != nil { return err } @@ -12306,7 +14353,7 @@ func awsAwsjson11_deserializeOpDocumentDescribeRegistryOutput(v **DescribeRegist return nil } -func awsAwsjson11_deserializeOpDocumentDescribeRepositoriesOutput(v **DescribeRepositoriesOutput, value interface{}) error { +func awsAwsjson11_deserializeOpDocumentGetAccountSettingOutput(v **GetAccountSettingOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } @@ -12319,27 +14366,31 @@ func awsAwsjson11_deserializeOpDocumentDescribeRepositoriesOutput(v **DescribeRe return fmt.Errorf("unexpected JSON type %v", value) } - var sv *DescribeRepositoriesOutput + var sv *GetAccountSettingOutput if *v == nil { - sv = &DescribeRepositoriesOutput{} + sv = &GetAccountSettingOutput{} } else { sv = *v } for key, value := range shape { switch key { - case "nextToken": + case "name": if value != nil { jtv, ok := value.(string) if !ok { - return fmt.Errorf("expected NextToken to be of type string, got %T instead", value) + return fmt.Errorf("expected AccountSettingName to be of type string, got %T instead", value) } - sv.NextToken = ptr.String(jtv) + sv.Name = ptr.String(jtv) } - case "repositories": - if err := awsAwsjson11_deserializeDocumentRepositoryList(&sv.Repositories, value); err != nil { - return err + case "value": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AccountSettingName to be of type string, got %T instead", value) + } + sv.Value = ptr.String(jtv) } default: @@ -12882,6 +14933,55 @@ func awsAwsjson11_deserializeOpDocumentListTagsForResourceOutput(v **ListTagsFor return nil } +func awsAwsjson11_deserializeOpDocumentPutAccountSettingOutput(v **PutAccountSettingOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *PutAccountSettingOutput + if *v == nil { + sv = &PutAccountSettingOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "name": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AccountSettingName to be of type string, got %T instead", value) + } + sv.Name = ptr.String(jtv) + } + + case "value": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AccountSettingValue to be of type string, got %T instead", value) + } + sv.Value = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + func awsAwsjson11_deserializeOpDocumentPutImageOutput(v **PutImageOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) @@ -13455,6 +15555,125 @@ func awsAwsjson11_deserializeOpDocumentUntagResourceOutput(v **UntagResourceOutp return nil } +func awsAwsjson11_deserializeOpDocumentUpdatePullThroughCacheRuleOutput(v **UpdatePullThroughCacheRuleOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *UpdatePullThroughCacheRuleOutput + if *v == nil { + sv = &UpdatePullThroughCacheRuleOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "credentialArn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected CredentialArn to be of type string, got %T instead", value) + } + sv.CredentialArn = ptr.String(jtv) + } + + case "ecrRepositoryPrefix": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PullThroughCacheRuleRepositoryPrefix to be of type string, got %T instead", value) + } + sv.EcrRepositoryPrefix = ptr.String(jtv) + } + + case "registryId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected RegistryId to be of type string, got %T instead", value) + } + sv.RegistryId = ptr.String(jtv) + } + + case "updatedAt": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.UpdatedAt = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected UpdatedTimestamp to be a JSON Number, got %T instead", value) + + } + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentUpdateRepositoryCreationTemplateOutput(v **UpdateRepositoryCreationTemplateOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *UpdateRepositoryCreationTemplateOutput + if *v == nil { + sv = &UpdateRepositoryCreationTemplateOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "registryId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected RegistryId to be of type string, got %T instead", value) + } + sv.RegistryId = ptr.String(jtv) + } + + case "repositoryCreationTemplate": + if err := awsAwsjson11_deserializeDocumentRepositoryCreationTemplate(&sv.RepositoryCreationTemplate, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + func awsAwsjson11_deserializeOpDocumentUploadLayerPartOutput(v **UploadLayerPartOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) @@ -13525,3 +15744,117 @@ func awsAwsjson11_deserializeOpDocumentUploadLayerPartOutput(v **UploadLayerPart *v = sv return nil } + +func awsAwsjson11_deserializeOpDocumentValidatePullThroughCacheRuleOutput(v **ValidatePullThroughCacheRuleOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *ValidatePullThroughCacheRuleOutput + if *v == nil { + sv = &ValidatePullThroughCacheRuleOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "credentialArn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected CredentialArn to be of type string, got %T instead", value) + } + sv.CredentialArn = ptr.String(jtv) + } + + case "ecrRepositoryPrefix": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PullThroughCacheRuleRepositoryPrefix to be of type string, got %T instead", value) + } + sv.EcrRepositoryPrefix = ptr.String(jtv) + } + + case "failure": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PTCValidateFailure to be of type string, got %T instead", value) + } + sv.Failure = ptr.String(jtv) + } + + case "isValid": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected IsPTCRuleValid to be of type *bool, got %T instead", value) + } + sv.IsValid = jtv + } + + case "registryId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected RegistryId to be of type string, got %T instead", value) + } + sv.RegistryId = ptr.String(jtv) + } + + case "upstreamRegistryUrl": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected Url to be of type string, got %T instead", value) + } + sv.UpstreamRegistryUrl = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +type protocolErrorInfo struct { + Type string `json:"__type"` + Message string + Code any // nonstandard for awsjson but some services do present the type here +} + +func getProtocolErrorInfo(decoder *json.Decoder) (protocolErrorInfo, error) { + var errInfo protocolErrorInfo + if err := decoder.Decode(&errInfo); err != nil { + if err == io.EOF { + return errInfo, nil + } + return errInfo, err + } + + return errInfo, nil +} + +func resolveProtocolErrorType(headerType string, bodyInfo protocolErrorInfo) (string, bool) { + if len(headerType) != 0 { + return headerType, true + } else if len(bodyInfo.Type) != 0 { + return bodyInfo.Type, true + } else if code, ok := bodyInfo.Code.(string); ok && len(code) != 0 { + return code, true + } + return "", false +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/doc.go index cd150610d4..7223cce0fc 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/doc.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/doc.go @@ -1,16 +1,20 @@ // Code generated by smithy-go-codegen DO NOT EDIT. // Package ecr provides the API client, operations, and parameter types for Amazon -// EC2 Container Registry. +// Elastic Container Registry. // -// Amazon Elastic Container Registry Amazon Elastic Container Registry (Amazon -// ECR) is a managed container image registry service. Customers can use the -// familiar Docker CLI, or their preferred client, to push, pull, and manage -// images. Amazon ECR provides a secure, scalable, and reliable registry for your -// Docker or Open Container Initiative (OCI) images. Amazon ECR supports private -// repositories with resource-based permissions using IAM so that specific users or -// Amazon EC2 instances can access repositories and images. Amazon ECR has service -// endpoints in each supported Region. For more information, see Amazon ECR -// endpoints (https://docs.aws.amazon.com/general/latest/gr/ecr.html) in the Amazon -// Web Services General Reference. +// # Amazon Elastic Container Registry +// +// Amazon Elastic Container Registry (Amazon ECR) is a managed container image +// registry service. Customers can use the familiar Docker CLI, or their preferred +// client, to push, pull, and manage images. Amazon ECR provides a secure, +// scalable, and reliable registry for your Docker or Open Container Initiative +// (OCI) images. Amazon ECR supports private repositories with resource-based +// permissions using IAM so that specific users or Amazon EC2 instances can access +// repositories and images. +// +// Amazon ECR has service endpoints in each supported Region. For more +// information, see [Amazon ECR endpoints]in the Amazon Web Services General Reference. +// +// [Amazon ECR endpoints]: https://docs.aws.amazon.com/general/latest/gr/ecr.html package ecr diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/endpoints.go index 8d169bdb22..c593447cd6 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/endpoints.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/endpoints.go @@ -8,14 +8,19 @@ import ( "fmt" "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + internalConfig "github.com/aws/aws-sdk-go-v2/internal/configsources" + "github.com/aws/aws-sdk-go-v2/internal/endpoints" "github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn" internalendpoints "github.com/aws/aws-sdk-go-v2/service/ecr/internal/endpoints" + smithyauth "github.com/aws/smithy-go/auth" smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" "github.com/aws/smithy-go/ptr" + "github.com/aws/smithy-go/tracing" smithyhttp "github.com/aws/smithy-go/transport/http" "net/http" "net/url" + "os" "strings" ) @@ -194,70 +199,29 @@ func resolveEndpointResolverV2(options *Options) { } } -// Utility function to aid with translating pseudo-regions to classical regions -// with the appropriate setting indicated by the pseudo-region -func mapPseudoRegion(pr string) (region string, fips aws.FIPSEndpointState) { - const fipsInfix = "-fips-" - const fipsPrefix = "fips-" - const fipsSuffix = "-fips" - - if strings.Contains(pr, fipsInfix) || - strings.Contains(pr, fipsPrefix) || - strings.Contains(pr, fipsSuffix) { - region = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll( - pr, fipsInfix, "-"), fipsPrefix, ""), fipsSuffix, "") - fips = aws.FIPSEndpointStateEnabled - } else { - region = pr +func resolveBaseEndpoint(cfg aws.Config, o *Options) { + if cfg.BaseEndpoint != nil { + o.BaseEndpoint = cfg.BaseEndpoint } - return region, fips -} - -// builtInParameterResolver is the interface responsible for resolving BuiltIn -// values during the sourcing of EndpointParameters -type builtInParameterResolver interface { - ResolveBuiltIns(*EndpointParameters) error -} - -// builtInResolver resolves modeled BuiltIn values using only the members defined -// below. -type builtInResolver struct { - // The AWS region used to dispatch the request. - Region string - - // Sourced BuiltIn value in a historical enabled or disabled state. - UseDualStack aws.DualStackEndpointState + _, g := os.LookupEnv("AWS_ENDPOINT_URL") + _, s := os.LookupEnv("AWS_ENDPOINT_URL_ECR") - // Sourced BuiltIn value in a historical enabled or disabled state. - UseFIPS aws.FIPSEndpointState + if g && !s { + return + } - // Base endpoint that can potentially be modified during Endpoint resolution. - Endpoint *string + value, found, err := internalConfig.ResolveServiceBaseEndpoint(context.Background(), "ECR", cfg.ConfigSources) + if found && err == nil { + o.BaseEndpoint = &value + } } -// Invoked at runtime to resolve BuiltIn Values. Only resolution code specific to -// each BuiltIn value is generated. -func (b *builtInResolver) ResolveBuiltIns(params *EndpointParameters) error { - - region, _ := mapPseudoRegion(b.Region) - if len(region) == 0 { - return fmt.Errorf("Could not resolve AWS::Region") - } else { - params.Region = aws.String(region) - } - if b.UseDualStack == aws.DualStackEndpointStateEnabled { - params.UseDualStack = aws.Bool(true) - } else { - params.UseDualStack = aws.Bool(false) +func bindRegion(region string) *string { + if region == "" { + return nil } - if b.UseFIPS == aws.FIPSEndpointStateEnabled { - params.UseFIPS = aws.Bool(true) - } else { - params.UseFIPS = aws.Bool(false) - } - params.Endpoint = b.Endpoint - return nil + return aws.String(endpoints.MapFIPSRegion(region)) } // EndpointParameters provides the parameters that influence how endpoints are @@ -325,6 +289,17 @@ func (p EndpointParameters) WithDefaults() EndpointParameters { return p } +type stringSlice []string + +func (s stringSlice) Get(i int) *string { + if i < 0 || i >= len(s) { + return nil + } + + v := s[i] + return &v +} + // EndpointResolverV2 provides the interface for resolving service endpoints. type EndpointResolverV2 interface { // ResolveEndpoint attempts to resolve the endpoint with the provided options, @@ -410,8 +385,8 @@ func (r *resolver) ResolveEndpoint( } } if _UseFIPS == true { - if true == _PartitionResult.SupportsFIPS { - if "aws" == _PartitionResult.Name { + if _PartitionResult.SupportsFIPS == true { + if _PartitionResult.Name == "aws" { uriString := func() string { var out strings.Builder out.WriteString("https://ecr-fips.") @@ -430,7 +405,7 @@ func (r *resolver) ResolveEndpoint( Headers: http.Header{}, }, nil } - if "aws-us-gov" == _PartitionResult.Name { + if _PartitionResult.Name == "aws-us-gov" { uriString := func() string { var out strings.Builder out.WriteString("https://ecr-fips.") @@ -516,3 +491,85 @@ func (r *resolver) ResolveEndpoint( } return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Missing Region") } + +type endpointParamsBinder interface { + bindEndpointParams(*EndpointParameters) +} + +func bindEndpointParams(ctx context.Context, input interface{}, options Options) *EndpointParameters { + params := &EndpointParameters{} + + params.Region = bindRegion(options.Region) + params.UseDualStack = aws.Bool(options.EndpointOptions.UseDualStackEndpoint == aws.DualStackEndpointStateEnabled) + params.UseFIPS = aws.Bool(options.EndpointOptions.UseFIPSEndpoint == aws.FIPSEndpointStateEnabled) + params.Endpoint = options.BaseEndpoint + + if b, ok := input.(endpointParamsBinder); ok { + b.bindEndpointParams(params) + } + + return params +} + +type resolveEndpointV2Middleware struct { + options Options +} + +func (*resolveEndpointV2Middleware) ID() string { + return "ResolveEndpointV2" +} + +func (m *resolveEndpointV2Middleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "ResolveEndpoint") + defer span.End() + + if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { + return next.HandleFinalize(ctx, in) + } + + req, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) + } + + if m.options.EndpointResolverV2 == nil { + return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") + } + + params := bindEndpointParams(ctx, getOperationInput(ctx), m.options) + endpt, err := timeOperationMetric(ctx, "client.call.resolve_endpoint_duration", + func() (smithyendpoints.Endpoint, error) { + return m.options.EndpointResolverV2.ResolveEndpoint(ctx, *params) + }) + if err != nil { + return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) + } + + span.SetProperty("client.call.resolved_endpoint", endpt.URI.String()) + + if endpt.URI.RawPath == "" && req.URL.RawPath != "" { + endpt.URI.RawPath = endpt.URI.Path + } + req.URL.Scheme = endpt.URI.Scheme + req.URL.Host = endpt.URI.Host + req.URL.Path = smithyhttp.JoinPath(endpt.URI.Path, req.URL.Path) + req.URL.RawPath = smithyhttp.JoinPath(endpt.URI.RawPath, req.URL.RawPath) + for k := range endpt.Headers { + req.Header.Set(k, endpt.Headers.Get(k)) + } + + rscheme := getResolvedAuthScheme(ctx) + if rscheme == nil { + return out, metadata, fmt.Errorf("no resolved auth scheme") + } + + opts, _ := smithyauth.GetAuthOptions(&endpt.Properties) + for _, o := range opts { + rscheme.SignerProperties.SetAll(&o.SignerProperties) + } + + span.End() + return next.HandleFinalize(ctx, in) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/generated.json b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/generated.json index 0b78f9a898..ed8ecd06af 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/generated.json +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/generated.json @@ -3,9 +3,7 @@ "github.com/aws/aws-sdk-go-v2": "v1.4.0", "github.com/aws/aws-sdk-go-v2/internal/configsources": "v0.0.0-00010101000000-000000000000", "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2": "v2.0.0-00010101000000-000000000000", - "github.com/aws/smithy-go": "v1.4.0", - "github.com/google/go-cmp": "v0.5.4", - "github.com/jmespath/go-jmespath": "v0.4.0" + "github.com/aws/smithy-go": "v1.4.0" }, "files": [ "api_client.go", @@ -17,10 +15,12 @@ "api_op_CompleteLayerUpload.go", "api_op_CreatePullThroughCacheRule.go", "api_op_CreateRepository.go", + "api_op_CreateRepositoryCreationTemplate.go", "api_op_DeleteLifecyclePolicy.go", "api_op_DeletePullThroughCacheRule.go", "api_op_DeleteRegistryPolicy.go", "api_op_DeleteRepository.go", + "api_op_DeleteRepositoryCreationTemplate.go", "api_op_DeleteRepositoryPolicy.go", "api_op_DescribeImageReplicationStatus.go", "api_op_DescribeImageScanFindings.go", @@ -28,6 +28,8 @@ "api_op_DescribePullThroughCacheRules.go", "api_op_DescribeRegistry.go", "api_op_DescribeRepositories.go", + "api_op_DescribeRepositoryCreationTemplates.go", + "api_op_GetAccountSetting.go", "api_op_GetAuthorizationToken.go", "api_op_GetDownloadUrlForLayer.go", "api_op_GetLifecyclePolicy.go", @@ -38,6 +40,7 @@ "api_op_InitiateLayerUpload.go", "api_op_ListImages.go", "api_op_ListTagsForResource.go", + "api_op_PutAccountSetting.go", "api_op_PutImage.go", "api_op_PutImageScanningConfiguration.go", "api_op_PutImageTagMutability.go", @@ -50,16 +53,23 @@ "api_op_StartLifecyclePolicyPreview.go", "api_op_TagResource.go", "api_op_UntagResource.go", + "api_op_UpdatePullThroughCacheRule.go", + "api_op_UpdateRepositoryCreationTemplate.go", "api_op_UploadLayerPart.go", + "api_op_ValidatePullThroughCacheRule.go", + "auth.go", "deserializers.go", "doc.go", "endpoints.go", + "endpoints_config_test.go", "endpoints_test.go", "generated.json", "internal/endpoints/endpoints.go", "internal/endpoints/endpoints_test.go", + "options.go", "protocol_test.go", "serializers.go", + "snapshot_test.go", "types/enums.go", "types/errors.go", "types/types.go", diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/go_module_metadata.go index f6cad4479b..0adcf28e30 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/go_module_metadata.go @@ -3,4 +3,4 @@ package ecr // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.20.2" +const goModuleVersion = "1.40.3" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/internal/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/internal/endpoints/endpoints.go index ca046cf69c..ebf04b8807 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/internal/endpoints/endpoints.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/internal/endpoints/endpoints.go @@ -94,7 +94,7 @@ var partitionRegexp = struct { AwsUsGov *regexp.Regexp }{ - Aws: regexp.MustCompile("^(us|eu|ap|sa|ca|me|af|il)\\-\\w+\\-\\d+$"), + Aws: regexp.MustCompile("^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$"), AwsCn: regexp.MustCompile("^cn\\-\\w+\\-\\d+$"), AwsIso: regexp.MustCompile("^us\\-iso\\-\\w+\\-\\d+$"), AwsIsoB: regexp.MustCompile("^us\\-isob\\-\\w+\\-\\d+$"), @@ -147,6 +147,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "af-south-1", }, }, + endpoints.EndpointKey{ + Region: "af-south-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.af-south-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "af-south-1", + }, + }, endpoints.EndpointKey{ Region: "ap-east-1", }: endpoints.Endpoint{ @@ -155,6 +164,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "ap-east-1", }, }, + endpoints.EndpointKey{ + Region: "ap-east-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.ap-east-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "ap-east-1", + }, + }, endpoints.EndpointKey{ Region: "ap-northeast-1", }: endpoints.Endpoint{ @@ -163,6 +181,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "ap-northeast-1", }, }, + endpoints.EndpointKey{ + Region: "ap-northeast-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.ap-northeast-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "ap-northeast-1", + }, + }, endpoints.EndpointKey{ Region: "ap-northeast-2", }: endpoints.Endpoint{ @@ -171,6 +198,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "ap-northeast-2", }, }, + endpoints.EndpointKey{ + Region: "ap-northeast-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.ap-northeast-2.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "ap-northeast-2", + }, + }, endpoints.EndpointKey{ Region: "ap-northeast-3", }: endpoints.Endpoint{ @@ -179,6 +215,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "ap-northeast-3", }, }, + endpoints.EndpointKey{ + Region: "ap-northeast-3", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.ap-northeast-3.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "ap-northeast-3", + }, + }, endpoints.EndpointKey{ Region: "ap-south-1", }: endpoints.Endpoint{ @@ -187,6 +232,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "ap-south-1", }, }, + endpoints.EndpointKey{ + Region: "ap-south-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.ap-south-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "ap-south-1", + }, + }, endpoints.EndpointKey{ Region: "ap-south-2", }: endpoints.Endpoint{ @@ -195,6 +249,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "ap-south-2", }, }, + endpoints.EndpointKey{ + Region: "ap-south-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.ap-south-2.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "ap-south-2", + }, + }, endpoints.EndpointKey{ Region: "ap-southeast-1", }: endpoints.Endpoint{ @@ -203,6 +266,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "ap-southeast-1", }, }, + endpoints.EndpointKey{ + Region: "ap-southeast-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.ap-southeast-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "ap-southeast-1", + }, + }, endpoints.EndpointKey{ Region: "ap-southeast-2", }: endpoints.Endpoint{ @@ -211,6 +283,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "ap-southeast-2", }, }, + endpoints.EndpointKey{ + Region: "ap-southeast-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.ap-southeast-2.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "ap-southeast-2", + }, + }, endpoints.EndpointKey{ Region: "ap-southeast-3", }: endpoints.Endpoint{ @@ -219,6 +300,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "ap-southeast-3", }, }, + endpoints.EndpointKey{ + Region: "ap-southeast-3", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.ap-southeast-3.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "ap-southeast-3", + }, + }, endpoints.EndpointKey{ Region: "ap-southeast-4", }: endpoints.Endpoint{ @@ -227,6 +317,49 @@ var defaultPartitions = endpoints.Partitions{ Region: "ap-southeast-4", }, }, + endpoints.EndpointKey{ + Region: "ap-southeast-4", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.ap-southeast-4.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "ap-southeast-4", + }, + }, + endpoints.EndpointKey{ + Region: "ap-southeast-5", + }: endpoints.Endpoint{ + Hostname: "api.ecr.ap-southeast-5.amazonaws.com", + CredentialScope: endpoints.CredentialScope{ + Region: "ap-southeast-5", + }, + }, + endpoints.EndpointKey{ + Region: "ap-southeast-5", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.ap-southeast-5.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "ap-southeast-5", + }, + }, + endpoints.EndpointKey{ + Region: "ap-southeast-7", + }: endpoints.Endpoint{ + Hostname: "api.ecr.ap-southeast-7.amazonaws.com", + CredentialScope: endpoints.CredentialScope{ + Region: "ap-southeast-7", + }, + }, + endpoints.EndpointKey{ + Region: "ap-southeast-7", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.ap-southeast-7.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "ap-southeast-7", + }, + }, endpoints.EndpointKey{ Region: "ca-central-1", }: endpoints.Endpoint{ @@ -235,6 +368,32 @@ var defaultPartitions = endpoints.Partitions{ Region: "ca-central-1", }, }, + endpoints.EndpointKey{ + Region: "ca-central-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.ca-central-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "ca-central-1", + }, + }, + endpoints.EndpointKey{ + Region: "ca-west-1", + }: endpoints.Endpoint{ + Hostname: "api.ecr.ca-west-1.amazonaws.com", + CredentialScope: endpoints.CredentialScope{ + Region: "ca-west-1", + }, + }, + endpoints.EndpointKey{ + Region: "ca-west-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.ca-west-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "ca-west-1", + }, + }, endpoints.EndpointKey{ Region: "dkr-us-east-1", }: endpoints.Endpoint{ @@ -315,6 +474,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "eu-central-1", }, }, + endpoints.EndpointKey{ + Region: "eu-central-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.eu-central-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "eu-central-1", + }, + }, endpoints.EndpointKey{ Region: "eu-central-2", }: endpoints.Endpoint{ @@ -323,6 +491,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "eu-central-2", }, }, + endpoints.EndpointKey{ + Region: "eu-central-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.eu-central-2.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "eu-central-2", + }, + }, endpoints.EndpointKey{ Region: "eu-north-1", }: endpoints.Endpoint{ @@ -331,6 +508,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "eu-north-1", }, }, + endpoints.EndpointKey{ + Region: "eu-north-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.eu-north-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "eu-north-1", + }, + }, endpoints.EndpointKey{ Region: "eu-south-1", }: endpoints.Endpoint{ @@ -339,6 +525,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "eu-south-1", }, }, + endpoints.EndpointKey{ + Region: "eu-south-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.eu-south-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "eu-south-1", + }, + }, endpoints.EndpointKey{ Region: "eu-south-2", }: endpoints.Endpoint{ @@ -347,6 +542,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "eu-south-2", }, }, + endpoints.EndpointKey{ + Region: "eu-south-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.eu-south-2.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "eu-south-2", + }, + }, endpoints.EndpointKey{ Region: "eu-west-1", }: endpoints.Endpoint{ @@ -355,6 +559,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "eu-west-1", }, }, + endpoints.EndpointKey{ + Region: "eu-west-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.eu-west-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "eu-west-1", + }, + }, endpoints.EndpointKey{ Region: "eu-west-2", }: endpoints.Endpoint{ @@ -363,6 +576,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "eu-west-2", }, }, + endpoints.EndpointKey{ + Region: "eu-west-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.eu-west-2.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "eu-west-2", + }, + }, endpoints.EndpointKey{ Region: "eu-west-3", }: endpoints.Endpoint{ @@ -371,6 +593,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "eu-west-3", }, }, + endpoints.EndpointKey{ + Region: "eu-west-3", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.eu-west-3.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "eu-west-3", + }, + }, endpoints.EndpointKey{ Region: "fips-dkr-us-east-1", }: endpoints.Endpoint{ @@ -451,6 +682,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "il-central-1", }, }, + endpoints.EndpointKey{ + Region: "il-central-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.il-central-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "il-central-1", + }, + }, endpoints.EndpointKey{ Region: "me-central-1", }: endpoints.Endpoint{ @@ -459,6 +699,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "me-central-1", }, }, + endpoints.EndpointKey{ + Region: "me-central-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.me-central-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "me-central-1", + }, + }, endpoints.EndpointKey{ Region: "me-south-1", }: endpoints.Endpoint{ @@ -467,6 +716,32 @@ var defaultPartitions = endpoints.Partitions{ Region: "me-south-1", }, }, + endpoints.EndpointKey{ + Region: "me-south-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.me-south-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "me-south-1", + }, + }, + endpoints.EndpointKey{ + Region: "mx-central-1", + }: endpoints.Endpoint{ + Hostname: "api.ecr.mx-central-1.amazonaws.com", + CredentialScope: endpoints.CredentialScope{ + Region: "mx-central-1", + }, + }, + endpoints.EndpointKey{ + Region: "mx-central-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.mx-central-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "mx-central-1", + }, + }, endpoints.EndpointKey{ Region: "sa-east-1", }: endpoints.Endpoint{ @@ -475,6 +750,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "sa-east-1", }, }, + endpoints.EndpointKey{ + Region: "sa-east-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.sa-east-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "sa-east-1", + }, + }, endpoints.EndpointKey{ Region: "us-east-1", }: endpoints.Endpoint{ @@ -492,6 +776,24 @@ var defaultPartitions = endpoints.Partitions{ Region: "us-east-1", }, }, + endpoints.EndpointKey{ + Region: "us-east-1", + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "ecr-fips.us-east-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "us-east-1", + }, + }, + endpoints.EndpointKey{ + Region: "us-east-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.us-east-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "us-east-1", + }, + }, endpoints.EndpointKey{ Region: "us-east-2", }: endpoints.Endpoint{ @@ -509,6 +811,24 @@ var defaultPartitions = endpoints.Partitions{ Region: "us-east-2", }, }, + endpoints.EndpointKey{ + Region: "us-east-2", + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "ecr-fips.us-east-2.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "us-east-2", + }, + }, + endpoints.EndpointKey{ + Region: "us-east-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.us-east-2.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "us-east-2", + }, + }, endpoints.EndpointKey{ Region: "us-west-1", }: endpoints.Endpoint{ @@ -526,6 +846,24 @@ var defaultPartitions = endpoints.Partitions{ Region: "us-west-1", }, }, + endpoints.EndpointKey{ + Region: "us-west-1", + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "ecr-fips.us-west-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "us-west-1", + }, + }, + endpoints.EndpointKey{ + Region: "us-west-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.us-west-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "us-west-1", + }, + }, endpoints.EndpointKey{ Region: "us-west-2", }: endpoints.Endpoint{ @@ -543,6 +881,24 @@ var defaultPartitions = endpoints.Partitions{ Region: "us-west-2", }, }, + endpoints.EndpointKey{ + Region: "us-west-2", + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "ecr-fips.us-west-2.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "us-west-2", + }, + }, + endpoints.EndpointKey{ + Region: "us-west-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.us-west-2.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "us-west-2", + }, + }, }, }, { @@ -588,6 +944,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "cn-north-1", }, }, + endpoints.EndpointKey{ + Region: "cn-north-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.cn-north-1.api.amazonwebservices.com.cn", + CredentialScope: endpoints.CredentialScope{ + Region: "cn-north-1", + }, + }, endpoints.EndpointKey{ Region: "cn-northwest-1", }: endpoints.Endpoint{ @@ -596,6 +961,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "cn-northwest-1", }, }, + endpoints.EndpointKey{ + Region: "cn-northwest-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.cn-northwest-1.api.amazonwebservices.com.cn", + CredentialScope: endpoints.CredentialScope{ + Region: "cn-northwest-1", + }, + }, }, }, { @@ -709,6 +1083,24 @@ var defaultPartitions = endpoints.Partitions{ }, RegionRegex: partitionRegexp.AwsIsoF, IsRegionalized: true, + Endpoints: endpoints.Endpoints{ + endpoints.EndpointKey{ + Region: "us-isof-east-1", + }: endpoints.Endpoint{ + Hostname: "api.ecr.us-isof-east-1.csp.hci.ic.gov", + CredentialScope: endpoints.CredentialScope{ + Region: "us-isof-east-1", + }, + }, + endpoints.EndpointKey{ + Region: "us-isof-south-1", + }: endpoints.Endpoint{ + Hostname: "api.ecr.us-isof-south-1.csp.hci.ic.gov", + CredentialScope: endpoints.CredentialScope{ + Region: "us-isof-south-1", + }, + }, + }, }, { ID: "aws-us-gov", @@ -834,6 +1226,24 @@ var defaultPartitions = endpoints.Partitions{ Region: "us-gov-east-1", }, }, + endpoints.EndpointKey{ + Region: "us-gov-east-1", + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "ecr-fips.us-gov-east-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "us-gov-east-1", + }, + }, + endpoints.EndpointKey{ + Region: "us-gov-east-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.us-gov-east-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "us-gov-east-1", + }, + }, endpoints.EndpointKey{ Region: "us-gov-west-1", }: endpoints.Endpoint{ @@ -851,6 +1261,24 @@ var defaultPartitions = endpoints.Partitions{ Region: "us-gov-west-1", }, }, + endpoints.EndpointKey{ + Region: "us-gov-west-1", + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "ecr-fips.us-gov-west-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "us-gov-west-1", + }, + }, + endpoints.EndpointKey{ + Region: "us-gov-west-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr.us-gov-west-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/options.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/options.go new file mode 100644 index 0000000000..8d993c73e2 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/options.go @@ -0,0 +1,232 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package ecr + +import ( + "context" + "github.com/aws/aws-sdk-go-v2/aws" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + internalauthsmithy "github.com/aws/aws-sdk-go-v2/internal/auth/smithy" + smithyauth "github.com/aws/smithy-go/auth" + "github.com/aws/smithy-go/logging" + "github.com/aws/smithy-go/metrics" + "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" + "net/http" +) + +type HTTPClient interface { + Do(*http.Request) (*http.Response, error) +} + +type Options struct { + // Set of options to modify how an operation is invoked. These apply to all + // operations invoked for this client. Use functional options on operation call to + // modify this list for per operation behavior. + APIOptions []func(*middleware.Stack) error + + // The optional application specific identifier appended to the User-Agent header. + AppID string + + // This endpoint will be given as input to an EndpointResolverV2. It is used for + // providing a custom base endpoint that is subject to modifications by the + // processing EndpointResolverV2. + BaseEndpoint *string + + // Configures the events that will be sent to the configured logger. + ClientLogMode aws.ClientLogMode + + // The credentials object to use when signing requests. + Credentials aws.CredentialsProvider + + // The configuration DefaultsMode that the SDK should use when constructing the + // clients initial default settings. + DefaultsMode aws.DefaultsMode + + // The endpoint options to be used when attempting to resolve an endpoint. + EndpointOptions EndpointResolverOptions + + // The service endpoint resolver. + // + // Deprecated: Deprecated: EndpointResolver and WithEndpointResolver. Providing a + // value for this field will likely prevent you from using any endpoint-related + // service features released after the introduction of EndpointResolverV2 and + // BaseEndpoint. + // + // To migrate an EndpointResolver implementation that uses a custom endpoint, set + // the client option BaseEndpoint instead. + EndpointResolver EndpointResolver + + // Resolves the endpoint used for a particular service operation. This should be + // used over the deprecated EndpointResolver. + EndpointResolverV2 EndpointResolverV2 + + // Signature Version 4 (SigV4) Signer + HTTPSignerV4 HTTPSignerV4 + + // The logger writer interface to write logging messages to. + Logger logging.Logger + + // The client meter provider. + MeterProvider metrics.MeterProvider + + // The region to send requests to. (Required) + Region string + + // RetryMaxAttempts specifies the maximum number attempts an API client will call + // an operation that fails with a retryable error. A value of 0 is ignored, and + // will not be used to configure the API client created default retryer, or modify + // per operation call's retry max attempts. + // + // If specified in an operation call's functional options with a value that is + // different than the constructed client's Options, the Client's Retryer will be + // wrapped to use the operation's specific RetryMaxAttempts value. + RetryMaxAttempts int + + // RetryMode specifies the retry mode the API client will be created with, if + // Retryer option is not also specified. + // + // When creating a new API Clients this member will only be used if the Retryer + // Options member is nil. This value will be ignored if Retryer is not nil. + // + // Currently does not support per operation call overrides, may in the future. + RetryMode aws.RetryMode + + // Retryer guides how HTTP requests should be retried in case of recoverable + // failures. When nil the API client will use a default retryer. The kind of + // default retry created by the API client can be changed with the RetryMode + // option. + Retryer aws.Retryer + + // The RuntimeEnvironment configuration, only populated if the DefaultsMode is set + // to DefaultsModeAuto and is initialized using config.LoadDefaultConfig . You + // should not populate this structure programmatically, or rely on the values here + // within your applications. + RuntimeEnvironment aws.RuntimeEnvironment + + // The client tracer provider. + TracerProvider tracing.TracerProvider + + // The initial DefaultsMode used when the client options were constructed. If the + // DefaultsMode was set to aws.DefaultsModeAuto this will store what the resolved + // value was at that point in time. + // + // Currently does not support per operation call overrides, may in the future. + resolvedDefaultsMode aws.DefaultsMode + + // The HTTP client to invoke API calls with. Defaults to client's default HTTP + // implementation if nil. + HTTPClient HTTPClient + + // The auth scheme resolver which determines how to authenticate for each + // operation. + AuthSchemeResolver AuthSchemeResolver + + // The list of auth schemes supported by the client. + AuthSchemes []smithyhttp.AuthScheme +} + +// Copy creates a clone where the APIOptions list is deep copied. +func (o Options) Copy() Options { + to := o + to.APIOptions = make([]func(*middleware.Stack) error, len(o.APIOptions)) + copy(to.APIOptions, o.APIOptions) + + return to +} + +func (o Options) GetIdentityResolver(schemeID string) smithyauth.IdentityResolver { + if schemeID == "aws.auth#sigv4" { + return getSigV4IdentityResolver(o) + } + if schemeID == "smithy.api#noAuth" { + return &smithyauth.AnonymousIdentityResolver{} + } + return nil +} + +// WithAPIOptions returns a functional option for setting the Client's APIOptions +// option. +func WithAPIOptions(optFns ...func(*middleware.Stack) error) func(*Options) { + return func(o *Options) { + o.APIOptions = append(o.APIOptions, optFns...) + } +} + +// Deprecated: EndpointResolver and WithEndpointResolver. Providing a value for +// this field will likely prevent you from using any endpoint-related service +// features released after the introduction of EndpointResolverV2 and BaseEndpoint. +// +// To migrate an EndpointResolver implementation that uses a custom endpoint, set +// the client option BaseEndpoint instead. +func WithEndpointResolver(v EndpointResolver) func(*Options) { + return func(o *Options) { + o.EndpointResolver = v + } +} + +// WithEndpointResolverV2 returns a functional option for setting the Client's +// EndpointResolverV2 option. +func WithEndpointResolverV2(v EndpointResolverV2) func(*Options) { + return func(o *Options) { + o.EndpointResolverV2 = v + } +} + +func getSigV4IdentityResolver(o Options) smithyauth.IdentityResolver { + if o.Credentials != nil { + return &internalauthsmithy.CredentialsProviderAdapter{Provider: o.Credentials} + } + return nil +} + +// WithSigV4SigningName applies an override to the authentication workflow to +// use the given signing name for SigV4-authenticated operations. +// +// This is an advanced setting. The value here is FINAL, taking precedence over +// the resolved signing name from both auth scheme resolution and endpoint +// resolution. +func WithSigV4SigningName(name string) func(*Options) { + fn := func(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, + ) { + return next.HandleInitialize(awsmiddleware.SetSigningName(ctx, name), in) + } + return func(o *Options) { + o.APIOptions = append(o.APIOptions, func(s *middleware.Stack) error { + return s.Initialize.Add( + middleware.InitializeMiddlewareFunc("withSigV4SigningName", fn), + middleware.Before, + ) + }) + } +} + +// WithSigV4SigningRegion applies an override to the authentication workflow to +// use the given signing region for SigV4-authenticated operations. +// +// This is an advanced setting. The value here is FINAL, taking precedence over +// the resolved signing region from both auth scheme resolution and endpoint +// resolution. +func WithSigV4SigningRegion(region string) func(*Options) { + fn := func(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, + ) { + return next.HandleInitialize(awsmiddleware.SetSigningRegion(ctx, region), in) + } + return func(o *Options) { + o.APIOptions = append(o.APIOptions, func(s *middleware.Stack) error { + return s.Initialize.Add( + middleware.InitializeMiddlewareFunc("withSigV4SigningRegion", fn), + middleware.Before, + ) + }) + } +} + +func ignoreAnonymousAuth(options *Options) { + if aws.IsCredentialsProvider(options.Credentials, (*aws.AnonymousCredentials)(nil)) { + options.Credentials = nil + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/serializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/serializers.go index e513d0312f..db1b0d7a16 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/serializers.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/serializers.go @@ -11,6 +11,7 @@ import ( "github.com/aws/smithy-go/encoding/httpbinding" smithyjson "github.com/aws/smithy-go/encoding/json" "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/tracing" smithyhttp "github.com/aws/smithy-go/transport/http" "path" ) @@ -25,6 +26,10 @@ func (*awsAwsjson11_serializeOpBatchCheckLayerAvailability) ID() string { func (m *awsAwsjson11_serializeOpBatchCheckLayerAvailability) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -67,6 +72,8 @@ func (m *awsAwsjson11_serializeOpBatchCheckLayerAvailability) HandleSerialize(ct } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -80,6 +87,10 @@ func (*awsAwsjson11_serializeOpBatchDeleteImage) ID() string { func (m *awsAwsjson11_serializeOpBatchDeleteImage) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -122,6 +133,8 @@ func (m *awsAwsjson11_serializeOpBatchDeleteImage) HandleSerialize(ctx context.C } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -135,6 +148,10 @@ func (*awsAwsjson11_serializeOpBatchGetImage) ID() string { func (m *awsAwsjson11_serializeOpBatchGetImage) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -177,6 +194,8 @@ func (m *awsAwsjson11_serializeOpBatchGetImage) HandleSerialize(ctx context.Cont } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -190,6 +209,10 @@ func (*awsAwsjson11_serializeOpBatchGetRepositoryScanningConfiguration) ID() str func (m *awsAwsjson11_serializeOpBatchGetRepositoryScanningConfiguration) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -232,6 +255,8 @@ func (m *awsAwsjson11_serializeOpBatchGetRepositoryScanningConfiguration) Handle } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -245,6 +270,10 @@ func (*awsAwsjson11_serializeOpCompleteLayerUpload) ID() string { func (m *awsAwsjson11_serializeOpCompleteLayerUpload) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -287,6 +316,8 @@ func (m *awsAwsjson11_serializeOpCompleteLayerUpload) HandleSerialize(ctx contex } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -300,6 +331,10 @@ func (*awsAwsjson11_serializeOpCreatePullThroughCacheRule) ID() string { func (m *awsAwsjson11_serializeOpCreatePullThroughCacheRule) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -342,6 +377,8 @@ func (m *awsAwsjson11_serializeOpCreatePullThroughCacheRule) HandleSerialize(ctx } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -355,6 +392,10 @@ func (*awsAwsjson11_serializeOpCreateRepository) ID() string { func (m *awsAwsjson11_serializeOpCreateRepository) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -397,6 +438,69 @@ func (m *awsAwsjson11_serializeOpCreateRepository) HandleSerialize(ctx context.C } in.Request = request + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpCreateRepositoryCreationTemplate struct { +} + +func (*awsAwsjson11_serializeOpCreateRepositoryCreationTemplate) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpCreateRepositoryCreationTemplate) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*CreateRepositoryCreationTemplateInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AmazonEC2ContainerRegistry_V20150921.CreateRepositoryCreationTemplate") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentCreateRepositoryCreationTemplateInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -410,6 +514,10 @@ func (*awsAwsjson11_serializeOpDeleteLifecyclePolicy) ID() string { func (m *awsAwsjson11_serializeOpDeleteLifecyclePolicy) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -452,6 +560,8 @@ func (m *awsAwsjson11_serializeOpDeleteLifecyclePolicy) HandleSerialize(ctx cont } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -465,6 +575,10 @@ func (*awsAwsjson11_serializeOpDeletePullThroughCacheRule) ID() string { func (m *awsAwsjson11_serializeOpDeletePullThroughCacheRule) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -507,6 +621,8 @@ func (m *awsAwsjson11_serializeOpDeletePullThroughCacheRule) HandleSerialize(ctx } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -520,6 +636,10 @@ func (*awsAwsjson11_serializeOpDeleteRegistryPolicy) ID() string { func (m *awsAwsjson11_serializeOpDeleteRegistryPolicy) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -562,6 +682,8 @@ func (m *awsAwsjson11_serializeOpDeleteRegistryPolicy) HandleSerialize(ctx conte } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -575,6 +697,10 @@ func (*awsAwsjson11_serializeOpDeleteRepository) ID() string { func (m *awsAwsjson11_serializeOpDeleteRepository) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -617,6 +743,69 @@ func (m *awsAwsjson11_serializeOpDeleteRepository) HandleSerialize(ctx context.C } in.Request = request + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDeleteRepositoryCreationTemplate struct { +} + +func (*awsAwsjson11_serializeOpDeleteRepositoryCreationTemplate) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDeleteRepositoryCreationTemplate) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DeleteRepositoryCreationTemplateInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AmazonEC2ContainerRegistry_V20150921.DeleteRepositoryCreationTemplate") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDeleteRepositoryCreationTemplateInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -630,6 +819,10 @@ func (*awsAwsjson11_serializeOpDeleteRepositoryPolicy) ID() string { func (m *awsAwsjson11_serializeOpDeleteRepositoryPolicy) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -672,6 +865,8 @@ func (m *awsAwsjson11_serializeOpDeleteRepositoryPolicy) HandleSerialize(ctx con } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -685,6 +880,10 @@ func (*awsAwsjson11_serializeOpDescribeImageReplicationStatus) ID() string { func (m *awsAwsjson11_serializeOpDescribeImageReplicationStatus) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -727,6 +926,8 @@ func (m *awsAwsjson11_serializeOpDescribeImageReplicationStatus) HandleSerialize } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -740,6 +941,10 @@ func (*awsAwsjson11_serializeOpDescribeImages) ID() string { func (m *awsAwsjson11_serializeOpDescribeImages) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -782,6 +987,8 @@ func (m *awsAwsjson11_serializeOpDescribeImages) HandleSerialize(ctx context.Con } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -795,6 +1002,10 @@ func (*awsAwsjson11_serializeOpDescribeImageScanFindings) ID() string { func (m *awsAwsjson11_serializeOpDescribeImageScanFindings) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -837,6 +1048,8 @@ func (m *awsAwsjson11_serializeOpDescribeImageScanFindings) HandleSerialize(ctx } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -850,6 +1063,10 @@ func (*awsAwsjson11_serializeOpDescribePullThroughCacheRules) ID() string { func (m *awsAwsjson11_serializeOpDescribePullThroughCacheRules) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -892,6 +1109,8 @@ func (m *awsAwsjson11_serializeOpDescribePullThroughCacheRules) HandleSerialize( } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -905,6 +1124,10 @@ func (*awsAwsjson11_serializeOpDescribeRegistry) ID() string { func (m *awsAwsjson11_serializeOpDescribeRegistry) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -947,6 +1170,8 @@ func (m *awsAwsjson11_serializeOpDescribeRegistry) HandleSerialize(ctx context.C } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -960,6 +1185,10 @@ func (*awsAwsjson11_serializeOpDescribeRepositories) ID() string { func (m *awsAwsjson11_serializeOpDescribeRepositories) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1002,6 +1231,130 @@ func (m *awsAwsjson11_serializeOpDescribeRepositories) HandleSerialize(ctx conte } in.Request = request + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDescribeRepositoryCreationTemplates struct { +} + +func (*awsAwsjson11_serializeOpDescribeRepositoryCreationTemplates) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDescribeRepositoryCreationTemplates) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DescribeRepositoryCreationTemplatesInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AmazonEC2ContainerRegistry_V20150921.DescribeRepositoryCreationTemplates") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDescribeRepositoryCreationTemplatesInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpGetAccountSetting struct { +} + +func (*awsAwsjson11_serializeOpGetAccountSetting) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpGetAccountSetting) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetAccountSettingInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AmazonEC2ContainerRegistry_V20150921.GetAccountSetting") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentGetAccountSettingInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1015,6 +1368,10 @@ func (*awsAwsjson11_serializeOpGetAuthorizationToken) ID() string { func (m *awsAwsjson11_serializeOpGetAuthorizationToken) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1057,6 +1414,8 @@ func (m *awsAwsjson11_serializeOpGetAuthorizationToken) HandleSerialize(ctx cont } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1070,6 +1429,10 @@ func (*awsAwsjson11_serializeOpGetDownloadUrlForLayer) ID() string { func (m *awsAwsjson11_serializeOpGetDownloadUrlForLayer) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1112,6 +1475,8 @@ func (m *awsAwsjson11_serializeOpGetDownloadUrlForLayer) HandleSerialize(ctx con } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1125,6 +1490,10 @@ func (*awsAwsjson11_serializeOpGetLifecyclePolicy) ID() string { func (m *awsAwsjson11_serializeOpGetLifecyclePolicy) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1167,6 +1536,8 @@ func (m *awsAwsjson11_serializeOpGetLifecyclePolicy) HandleSerialize(ctx context } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1180,6 +1551,10 @@ func (*awsAwsjson11_serializeOpGetLifecyclePolicyPreview) ID() string { func (m *awsAwsjson11_serializeOpGetLifecyclePolicyPreview) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1222,6 +1597,8 @@ func (m *awsAwsjson11_serializeOpGetLifecyclePolicyPreview) HandleSerialize(ctx } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1235,6 +1612,10 @@ func (*awsAwsjson11_serializeOpGetRegistryPolicy) ID() string { func (m *awsAwsjson11_serializeOpGetRegistryPolicy) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1277,6 +1658,8 @@ func (m *awsAwsjson11_serializeOpGetRegistryPolicy) HandleSerialize(ctx context. } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1290,6 +1673,10 @@ func (*awsAwsjson11_serializeOpGetRegistryScanningConfiguration) ID() string { func (m *awsAwsjson11_serializeOpGetRegistryScanningConfiguration) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1332,6 +1719,8 @@ func (m *awsAwsjson11_serializeOpGetRegistryScanningConfiguration) HandleSeriali } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1345,6 +1734,10 @@ func (*awsAwsjson11_serializeOpGetRepositoryPolicy) ID() string { func (m *awsAwsjson11_serializeOpGetRepositoryPolicy) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1387,6 +1780,8 @@ func (m *awsAwsjson11_serializeOpGetRepositoryPolicy) HandleSerialize(ctx contex } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1400,6 +1795,10 @@ func (*awsAwsjson11_serializeOpInitiateLayerUpload) ID() string { func (m *awsAwsjson11_serializeOpInitiateLayerUpload) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1442,6 +1841,8 @@ func (m *awsAwsjson11_serializeOpInitiateLayerUpload) HandleSerialize(ctx contex } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1455,6 +1856,10 @@ func (*awsAwsjson11_serializeOpListImages) ID() string { func (m *awsAwsjson11_serializeOpListImages) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1497,6 +1902,8 @@ func (m *awsAwsjson11_serializeOpListImages) HandleSerialize(ctx context.Context } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1510,6 +1917,10 @@ func (*awsAwsjson11_serializeOpListTagsForResource) ID() string { func (m *awsAwsjson11_serializeOpListTagsForResource) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1552,6 +1963,69 @@ func (m *awsAwsjson11_serializeOpListTagsForResource) HandleSerialize(ctx contex } in.Request = request + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpPutAccountSetting struct { +} + +func (*awsAwsjson11_serializeOpPutAccountSetting) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpPutAccountSetting) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*PutAccountSettingInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AmazonEC2ContainerRegistry_V20150921.PutAccountSetting") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentPutAccountSettingInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1565,6 +2039,10 @@ func (*awsAwsjson11_serializeOpPutImage) ID() string { func (m *awsAwsjson11_serializeOpPutImage) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1607,6 +2085,8 @@ func (m *awsAwsjson11_serializeOpPutImage) HandleSerialize(ctx context.Context, } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1620,6 +2100,10 @@ func (*awsAwsjson11_serializeOpPutImageScanningConfiguration) ID() string { func (m *awsAwsjson11_serializeOpPutImageScanningConfiguration) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1662,6 +2146,8 @@ func (m *awsAwsjson11_serializeOpPutImageScanningConfiguration) HandleSerialize( } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1675,6 +2161,10 @@ func (*awsAwsjson11_serializeOpPutImageTagMutability) ID() string { func (m *awsAwsjson11_serializeOpPutImageTagMutability) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1717,6 +2207,8 @@ func (m *awsAwsjson11_serializeOpPutImageTagMutability) HandleSerialize(ctx cont } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1730,6 +2222,10 @@ func (*awsAwsjson11_serializeOpPutLifecyclePolicy) ID() string { func (m *awsAwsjson11_serializeOpPutLifecyclePolicy) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1772,6 +2268,8 @@ func (m *awsAwsjson11_serializeOpPutLifecyclePolicy) HandleSerialize(ctx context } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1785,6 +2283,10 @@ func (*awsAwsjson11_serializeOpPutRegistryPolicy) ID() string { func (m *awsAwsjson11_serializeOpPutRegistryPolicy) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1827,6 +2329,8 @@ func (m *awsAwsjson11_serializeOpPutRegistryPolicy) HandleSerialize(ctx context. } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1840,6 +2344,10 @@ func (*awsAwsjson11_serializeOpPutRegistryScanningConfiguration) ID() string { func (m *awsAwsjson11_serializeOpPutRegistryScanningConfiguration) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1882,6 +2390,8 @@ func (m *awsAwsjson11_serializeOpPutRegistryScanningConfiguration) HandleSeriali } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1895,6 +2405,10 @@ func (*awsAwsjson11_serializeOpPutReplicationConfiguration) ID() string { func (m *awsAwsjson11_serializeOpPutReplicationConfiguration) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1937,6 +2451,8 @@ func (m *awsAwsjson11_serializeOpPutReplicationConfiguration) HandleSerialize(ct } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1950,6 +2466,10 @@ func (*awsAwsjson11_serializeOpSetRepositoryPolicy) ID() string { func (m *awsAwsjson11_serializeOpSetRepositoryPolicy) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1992,6 +2512,8 @@ func (m *awsAwsjson11_serializeOpSetRepositoryPolicy) HandleSerialize(ctx contex } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -2005,6 +2527,10 @@ func (*awsAwsjson11_serializeOpStartImageScan) ID() string { func (m *awsAwsjson11_serializeOpStartImageScan) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -2047,6 +2573,8 @@ func (m *awsAwsjson11_serializeOpStartImageScan) HandleSerialize(ctx context.Con } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -2060,6 +2588,10 @@ func (*awsAwsjson11_serializeOpStartLifecyclePolicyPreview) ID() string { func (m *awsAwsjson11_serializeOpStartLifecyclePolicyPreview) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -2102,6 +2634,8 @@ func (m *awsAwsjson11_serializeOpStartLifecyclePolicyPreview) HandleSerialize(ct } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -2115,6 +2649,10 @@ func (*awsAwsjson11_serializeOpTagResource) ID() string { func (m *awsAwsjson11_serializeOpTagResource) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -2157,6 +2695,8 @@ func (m *awsAwsjson11_serializeOpTagResource) HandleSerialize(ctx context.Contex } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -2170,6 +2710,10 @@ func (*awsAwsjson11_serializeOpUntagResource) ID() string { func (m *awsAwsjson11_serializeOpUntagResource) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -2212,25 +2756,31 @@ func (m *awsAwsjson11_serializeOpUntagResource) HandleSerialize(ctx context.Cont } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } -type awsAwsjson11_serializeOpUploadLayerPart struct { +type awsAwsjson11_serializeOpUpdatePullThroughCacheRule struct { } -func (*awsAwsjson11_serializeOpUploadLayerPart) ID() string { +func (*awsAwsjson11_serializeOpUpdatePullThroughCacheRule) ID() string { return "OperationSerializer" } -func (m *awsAwsjson11_serializeOpUploadLayerPart) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( +func (m *awsAwsjson11_serializeOpUpdatePullThroughCacheRule) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} } - input, ok := in.Parameters.(*UploadLayerPartInput) + input, ok := in.Parameters.(*UpdatePullThroughCacheRuleInput) _ = input if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} @@ -2251,10 +2801,10 @@ func (m *awsAwsjson11_serializeOpUploadLayerPart) HandleSerialize(ctx context.Co return out, metadata, &smithy.SerializationError{Err: err} } httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") - httpBindingEncoder.SetHeader("X-Amz-Target").String("AmazonEC2ContainerRegistry_V20150921.UploadLayerPart") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AmazonEC2ContainerRegistry_V20150921.UpdatePullThroughCacheRule") jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentUploadLayerPartInput(input, jsonEncoder.Value); err != nil { + if err := awsAwsjson11_serializeOpDocumentUpdatePullThroughCacheRuleInput(input, jsonEncoder.Value); err != nil { return out, metadata, &smithy.SerializationError{Err: err} } @@ -2267,14 +2817,199 @@ func (m *awsAwsjson11_serializeOpUploadLayerPart) HandleSerialize(ctx context.Co } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } -func awsAwsjson11_serializeDocumentBatchedOperationLayerDigestList(v []string, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - for i := range v { - av := array.Value() +type awsAwsjson11_serializeOpUpdateRepositoryCreationTemplate struct { +} + +func (*awsAwsjson11_serializeOpUpdateRepositoryCreationTemplate) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpUpdateRepositoryCreationTemplate) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*UpdateRepositoryCreationTemplateInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AmazonEC2ContainerRegistry_V20150921.UpdateRepositoryCreationTemplate") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentUpdateRepositoryCreationTemplateInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpUploadLayerPart struct { +} + +func (*awsAwsjson11_serializeOpUploadLayerPart) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpUploadLayerPart) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*UploadLayerPartInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AmazonEC2ContainerRegistry_V20150921.UploadLayerPart") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentUploadLayerPartInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpValidatePullThroughCacheRule struct { +} + +func (*awsAwsjson11_serializeOpValidatePullThroughCacheRule) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpValidatePullThroughCacheRule) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ValidatePullThroughCacheRuleInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AmazonEC2ContainerRegistry_V20150921.ValidatePullThroughCacheRule") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentValidatePullThroughCacheRuleInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} +func awsAwsjson11_serializeDocumentBatchedOperationLayerDigestList(v []string, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() av.String(v[i]) } return nil @@ -2309,6 +3044,23 @@ func awsAwsjson11_serializeDocumentEncryptionConfiguration(v *types.EncryptionCo return nil } +func awsAwsjson11_serializeDocumentEncryptionConfigurationForRepositoryCreationTemplate(v *types.EncryptionConfigurationForRepositoryCreationTemplate, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if len(v.EncryptionType) > 0 { + ok := object.Key("encryptionType") + ok.String(string(v.EncryptionType)) + } + + if v.KmsKey != nil { + ok := object.Key("kmsKey") + ok.String(*v.KmsKey) + } + + return nil +} + func awsAwsjson11_serializeDocumentGetAuthorizationTokenRegistryIdList(v []string, value smithyjson.Value) error { array := value.Array() defer array.Close() @@ -2408,6 +3160,17 @@ func awsAwsjson11_serializeDocumentMediaTypeList(v []string, value smithyjson.Va return nil } +func awsAwsjson11_serializeDocumentPrefixList(v []string, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(v[i]) + } + return nil +} + func awsAwsjson11_serializeDocumentPullThroughCacheRuleRepositoryPrefixList(v []string, value smithyjson.Value) error { array := value.Array() defer array.Close() @@ -2419,6 +3182,17 @@ func awsAwsjson11_serializeDocumentPullThroughCacheRuleRepositoryPrefixList(v [] return nil } +func awsAwsjson11_serializeDocumentRCTAppliedForList(v []types.RCTAppliedFor, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(string(v[i])) + } + return nil +} + func awsAwsjson11_serializeDocumentRegistryScanningRule(v *types.RegistryScanningRule, value smithyjson.Value) error { object := value.Object() defer object.Close() @@ -2778,6 +3552,11 @@ func awsAwsjson11_serializeOpDocumentCreatePullThroughCacheRuleInput(v *CreatePu object := value.Object() defer object.Close() + if v.CredentialArn != nil { + ok := object.Key("credentialArn") + ok.String(*v.CredentialArn) + } + if v.EcrRepositoryPrefix != nil { ok := object.Key("ecrRepositoryPrefix") ok.String(*v.EcrRepositoryPrefix) @@ -2788,6 +3567,11 @@ func awsAwsjson11_serializeOpDocumentCreatePullThroughCacheRuleInput(v *CreatePu ok.String(*v.RegistryId) } + if len(v.UpstreamRegistry) > 0 { + ok := object.Key("upstreamRegistry") + ok.String(string(v.UpstreamRegistry)) + } + if v.UpstreamRegistryUrl != nil { ok := object.Key("upstreamRegistryUrl") ok.String(*v.UpstreamRegistryUrl) @@ -2796,6 +3580,64 @@ func awsAwsjson11_serializeOpDocumentCreatePullThroughCacheRuleInput(v *CreatePu return nil } +func awsAwsjson11_serializeOpDocumentCreateRepositoryCreationTemplateInput(v *CreateRepositoryCreationTemplateInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AppliedFor != nil { + ok := object.Key("appliedFor") + if err := awsAwsjson11_serializeDocumentRCTAppliedForList(v.AppliedFor, ok); err != nil { + return err + } + } + + if v.CustomRoleArn != nil { + ok := object.Key("customRoleArn") + ok.String(*v.CustomRoleArn) + } + + if v.Description != nil { + ok := object.Key("description") + ok.String(*v.Description) + } + + if v.EncryptionConfiguration != nil { + ok := object.Key("encryptionConfiguration") + if err := awsAwsjson11_serializeDocumentEncryptionConfigurationForRepositoryCreationTemplate(v.EncryptionConfiguration, ok); err != nil { + return err + } + } + + if len(v.ImageTagMutability) > 0 { + ok := object.Key("imageTagMutability") + ok.String(string(v.ImageTagMutability)) + } + + if v.LifecyclePolicy != nil { + ok := object.Key("lifecyclePolicy") + ok.String(*v.LifecyclePolicy) + } + + if v.Prefix != nil { + ok := object.Key("prefix") + ok.String(*v.Prefix) + } + + if v.RepositoryPolicy != nil { + ok := object.Key("repositoryPolicy") + ok.String(*v.RepositoryPolicy) + } + + if v.ResourceTags != nil { + ok := object.Key("resourceTags") + if err := awsAwsjson11_serializeDocumentTagList(v.ResourceTags, ok); err != nil { + return err + } + } + + return nil +} + func awsAwsjson11_serializeOpDocumentCreateRepositoryInput(v *CreateRepositoryInput, value smithyjson.Value) error { object := value.Object() defer object.Close() @@ -2880,6 +3722,18 @@ func awsAwsjson11_serializeOpDocumentDeleteRegistryPolicyInput(v *DeleteRegistry return nil } +func awsAwsjson11_serializeOpDocumentDeleteRepositoryCreationTemplateInput(v *DeleteRepositoryCreationTemplateInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Prefix != nil { + ok := object.Key("prefix") + ok.String(*v.Prefix) + } + + return nil +} + func awsAwsjson11_serializeOpDocumentDeleteRepositoryInput(v *DeleteRepositoryInput, value smithyjson.Value) error { object := value.Object() defer object.Close() @@ -3083,6 +3937,42 @@ func awsAwsjson11_serializeOpDocumentDescribeRepositoriesInput(v *DescribeReposi return nil } +func awsAwsjson11_serializeOpDocumentDescribeRepositoryCreationTemplatesInput(v *DescribeRepositoryCreationTemplatesInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.MaxResults != nil { + ok := object.Key("maxResults") + ok.Integer(*v.MaxResults) + } + + if v.NextToken != nil { + ok := object.Key("nextToken") + ok.String(*v.NextToken) + } + + if v.Prefixes != nil { + ok := object.Key("prefixes") + if err := awsAwsjson11_serializeDocumentPrefixList(v.Prefixes, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentGetAccountSettingInput(v *GetAccountSettingInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Name != nil { + ok := object.Key("name") + ok.String(*v.Name) + } + + return nil +} + func awsAwsjson11_serializeOpDocumentGetAuthorizationTokenInput(v *GetAuthorizationTokenInput, value smithyjson.Value) error { object := value.Object() defer object.Close() @@ -3271,6 +4161,23 @@ func awsAwsjson11_serializeOpDocumentListTagsForResourceInput(v *ListTagsForReso return nil } +func awsAwsjson11_serializeOpDocumentPutAccountSettingInput(v *PutAccountSettingInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Name != nil { + ok := object.Key("name") + ok.String(*v.Name) + } + + if v.Value != nil { + ok := object.Key("value") + ok.String(*v.Value) + } + + return nil +} + func awsAwsjson11_serializeOpDocumentPutImageInput(v *PutImageInput, value smithyjson.Value) error { object := value.Object() defer object.Close() @@ -3532,6 +4439,86 @@ func awsAwsjson11_serializeOpDocumentUntagResourceInput(v *UntagResourceInput, v return nil } +func awsAwsjson11_serializeOpDocumentUpdatePullThroughCacheRuleInput(v *UpdatePullThroughCacheRuleInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.CredentialArn != nil { + ok := object.Key("credentialArn") + ok.String(*v.CredentialArn) + } + + if v.EcrRepositoryPrefix != nil { + ok := object.Key("ecrRepositoryPrefix") + ok.String(*v.EcrRepositoryPrefix) + } + + if v.RegistryId != nil { + ok := object.Key("registryId") + ok.String(*v.RegistryId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentUpdateRepositoryCreationTemplateInput(v *UpdateRepositoryCreationTemplateInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AppliedFor != nil { + ok := object.Key("appliedFor") + if err := awsAwsjson11_serializeDocumentRCTAppliedForList(v.AppliedFor, ok); err != nil { + return err + } + } + + if v.CustomRoleArn != nil { + ok := object.Key("customRoleArn") + ok.String(*v.CustomRoleArn) + } + + if v.Description != nil { + ok := object.Key("description") + ok.String(*v.Description) + } + + if v.EncryptionConfiguration != nil { + ok := object.Key("encryptionConfiguration") + if err := awsAwsjson11_serializeDocumentEncryptionConfigurationForRepositoryCreationTemplate(v.EncryptionConfiguration, ok); err != nil { + return err + } + } + + if len(v.ImageTagMutability) > 0 { + ok := object.Key("imageTagMutability") + ok.String(string(v.ImageTagMutability)) + } + + if v.LifecyclePolicy != nil { + ok := object.Key("lifecyclePolicy") + ok.String(*v.LifecyclePolicy) + } + + if v.Prefix != nil { + ok := object.Key("prefix") + ok.String(*v.Prefix) + } + + if v.RepositoryPolicy != nil { + ok := object.Key("repositoryPolicy") + ok.String(*v.RepositoryPolicy) + } + + if v.ResourceTags != nil { + ok := object.Key("resourceTags") + if err := awsAwsjson11_serializeDocumentTagList(v.ResourceTags, ok); err != nil { + return err + } + } + + return nil +} + func awsAwsjson11_serializeOpDocumentUploadLayerPartInput(v *UploadLayerPartInput, value smithyjson.Value) error { object := value.Object() defer object.Close() @@ -3568,3 +4555,20 @@ func awsAwsjson11_serializeOpDocumentUploadLayerPartInput(v *UploadLayerPartInpu return nil } + +func awsAwsjson11_serializeOpDocumentValidatePullThroughCacheRuleInput(v *ValidatePullThroughCacheRuleInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.EcrRepositoryPrefix != nil { + ok := object.Key("ecrRepositoryPrefix") + ok.String(*v.EcrRepositoryPrefix) + } + + if v.RegistryId != nil { + ok := object.Key("registryId") + ok.String(*v.RegistryId) + } + + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/types/enums.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/types/enums.go index d782c4ec9c..52470b4ebe 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/types/enums.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/types/enums.go @@ -6,17 +6,20 @@ type EncryptionType string // Enum values for EncryptionType const ( - EncryptionTypeAes256 EncryptionType = "AES256" - EncryptionTypeKms EncryptionType = "KMS" + EncryptionTypeAes256 EncryptionType = "AES256" + EncryptionTypeKms EncryptionType = "KMS" + EncryptionTypeKmsDsse EncryptionType = "KMS_DSSE" ) // Values returns all known values for EncryptionType. Note that this can be -// expanded in the future, and so it is only as up to date as the client. The -// ordering of this slice is not guaranteed to be stable across updates. +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. func (EncryptionType) Values() []EncryptionType { return []EncryptionType{ "AES256", "KMS", + "KMS_DSSE", } } @@ -33,8 +36,9 @@ const ( ) // Values returns all known values for FindingSeverity. Note that this can be -// expanded in the future, and so it is only as up to date as the client. The -// ordering of this slice is not guaranteed to be stable across updates. +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. func (FindingSeverity) Values() []FindingSeverity { return []FindingSeverity{ "INFORMATIONAL", @@ -54,8 +58,9 @@ const ( ) // Values returns all known values for ImageActionType. Note that this can be -// expanded in the future, and so it is only as up to date as the client. The -// ordering of this slice is not guaranteed to be stable across updates. +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. func (ImageActionType) Values() []ImageActionType { return []ImageActionType{ "EXPIRE", @@ -73,11 +78,15 @@ const ( ImageFailureCodeMissingDigestAndTag ImageFailureCode = "MissingDigestAndTag" ImageFailureCodeImageReferencedByManifestList ImageFailureCode = "ImageReferencedByManifestList" ImageFailureCodeKmsError ImageFailureCode = "KmsError" + ImageFailureCodeUpstreamAccessDenied ImageFailureCode = "UpstreamAccessDenied" + ImageFailureCodeUpstreamTooManyRequests ImageFailureCode = "UpstreamTooManyRequests" + ImageFailureCodeUpstreamUnavailable ImageFailureCode = "UpstreamUnavailable" ) // Values returns all known values for ImageFailureCode. Note that this can be -// expanded in the future, and so it is only as up to date as the client. The -// ordering of this slice is not guaranteed to be stable across updates. +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. func (ImageFailureCode) Values() []ImageFailureCode { return []ImageFailureCode{ "InvalidImageDigest", @@ -87,6 +96,9 @@ func (ImageFailureCode) Values() []ImageFailureCode { "MissingDigestAndTag", "ImageReferencedByManifestList", "KmsError", + "UpstreamAccessDenied", + "UpstreamTooManyRequests", + "UpstreamUnavailable", } } @@ -99,8 +111,9 @@ const ( ) // Values returns all known values for ImageTagMutability. Note that this can be -// expanded in the future, and so it is only as up to date as the client. The -// ordering of this slice is not guaranteed to be stable across updates. +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. func (ImageTagMutability) Values() []ImageTagMutability { return []ImageTagMutability{ "MUTABLE", @@ -117,8 +130,9 @@ const ( ) // Values returns all known values for LayerAvailability. Note that this can be -// expanded in the future, and so it is only as up to date as the client. The -// ordering of this slice is not guaranteed to be stable across updates. +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. func (LayerAvailability) Values() []LayerAvailability { return []LayerAvailability{ "AVAILABLE", @@ -135,8 +149,9 @@ const ( ) // Values returns all known values for LayerFailureCode. Note that this can be -// expanded in the future, and so it is only as up to date as the client. The -// ordering of this slice is not guaranteed to be stable across updates. +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. func (LayerFailureCode) Values() []LayerFailureCode { return []LayerFailureCode{ "InvalidLayerDigest", @@ -156,8 +171,9 @@ const ( // Values returns all known values for LifecyclePolicyPreviewStatus. Note that // this can be expanded in the future, and so it is only as up to date as the -// client. The ordering of this slice is not guaranteed to be stable across -// updates. +// client. +// +// The ordering of this slice is not guaranteed to be stable across updates. func (LifecyclePolicyPreviewStatus) Values() []LifecyclePolicyPreviewStatus { return []LifecyclePolicyPreviewStatus{ "IN_PROGRESS", @@ -167,6 +183,25 @@ func (LifecyclePolicyPreviewStatus) Values() []LifecyclePolicyPreviewStatus { } } +type RCTAppliedFor string + +// Enum values for RCTAppliedFor +const ( + RCTAppliedForReplication RCTAppliedFor = "REPLICATION" + RCTAppliedForPullThroughCache RCTAppliedFor = "PULL_THROUGH_CACHE" +) + +// Values returns all known values for RCTAppliedFor. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (RCTAppliedFor) Values() []RCTAppliedFor { + return []RCTAppliedFor{ + "REPLICATION", + "PULL_THROUGH_CACHE", + } +} + type ReplicationStatus string // Enum values for ReplicationStatus @@ -177,8 +212,9 @@ const ( ) // Values returns all known values for ReplicationStatus. Note that this can be -// expanded in the future, and so it is only as up to date as the client. The -// ordering of this slice is not guaranteed to be stable across updates. +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. func (ReplicationStatus) Values() []ReplicationStatus { return []ReplicationStatus{ "IN_PROGRESS", @@ -195,8 +231,9 @@ const ( ) // Values returns all known values for RepositoryFilterType. Note that this can be -// expanded in the future, and so it is only as up to date as the client. The -// ordering of this slice is not guaranteed to be stable across updates. +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. func (RepositoryFilterType) Values() []RepositoryFilterType { return []RepositoryFilterType{ "PREFIX_MATCH", @@ -213,8 +250,9 @@ const ( ) // Values returns all known values for ScanFrequency. Note that this can be -// expanded in the future, and so it is only as up to date as the client. The -// ordering of this slice is not guaranteed to be stable across updates. +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. func (ScanFrequency) Values() []ScanFrequency { return []ScanFrequency{ "SCAN_ON_PUSH", @@ -232,8 +270,9 @@ const ( // Values returns all known values for ScanningConfigurationFailureCode. Note that // this can be expanded in the future, and so it is only as up to date as the -// client. The ordering of this slice is not guaranteed to be stable across -// updates. +// client. +// +// The ordering of this slice is not guaranteed to be stable across updates. func (ScanningConfigurationFailureCode) Values() []ScanningConfigurationFailureCode { return []ScanningConfigurationFailureCode{ "REPOSITORY_NOT_FOUND", @@ -249,8 +288,9 @@ const ( // Values returns all known values for ScanningRepositoryFilterType. Note that // this can be expanded in the future, and so it is only as up to date as the -// client. The ordering of this slice is not guaranteed to be stable across -// updates. +// client. +// +// The ordering of this slice is not guaranteed to be stable across updates. func (ScanningRepositoryFilterType) Values() []ScanningRepositoryFilterType { return []ScanningRepositoryFilterType{ "WILDCARD", @@ -272,8 +312,9 @@ const ( ) // Values returns all known values for ScanStatus. Note that this can be expanded -// in the future, and so it is only as up to date as the client. The ordering of -// this slice is not guaranteed to be stable across updates. +// in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. func (ScanStatus) Values() []ScanStatus { return []ScanStatus{ "IN_PROGRESS", @@ -296,8 +337,9 @@ const ( ) // Values returns all known values for ScanType. Note that this can be expanded in -// the future, and so it is only as up to date as the client. The ordering of this -// slice is not guaranteed to be stable across updates. +// the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. func (ScanType) Values() []ScanType { return []ScanType{ "BASIC", @@ -315,8 +357,9 @@ const ( ) // Values returns all known values for TagStatus. Note that this can be expanded -// in the future, and so it is only as up to date as the client. The ordering of -// this slice is not guaranteed to be stable across updates. +// in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. func (TagStatus) Values() []TagStatus { return []TagStatus{ "TAGGED", @@ -324,3 +367,32 @@ func (TagStatus) Values() []TagStatus { "ANY", } } + +type UpstreamRegistry string + +// Enum values for UpstreamRegistry +const ( + UpstreamRegistryEcrPublic UpstreamRegistry = "ecr-public" + UpstreamRegistryQuay UpstreamRegistry = "quay" + UpstreamRegistryK8s UpstreamRegistry = "k8s" + UpstreamRegistryDockerHub UpstreamRegistry = "docker-hub" + UpstreamRegistryGitHubContainerRegistry UpstreamRegistry = "github-container-registry" + UpstreamRegistryAzureContainerRegistry UpstreamRegistry = "azure-container-registry" + UpstreamRegistryGitLabContainerRegistry UpstreamRegistry = "gitlab-container-registry" +) + +// Values returns all known values for UpstreamRegistry. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (UpstreamRegistry) Values() []UpstreamRegistry { + return []UpstreamRegistry{ + "ecr-public", + "quay", + "k8s", + "docker-hub", + "github-container-registry", + "azure-container-registry", + "gitlab-container-registry", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/types/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/types/errors.go index 4b4782c5a5..9e1f90cf5f 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/types/errors.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/types/errors.go @@ -472,8 +472,10 @@ func (e *LifecyclePolicyPreviewNotFoundException) ErrorFault() smithy.ErrorFault } // The operation did not succeed because it would have exceeded a service limit -// for your account. For more information, see Amazon ECR service quotas (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service-quotas.html) -// in the Amazon Elastic Container Registry User Guide. +// for your account. For more information, see [Amazon ECR service quotas]in the Amazon Elastic Container +// Registry User Guide. +// +// [Amazon ECR service quotas]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/service-quotas.html type LimitExceededException struct { Message *string @@ -744,6 +746,33 @@ func (e *ScanNotFoundException) ErrorCode() string { } func (e *ScanNotFoundException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } +// The ARN of the secret specified in the pull through cache rule was not found. +// Update the pull through cache rule with a valid secret ARN and try again. +type SecretNotFoundException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *SecretNotFoundException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *SecretNotFoundException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *SecretNotFoundException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "SecretNotFoundException" + } + return *e.ErrorCodeOverride +} +func (e *SecretNotFoundException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + // These errors are usually caused by a server-side issue. type ServerException struct { Message *string @@ -770,6 +799,60 @@ func (e *ServerException) ErrorCode() string { } func (e *ServerException) ErrorFault() smithy.ErrorFault { return smithy.FaultServer } +// The repository creation template already exists. Specify a unique prefix and +// try again. +type TemplateAlreadyExistsException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *TemplateAlreadyExistsException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *TemplateAlreadyExistsException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *TemplateAlreadyExistsException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "TemplateAlreadyExistsException" + } + return *e.ErrorCodeOverride +} +func (e *TemplateAlreadyExistsException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// The specified repository creation template can't be found. Verify the registry +// ID and prefix and try again. +type TemplateNotFoundException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *TemplateNotFoundException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *TemplateNotFoundException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *TemplateNotFoundException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "TemplateNotFoundException" + } + return *e.ErrorCodeOverride +} +func (e *TemplateNotFoundException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + // The list of tags on the repository is over the limit. The maximum number of // tags that can be applied to a repository is 50. type TooManyTagsException struct { @@ -797,6 +880,117 @@ func (e *TooManyTagsException) ErrorCode() string { } func (e *TooManyTagsException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } +// The secret is unable to be accessed. Verify the resource permissions for the +// secret and try again. +type UnableToAccessSecretException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *UnableToAccessSecretException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *UnableToAccessSecretException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *UnableToAccessSecretException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "UnableToAccessSecretException" + } + return *e.ErrorCodeOverride +} +func (e *UnableToAccessSecretException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// The secret is accessible but is unable to be decrypted. Verify the resource +// permisisons and try again. +type UnableToDecryptSecretValueException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *UnableToDecryptSecretValueException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *UnableToDecryptSecretValueException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *UnableToDecryptSecretValueException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "UnableToDecryptSecretValueException" + } + return *e.ErrorCodeOverride +} +func (e *UnableToDecryptSecretValueException) ErrorFault() smithy.ErrorFault { + return smithy.FaultClient +} + +// The image or images were unable to be pulled using the pull through cache rule. +// This is usually caused because of an issue with the Secrets Manager secret +// containing the credentials for the upstream registry. +type UnableToGetUpstreamImageException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *UnableToGetUpstreamImageException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *UnableToGetUpstreamImageException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *UnableToGetUpstreamImageException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "UnableToGetUpstreamImageException" + } + return *e.ErrorCodeOverride +} +func (e *UnableToGetUpstreamImageException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// There was an issue getting the upstream layer matching the pull through cache +// rule. +type UnableToGetUpstreamLayerException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *UnableToGetUpstreamLayerException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *UnableToGetUpstreamLayerException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *UnableToGetUpstreamLayerException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "UnableToGetUpstreamLayerException" + } + return *e.ErrorCodeOverride +} +func (e *UnableToGetUpstreamLayerException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + // The image is of a type that cannot be scanned. type UnsupportedImageTypeException struct { Message *string diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/types/types.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/types/types.go index 1dbaf77259..7bab166264 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/types/types.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/types/types.go @@ -127,38 +127,50 @@ type CvssScoreDetails struct { // An object representing a filter on a DescribeImages operation. type DescribeImagesFilter struct { - // The tag status with which to filter your DescribeImages results. You can filter - // results based on whether they are TAGGED or UNTAGGED . + // The tag status with which to filter your DescribeImages results. You can filter results based + // on whether they are TAGGED or UNTAGGED . TagStatus TagStatus noSmithyDocumentSerde } // The encryption configuration for the repository. This determines how the -// contents of your repository are encrypted at rest. By default, when no -// encryption configuration is set or the AES256 encryption type is used, Amazon -// ECR uses server-side encryption with Amazon S3-managed encryption keys which -// encrypts your data at rest using an AES-256 encryption algorithm. This does not -// require any action on your part. For more control over the encryption of the -// contents of your repository, you can use server-side encryption with Key -// Management Service key stored in Key Management Service (KMS) to encrypt your -// images. For more information, see Amazon ECR encryption at rest (https://docs.aws.amazon.com/AmazonECR/latest/userguide/encryption-at-rest.html) -// in the Amazon Elastic Container Registry User Guide. +// contents of your repository are encrypted at rest. +// +// By default, when no encryption configuration is set or the AES256 encryption +// type is used, Amazon ECR uses server-side encryption with Amazon S3-managed +// encryption keys which encrypts your data at rest using an AES256 encryption +// algorithm. This does not require any action on your part. +// +// For more control over the encryption of the contents of your repository, you +// can use server-side encryption with Key Management Service key stored in Key +// Management Service (KMS) to encrypt your images. For more information, see [Amazon ECR encryption at rest]in +// the Amazon Elastic Container Registry User Guide. +// +// [Amazon ECR encryption at rest]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/encryption-at-rest.html type EncryptionConfiguration struct { - // The encryption type to use. If you use the KMS encryption type, the contents of - // the repository will be encrypted using server-side encryption with Key - // Management Service key stored in KMS. When you use KMS to encrypt your data, you - // can either use the default Amazon Web Services managed KMS key for Amazon ECR, - // or specify your own KMS key, which you already created. For more information, - // see Protecting data using server-side encryption with an KMS key stored in Key - // Management Service (SSE-KMS) (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html) - // in the Amazon Simple Storage Service Console Developer Guide. If you use the - // AES256 encryption type, Amazon ECR uses server-side encryption with Amazon - // S3-managed encryption keys which encrypts the images in the repository using an - // AES-256 encryption algorithm. For more information, see Protecting data using - // server-side encryption with Amazon S3-managed encryption keys (SSE-S3) (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingServerSideEncryption.html) - // in the Amazon Simple Storage Service Console Developer Guide. + // The encryption type to use. + // + // If you use the KMS encryption type, the contents of the repository will be + // encrypted using server-side encryption with Key Management Service key stored in + // KMS. When you use KMS to encrypt your data, you can either use the default + // Amazon Web Services managed KMS key for Amazon ECR, or specify your own KMS key, + // which you already created. + // + // If you use the KMS_DSSE encryption type, the contents of the repository will be + // encrypted with two layers of encryption using server-side encryption with the + // KMS Management Service key stored in KMS. Similar to the KMS encryption type, + // you can either use the default Amazon Web Services managed KMS key for Amazon + // ECR, or specify your own KMS key, which you've already created. + // + // If you use the AES256 encryption type, Amazon ECR uses server-side encryption + // with Amazon S3-managed encryption keys which encrypts the images in the + // repository using an AES256 encryption algorithm. + // + // For more information, see [Amazon ECR encryption at rest] in the Amazon Elastic Container Registry User Guide. + // + // [Amazon ECR encryption at rest]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/encryption-at-rest.html // // This member is required. EncryptionType EncryptionType @@ -172,6 +184,38 @@ type EncryptionConfiguration struct { noSmithyDocumentSerde } +// The encryption configuration to associate with the repository creation template. +type EncryptionConfigurationForRepositoryCreationTemplate struct { + + // The encryption type to use. + // + // If you use the KMS encryption type, the contents of the repository will be + // encrypted using server-side encryption with Key Management Service key stored in + // KMS. When you use KMS to encrypt your data, you can either use the default + // Amazon Web Services managed KMS key for Amazon ECR, or specify your own KMS key, + // which you already created. For more information, see [Protecting data using server-side encryption with an KMS key stored in Key Management Service (SSE-KMS)]in the Amazon Simple + // Storage Service Console Developer Guide. + // + // If you use the AES256 encryption type, Amazon ECR uses server-side encryption + // with Amazon S3-managed encryption keys which encrypts the images in the + // repository using an AES256 encryption algorithm. For more information, see [Protecting data using server-side encryption with Amazon S3-managed encryption keys (SSE-S3)]in + // the Amazon Simple Storage Service Console Developer Guide. + // + // [Protecting data using server-side encryption with Amazon S3-managed encryption keys (SSE-S3)]: https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingServerSideEncryption.html + // [Protecting data using server-side encryption with an KMS key stored in Key Management Service (SSE-KMS)]: https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html + // + // This member is required. + EncryptionType EncryptionType + + // If you use the KMS encryption type, specify the KMS key to use for encryption. + // The full ARN of the KMS key must be specified. The key must exist in the same + // Region as the repository. If no key is specified, the default Amazon Web + // Services managed KMS key for Amazon ECR will be used. + KmsKey *string + + noSmithyDocumentSerde +} + // The details of an enhanced image scan. This is returned when enhanced scanning // is enabled for your private registry. type EnhancedImageScanFinding struct { @@ -182,12 +226,21 @@ type EnhancedImageScanFinding struct { // The description of the finding. Description *string + // If a finding discovered in your environment has an exploit available. + ExploitAvailable *string + // The Amazon Resource Number (ARN) of the finding. FindingArn *string // The date and time that the finding was first observed. FirstObservedAt *time.Time + // Details on whether a fix is available through a version update. This value can + // be YES , NO , or PARTIAL . A PARTIAL fix means that some, but not all, of the + // packages identified in the finding have fixes available through updated + // versions. + FixAvailable *string + // The date and time that the finding was last observed. LastObservedAt *time.Time @@ -268,24 +321,29 @@ type ImageDetail struct { // The current state of the scan. ImageScanStatus *ImageScanStatus - // The size, in bytes, of the image in the repository. If the image is a manifest - // list, this will be the max size of all manifests in the list. Beginning with - // Docker version 1.9, the Docker client compresses image layers before pushing - // them to a V2 Docker registry. The output of the docker images command shows the - // uncompressed image size, so it may return a larger image size than the image - // sizes returned by DescribeImages . + // The size, in bytes, of the image in the repository. + // + // If the image is a manifest list, this will be the max size of all manifests in + // the list. + // + // Beginning with Docker version 1.9, the Docker client compresses image layers + // before pushing them to a V2 Docker registry. The output of the docker images + // command shows the uncompressed image size, so it may return a larger image size + // than the image sizes returned by DescribeImages. ImageSizeInBytes *int64 // The list of tags associated with this image. ImageTags []string // The date and time, expressed in standard JavaScript date format, when Amazon - // ECR recorded the last image pull. Amazon ECR refreshes the last image pull - // timestamp at least once every 24 hours. For example, if you pull an image once a - // day then the lastRecordedPullTime timestamp will indicate the exact time that - // the image was last pulled. However, if you pull an image once an hour, because - // Amazon ECR refreshes the lastRecordedPullTime timestamp at least once every 24 - // hours, the result may not be the exact time that the image was last pulled. + // ECR recorded the last image pull. + // + // Amazon ECR refreshes the last image pull timestamp at least once every 24 + // hours. For example, if you pull an image once a day then the + // lastRecordedPullTime timestamp will indicate the exact time that the image was + // last pulled. However, if you pull an image once an hour, because Amazon ECR + // refreshes the lastRecordedPullTime timestamp at least once every 24 hours, the + // result may not be the exact time that the image was last pulled. LastRecordedPullTime *time.Time // The Amazon Web Services account ID associated with the registry to which this @@ -407,8 +465,9 @@ type ImageScanningConfiguration struct { // The setting that determines whether images are scanned after being pushed to a // repository. If set to true , images will be scanned after being pushed. If this // parameter is not specified, it will default to false and images will not be - // scanned unless a scan is manually started with the API_StartImageScan (https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_StartImageScan.html) - // API. + // scanned unless a scan is manually started with the [API_StartImageScan]API. + // + // [API_StartImageScan]: https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_StartImageScan.html ScanOnPush bool noSmithyDocumentSerde @@ -513,8 +572,8 @@ type LifecyclePolicyRuleAction struct { // An object representing a filter on a ListImages operation. type ListImagesFilter struct { - // The tag status with which to filter your ListImages results. You can filter - // results based on whether they are TAGGED or UNTAGGED . + // The tag status with which to filter your ListImages results. You can filter results based + // on whether they are TAGGED or UNTAGGED . TagStatus TagStatus noSmithyDocumentSerde @@ -563,6 +622,10 @@ type PullThroughCacheRule struct { // The date and time the pull through cache was created. CreatedAt *time.Time + // The ARN of the Secrets Manager secret associated with the pull through cache + // rule. + CredentialArn *string + // The Amazon ECR repository prefix associated with the pull through cache rule. EcrRepositoryPrefix *string @@ -570,6 +633,14 @@ type PullThroughCacheRule struct { // through cache rule is associated with. RegistryId *string + // The date and time, in JavaScript date format, when the pull through cache rule + // was last updated. + UpdatedAt *time.Time + + // The name of the upstream source registry associated with the pull through cache + // rule. + UpstreamRegistry UpstreamRegistry + // The upstream registry URL associated with the pull through cache rule. UpstreamRegistryUrl *string @@ -715,6 +786,61 @@ type Repository struct { noSmithyDocumentSerde } +// The details of the repository creation template associated with the request. +type RepositoryCreationTemplate struct { + + // A list of enumerable Strings representing the repository creation scenarios + // that this template will apply towards. The two supported scenarios are + // PULL_THROUGH_CACHE and REPLICATION + AppliedFor []RCTAppliedFor + + // The date and time, in JavaScript date format, when the repository creation + // template was created. + CreatedAt *time.Time + + // The ARN of the role to be assumed by Amazon ECR. Amazon ECR will assume your + // supplied role when the customRoleArn is specified. When this field isn't + // specified, Amazon ECR will use the service-linked role for the repository + // creation template. + CustomRoleArn *string + + // The description associated with the repository creation template. + Description *string + + // The encryption configuration associated with the repository creation template. + EncryptionConfiguration *EncryptionConfigurationForRepositoryCreationTemplate + + // The tag mutability setting for the repository. If this parameter is omitted, + // the default setting of MUTABLE will be used which will allow image tags to be + // overwritten. If IMMUTABLE is specified, all image tags within the repository + // will be immutable which will prevent them from being overwritten. + ImageTagMutability ImageTagMutability + + // The lifecycle policy to use for repositories created using the template. + LifecyclePolicy *string + + // The repository namespace prefix associated with the repository creation + // template. + Prefix *string + + // he repository policy to apply to repositories created using the template. A + // repository policy is a permissions policy associated with a repository to + // control access permissions. + RepositoryPolicy *string + + // The metadata to apply to the repository to help you categorize and organize. + // Each tag consists of a key and an optional value, both of which you define. Tag + // keys can have a maximum character length of 128 characters, and tag values can + // have a maximum length of 256 characters. + ResourceTags []Tag + + // The date and time, in JavaScript date format, when the repository creation + // template was last updated. + UpdatedAt *time.Time + + noSmithyDocumentSerde +} + // The filter settings used with image replication. Specifying a repository filter // to a replication rule provides a method for controlling which repositories in a // private registry are replicated. If no filters are added, the contents of all @@ -803,8 +929,9 @@ type ResourceDetails struct { } // The details of a scanning repository filter. For more information on how to use -// filters, see Using filters (https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-scanning.html#image-scanning-filters) -// in the Amazon Elastic Container Registry User Guide. +// filters, see [Using filters]in the Amazon Elastic Container Registry User Guide. +// +// [Using filters]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-scanning.html#image-scanning-filters type ScanningRepositoryFilter struct { // The filter to use when scanning. @@ -861,6 +988,9 @@ type VulnerablePackage struct { // The file path of the vulnerable package. FilePath *string + // The version of the package that contains the vulnerability fix. + FixedInVersion *string + // The name of the vulnerable package. Name *string diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/validators.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/validators.go index 754611f1c8..930a3ccd83 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/validators.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecr/validators.go @@ -130,6 +130,26 @@ func (m *validateOpCreatePullThroughCacheRule) HandleInitialize(ctx context.Cont return next.HandleInitialize(ctx, in) } +type validateOpCreateRepositoryCreationTemplate struct { +} + +func (*validateOpCreateRepositoryCreationTemplate) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpCreateRepositoryCreationTemplate) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*CreateRepositoryCreationTemplateInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpCreateRepositoryCreationTemplateInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + type validateOpCreateRepository struct { } @@ -190,6 +210,26 @@ func (m *validateOpDeletePullThroughCacheRule) HandleInitialize(ctx context.Cont return next.HandleInitialize(ctx, in) } +type validateOpDeleteRepositoryCreationTemplate struct { +} + +func (*validateOpDeleteRepositoryCreationTemplate) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDeleteRepositoryCreationTemplate) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DeleteRepositoryCreationTemplateInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDeleteRepositoryCreationTemplateInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + type validateOpDeleteRepository struct { } @@ -290,6 +330,26 @@ func (m *validateOpDescribeImages) HandleInitialize(ctx context.Context, in midd return next.HandleInitialize(ctx, in) } +type validateOpGetAccountSetting struct { +} + +func (*validateOpGetAccountSetting) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetAccountSetting) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetAccountSettingInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetAccountSettingInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + type validateOpGetDownloadUrlForLayer struct { } @@ -430,6 +490,26 @@ func (m *validateOpListTagsForResource) HandleInitialize(ctx context.Context, in return next.HandleInitialize(ctx, in) } +type validateOpPutAccountSetting struct { +} + +func (*validateOpPutAccountSetting) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpPutAccountSetting) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*PutAccountSettingInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpPutAccountSettingInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + type validateOpPutImage struct { } @@ -670,6 +750,46 @@ func (m *validateOpUntagResource) HandleInitialize(ctx context.Context, in middl return next.HandleInitialize(ctx, in) } +type validateOpUpdatePullThroughCacheRule struct { +} + +func (*validateOpUpdatePullThroughCacheRule) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpUpdatePullThroughCacheRule) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*UpdatePullThroughCacheRuleInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpUpdatePullThroughCacheRuleInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpUpdateRepositoryCreationTemplate struct { +} + +func (*validateOpUpdateRepositoryCreationTemplate) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpUpdateRepositoryCreationTemplate) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*UpdateRepositoryCreationTemplateInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpUpdateRepositoryCreationTemplateInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + type validateOpUploadLayerPart struct { } @@ -690,6 +810,26 @@ func (m *validateOpUploadLayerPart) HandleInitialize(ctx context.Context, in mid return next.HandleInitialize(ctx, in) } +type validateOpValidatePullThroughCacheRule struct { +} + +func (*validateOpValidatePullThroughCacheRule) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpValidatePullThroughCacheRule) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*ValidatePullThroughCacheRuleInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpValidatePullThroughCacheRuleInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + func addOpBatchCheckLayerAvailabilityValidationMiddleware(stack *middleware.Stack) error { return stack.Initialize.Add(&validateOpBatchCheckLayerAvailability{}, middleware.After) } @@ -714,6 +854,10 @@ func addOpCreatePullThroughCacheRuleValidationMiddleware(stack *middleware.Stack return stack.Initialize.Add(&validateOpCreatePullThroughCacheRule{}, middleware.After) } +func addOpCreateRepositoryCreationTemplateValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpCreateRepositoryCreationTemplate{}, middleware.After) +} + func addOpCreateRepositoryValidationMiddleware(stack *middleware.Stack) error { return stack.Initialize.Add(&validateOpCreateRepository{}, middleware.After) } @@ -726,6 +870,10 @@ func addOpDeletePullThroughCacheRuleValidationMiddleware(stack *middleware.Stack return stack.Initialize.Add(&validateOpDeletePullThroughCacheRule{}, middleware.After) } +func addOpDeleteRepositoryCreationTemplateValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDeleteRepositoryCreationTemplate{}, middleware.After) +} + func addOpDeleteRepositoryValidationMiddleware(stack *middleware.Stack) error { return stack.Initialize.Add(&validateOpDeleteRepository{}, middleware.After) } @@ -746,6 +894,10 @@ func addOpDescribeImagesValidationMiddleware(stack *middleware.Stack) error { return stack.Initialize.Add(&validateOpDescribeImages{}, middleware.After) } +func addOpGetAccountSettingValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetAccountSetting{}, middleware.After) +} + func addOpGetDownloadUrlForLayerValidationMiddleware(stack *middleware.Stack) error { return stack.Initialize.Add(&validateOpGetDownloadUrlForLayer{}, middleware.After) } @@ -774,6 +926,10 @@ func addOpListTagsForResourceValidationMiddleware(stack *middleware.Stack) error return stack.Initialize.Add(&validateOpListTagsForResource{}, middleware.After) } +func addOpPutAccountSettingValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpPutAccountSetting{}, middleware.After) +} + func addOpPutImageValidationMiddleware(stack *middleware.Stack) error { return stack.Initialize.Add(&validateOpPutImage{}, middleware.After) } @@ -822,10 +978,22 @@ func addOpUntagResourceValidationMiddleware(stack *middleware.Stack) error { return stack.Initialize.Add(&validateOpUntagResource{}, middleware.After) } +func addOpUpdatePullThroughCacheRuleValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpUpdatePullThroughCacheRule{}, middleware.After) +} + +func addOpUpdateRepositoryCreationTemplateValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpUpdateRepositoryCreationTemplate{}, middleware.After) +} + func addOpUploadLayerPartValidationMiddleware(stack *middleware.Stack) error { return stack.Initialize.Add(&validateOpUploadLayerPart{}, middleware.After) } +func addOpValidatePullThroughCacheRuleValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpValidatePullThroughCacheRule{}, middleware.After) +} + func validateEncryptionConfiguration(v *types.EncryptionConfiguration) error { if v == nil { return nil @@ -841,6 +1009,21 @@ func validateEncryptionConfiguration(v *types.EncryptionConfiguration) error { } } +func validateEncryptionConfigurationForRepositoryCreationTemplate(v *types.EncryptionConfigurationForRepositoryCreationTemplate) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "EncryptionConfigurationForRepositoryCreationTemplate"} + if len(v.EncryptionType) == 0 { + invalidParams.Add(smithy.NewErrParamRequired("EncryptionType")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + func validateRegistryScanningRule(v *types.RegistryScanningRule) error { if v == nil { return nil @@ -1188,6 +1371,34 @@ func validateOpCreatePullThroughCacheRuleInput(v *CreatePullThroughCacheRuleInpu } } +func validateOpCreateRepositoryCreationTemplateInput(v *CreateRepositoryCreationTemplateInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "CreateRepositoryCreationTemplateInput"} + if v.Prefix == nil { + invalidParams.Add(smithy.NewErrParamRequired("Prefix")) + } + if v.EncryptionConfiguration != nil { + if err := validateEncryptionConfigurationForRepositoryCreationTemplate(v.EncryptionConfiguration); err != nil { + invalidParams.AddNested("EncryptionConfiguration", err.(smithy.InvalidParamsError)) + } + } + if v.ResourceTags != nil { + if err := validateTagList(v.ResourceTags); err != nil { + invalidParams.AddNested("ResourceTags", err.(smithy.InvalidParamsError)) + } + } + if v.AppliedFor == nil { + invalidParams.Add(smithy.NewErrParamRequired("AppliedFor")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + func validateOpCreateRepositoryInput(v *CreateRepositoryInput) error { if v == nil { return nil @@ -1243,6 +1454,21 @@ func validateOpDeletePullThroughCacheRuleInput(v *DeletePullThroughCacheRuleInpu } } +func validateOpDeleteRepositoryCreationTemplateInput(v *DeleteRepositoryCreationTemplateInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DeleteRepositoryCreationTemplateInput"} + if v.Prefix == nil { + invalidParams.Add(smithy.NewErrParamRequired("Prefix")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + func validateOpDeleteRepositoryInput(v *DeleteRepositoryInput) error { if v == nil { return nil @@ -1324,6 +1550,21 @@ func validateOpDescribeImagesInput(v *DescribeImagesInput) error { } } +func validateOpGetAccountSettingInput(v *GetAccountSettingInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetAccountSettingInput"} + if v.Name == nil { + invalidParams.Add(smithy.NewErrParamRequired("Name")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + func validateOpGetDownloadUrlForLayerInput(v *GetDownloadUrlForLayerInput) error { if v == nil { return nil @@ -1432,6 +1673,24 @@ func validateOpListTagsForResourceInput(v *ListTagsForResourceInput) error { } } +func validateOpPutAccountSettingInput(v *PutAccountSettingInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "PutAccountSettingInput"} + if v.Name == nil { + invalidParams.Add(smithy.NewErrParamRequired("Name")) + } + if v.Value == nil { + invalidParams.Add(smithy.NewErrParamRequired("Value")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + func validateOpPutImageInput(v *PutImageInput) error { if v == nil { return nil @@ -1646,6 +1905,49 @@ func validateOpUntagResourceInput(v *UntagResourceInput) error { } } +func validateOpUpdatePullThroughCacheRuleInput(v *UpdatePullThroughCacheRuleInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "UpdatePullThroughCacheRuleInput"} + if v.EcrRepositoryPrefix == nil { + invalidParams.Add(smithy.NewErrParamRequired("EcrRepositoryPrefix")) + } + if v.CredentialArn == nil { + invalidParams.Add(smithy.NewErrParamRequired("CredentialArn")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpUpdateRepositoryCreationTemplateInput(v *UpdateRepositoryCreationTemplateInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "UpdateRepositoryCreationTemplateInput"} + if v.Prefix == nil { + invalidParams.Add(smithy.NewErrParamRequired("Prefix")) + } + if v.EncryptionConfiguration != nil { + if err := validateEncryptionConfigurationForRepositoryCreationTemplate(v.EncryptionConfiguration); err != nil { + invalidParams.AddNested("EncryptionConfiguration", err.(smithy.InvalidParamsError)) + } + } + if v.ResourceTags != nil { + if err := validateTagList(v.ResourceTags); err != nil { + invalidParams.AddNested("ResourceTags", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + func validateOpUploadLayerPartInput(v *UploadLayerPartInput) error { if v == nil { return nil @@ -1672,3 +1974,18 @@ func validateOpUploadLayerPartInput(v *UploadLayerPartInput) error { return nil } } + +func validateOpValidatePullThroughCacheRuleInput(v *ValidatePullThroughCacheRuleInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ValidatePullThroughCacheRuleInput"} + if v.EcrRepositoryPrefix == nil { + invalidParams.Add(smithy.NewErrParamRequired("EcrRepositoryPrefix")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/CHANGELOG.md index b3b5a57e6d..4b60c6b16d 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/CHANGELOG.md @@ -1,3 +1,283 @@ +# v1.31.2 (2025-02-05) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.31.1 (2025-01-31) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.31.0 (2025-01-30) + +* **Feature**: Temporarily updating dualstack endpoint support +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.30.0 (2025-01-29) + +* **Feature**: Add support for Dualstack Endpoints + +# v1.29.5 (2025-01-24) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.22.2. + +# v1.29.4 (2025-01-17) + +* **Bug Fix**: Fix bug where credentials weren't refreshed during retry loop. + +# v1.29.3 (2025-01-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.29.2 (2025-01-09) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.29.1 (2025-01-03) + +* No change notes available for this release. + +# v1.29.0 (2024-12-28) + +* **Feature**: Restoring custom endpoint functionality for ECR Public + +# v1.28.1 (2024-12-26) + +* No change notes available for this release. + +# v1.28.0 (2024-12-23) + +* **Feature**: Add support for Dualstack endpoints + +# v1.27.8 (2024-12-19) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.27.7 (2024-12-02) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.27.6 (2024-11-18) + +* **Dependency Update**: Update to smithy-go v1.22.1. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.27.5 (2024-11-07) + +* **Bug Fix**: Adds case-insensitive handling of error message fields in service responses + +# v1.27.4 (2024-11-06) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.27.3 (2024-10-28) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.27.2 (2024-10-08) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.27.1 (2024-10-07) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.27.0 (2024-10-04) + +* **Feature**: Add support for HTTP client metrics. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.26.4 (2024-10-03) + +* No change notes available for this release. + +# v1.26.3 (2024-09-27) + +* No change notes available for this release. + +# v1.26.2 (2024-09-25) + +* No change notes available for this release. + +# v1.26.1 (2024-09-23) + +* No change notes available for this release. + +# v1.26.0 (2024-09-20) + +* **Feature**: Add tracing and metrics support to service clients. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.25.7 (2024-09-17) + +* **Bug Fix**: **BREAKFIX**: Only generate AccountIDEndpointMode config for services that use it. This is a compiler break, but removes no actual functionality, as no services currently use the account ID in endpoint resolution. + +# v1.25.6 (2024-09-04) + +* No change notes available for this release. + +# v1.25.5 (2024-09-03) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.25.4 (2024-08-15) + +* **Dependency Update**: Bump minimum Go version to 1.21. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.25.3 (2024-07-10.2) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.25.2 (2024-07-10) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.25.1 (2024-06-28) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.25.0 (2024-06-26) + +* **Feature**: Support list-of-string endpoint parameter. + +# v1.24.1 (2024-06-19) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.24.0 (2024-06-18) + +* **Feature**: Track usage of various AWS SDK features in user-agent string. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.23.11 (2024-06-17) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.23.10 (2024-06-07) + +* **Bug Fix**: Add clock skew correction on all service clients +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.23.9 (2024-06-03) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.23.8 (2024-05-23) + +* No change notes available for this release. + +# v1.23.7 (2024-05-16) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.23.6 (2024-05-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.23.5 (2024-05-08) + +* **Bug Fix**: GoDoc improvement + +# v1.23.4 (2024-03-29) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.23.3 (2024-03-18) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.23.2 (2024-03-07) + +* **Bug Fix**: Remove dependency on go-cmp. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.23.1 (2024-02-23) + +* **Bug Fix**: Move all common, SDK-side middleware stack ops into the service client module to prevent cross-module compatibility issues in the future. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.23.0 (2024-02-22) + +* **Feature**: Add middleware stack snapshot tests. + +# v1.22.3 (2024-02-21) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.22.2 (2024-02-20) + +* **Bug Fix**: When sourcing values for a service's `EndpointParameters`, the lack of a configured region (i.e. `options.Region == ""`) will now translate to a `nil` value for `EndpointParameters.Region` instead of a pointer to the empty string `""`. This will result in a much more explicit error when calling an operation instead of an obscure hostname lookup failure. + +# v1.22.1 (2024-02-15) + +* **Bug Fix**: Correct failure to determine the error type in awsJson services that could occur when errors were modeled with a non-string `code` field. + +# v1.22.0 (2024-02-13) + +* **Feature**: Bump minimum Go version to 1.20 per our language support policy. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.21.6 (2024-01-04) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.21.5 (2023-12-08) + +* **Bug Fix**: Reinstate presence of default Retryer in functional options, but still respect max attempts set therein. + +# v1.21.4 (2023-12-07) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.21.3 (2023-12-06) + +* **Bug Fix**: Restore pre-refactor auth behavior where all operations could technically be performed anonymously. + +# v1.21.2 (2023-12-01) + +* **Bug Fix**: Correct wrapping of errors in authentication workflow. +* **Bug Fix**: Correctly recognize cache-wrapped instances of AnonymousCredentials at client construction. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.21.1 (2023-11-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.21.0 (2023-11-29) + +* **Feature**: Expose Options() accessor on service clients. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.20.5 (2023-11-28.2) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.20.4 (2023-11-28) + +* **Bug Fix**: Respect setting RetryMaxAttempts in functional options at client construction. + +# v1.20.3 (2023-11-20) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.20.2 (2023-11-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.20.1 (2023-11-09) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.20.0 (2023-11-01) + +* **Feature**: Adds support for configured endpoints via environment variables and the AWS shared configuration file. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.19.0 (2023-10-31) + +* **Feature**: **BREAKING CHANGE**: Bump minimum go version to 1.19 per the revised [go version support policy](https://aws.amazon.com/blogs/developer/aws-sdk-for-go-aligns-with-go-release-policy-on-supported-runtimes/). +* **Dependency Update**: Updated to the latest SDK module versions + # v1.18.2 (2023-10-12) * **Dependency Update**: Updated to the latest SDK module versions diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_client.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_client.go index a8264f47a9..6ec6c3ec1c 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_client.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_client.go @@ -4,6 +4,7 @@ package ecrpublic import ( "context" + "errors" "fmt" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/aws/defaults" @@ -11,24 +12,161 @@ import ( "github.com/aws/aws-sdk-go-v2/aws/retry" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" + internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" + internalauthsmithy "github.com/aws/aws-sdk-go-v2/internal/auth/smithy" internalConfig "github.com/aws/aws-sdk-go-v2/internal/configsources" + internalmiddleware "github.com/aws/aws-sdk-go-v2/internal/middleware" smithy "github.com/aws/smithy-go" + smithyauth "github.com/aws/smithy-go/auth" smithydocument "github.com/aws/smithy-go/document" "github.com/aws/smithy-go/logging" + "github.com/aws/smithy-go/metrics" "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/tracing" smithyhttp "github.com/aws/smithy-go/transport/http" "net" "net/http" + "sync/atomic" "time" ) const ServiceID = "ECR PUBLIC" const ServiceAPIVersion = "2020-10-30" +type operationMetrics struct { + Duration metrics.Float64Histogram + SerializeDuration metrics.Float64Histogram + ResolveIdentityDuration metrics.Float64Histogram + ResolveEndpointDuration metrics.Float64Histogram + SignRequestDuration metrics.Float64Histogram + DeserializeDuration metrics.Float64Histogram +} + +func (m *operationMetrics) histogramFor(name string) metrics.Float64Histogram { + switch name { + case "client.call.duration": + return m.Duration + case "client.call.serialization_duration": + return m.SerializeDuration + case "client.call.resolve_identity_duration": + return m.ResolveIdentityDuration + case "client.call.resolve_endpoint_duration": + return m.ResolveEndpointDuration + case "client.call.signing_duration": + return m.SignRequestDuration + case "client.call.deserialization_duration": + return m.DeserializeDuration + default: + panic("unrecognized operation metric") + } +} + +func timeOperationMetric[T any]( + ctx context.Context, metric string, fn func() (T, error), + opts ...metrics.RecordMetricOption, +) (T, error) { + instr := getOperationMetrics(ctx).histogramFor(metric) + opts = append([]metrics.RecordMetricOption{withOperationMetadata(ctx)}, opts...) + + start := time.Now() + v, err := fn() + end := time.Now() + + elapsed := end.Sub(start) + instr.Record(ctx, float64(elapsed)/1e9, opts...) + return v, err +} + +func startMetricTimer(ctx context.Context, metric string, opts ...metrics.RecordMetricOption) func() { + instr := getOperationMetrics(ctx).histogramFor(metric) + opts = append([]metrics.RecordMetricOption{withOperationMetadata(ctx)}, opts...) + + var ended bool + start := time.Now() + return func() { + if ended { + return + } + ended = true + + end := time.Now() + + elapsed := end.Sub(start) + instr.Record(ctx, float64(elapsed)/1e9, opts...) + } +} + +func withOperationMetadata(ctx context.Context) metrics.RecordMetricOption { + return func(o *metrics.RecordMetricOptions) { + o.Properties.Set("rpc.service", middleware.GetServiceID(ctx)) + o.Properties.Set("rpc.method", middleware.GetOperationName(ctx)) + } +} + +type operationMetricsKey struct{} + +func withOperationMetrics(parent context.Context, mp metrics.MeterProvider) (context.Context, error) { + meter := mp.Meter("github.com/aws/aws-sdk-go-v2/service/ecrpublic") + om := &operationMetrics{} + + var err error + + om.Duration, err = operationMetricTimer(meter, "client.call.duration", + "Overall call duration (including retries and time to send or receive request and response body)") + if err != nil { + return nil, err + } + om.SerializeDuration, err = operationMetricTimer(meter, "client.call.serialization_duration", + "The time it takes to serialize a message body") + if err != nil { + return nil, err + } + om.ResolveIdentityDuration, err = operationMetricTimer(meter, "client.call.auth.resolve_identity_duration", + "The time taken to acquire an identity (AWS credentials, bearer token, etc) from an Identity Provider") + if err != nil { + return nil, err + } + om.ResolveEndpointDuration, err = operationMetricTimer(meter, "client.call.resolve_endpoint_duration", + "The time it takes to resolve an endpoint (endpoint resolver, not DNS) for the request") + if err != nil { + return nil, err + } + om.SignRequestDuration, err = operationMetricTimer(meter, "client.call.auth.signing_duration", + "The time it takes to sign a request") + if err != nil { + return nil, err + } + om.DeserializeDuration, err = operationMetricTimer(meter, "client.call.deserialization_duration", + "The time it takes to deserialize a message body") + if err != nil { + return nil, err + } + + return context.WithValue(parent, operationMetricsKey{}, om), nil +} + +func operationMetricTimer(m metrics.Meter, name, desc string) (metrics.Float64Histogram, error) { + return m.Float64Histogram(name, func(o *metrics.InstrumentOptions) { + o.UnitLabel = "s" + o.Description = desc + }) +} + +func getOperationMetrics(ctx context.Context) *operationMetrics { + return ctx.Value(operationMetricsKey{}).(*operationMetrics) +} + +func operationTracer(p tracing.TracerProvider) tracing.Tracer { + return p.Tracer("github.com/aws/aws-sdk-go-v2/service/ecrpublic") +} + // Client provides the API client to make operations call for Amazon Elastic // Container Registry Public. type Client struct { options Options + + // Difference between the time reported by the server and the client + timeOffset *atomic.Int64 } // New returns an initialized Client based on the functional options. Provide @@ -47,157 +185,61 @@ func New(options Options, optFns ...func(*Options)) *Client { resolveHTTPSignerV4(&options) - for _, fn := range optFns { - fn(&options) - } - - client := &Client{ - options: options, - } - - return client -} - -type Options struct { - // Set of options to modify how an operation is invoked. These apply to all - // operations invoked for this client. Use functional options on operation call to - // modify this list for per operation behavior. - APIOptions []func(*middleware.Stack) error - - // The optional application specific identifier appended to the User-Agent header. - AppID string - - // This endpoint will be given as input to an EndpointResolverV2. It is used for - // providing a custom base endpoint that is subject to modifications by the - // processing EndpointResolverV2. - BaseEndpoint *string - - // Configures the events that will be sent to the configured logger. - ClientLogMode aws.ClientLogMode - - // The credentials object to use when signing requests. - Credentials aws.CredentialsProvider - - // The configuration DefaultsMode that the SDK should use when constructing the - // clients initial default settings. - DefaultsMode aws.DefaultsMode - - // The endpoint options to be used when attempting to resolve an endpoint. - EndpointOptions EndpointResolverOptions - - // The service endpoint resolver. - // - // Deprecated: Deprecated: EndpointResolver and WithEndpointResolver. Providing a - // value for this field will likely prevent you from using any endpoint-related - // service features released after the introduction of EndpointResolverV2 and - // BaseEndpoint. To migrate an EndpointResolver implementation that uses a custom - // endpoint, set the client option BaseEndpoint instead. - EndpointResolver EndpointResolver - - // Resolves the endpoint used for a particular service. This should be used over - // the deprecated EndpointResolver - EndpointResolverV2 EndpointResolverV2 - - // Signature Version 4 (SigV4) Signer - HTTPSignerV4 HTTPSignerV4 + resolveEndpointResolverV2(&options) - // The logger writer interface to write logging messages to. - Logger logging.Logger + resolveTracerProvider(&options) - // The region to send requests to. (Required) - Region string + resolveMeterProvider(&options) - // RetryMaxAttempts specifies the maximum number attempts an API client will call - // an operation that fails with a retryable error. A value of 0 is ignored, and - // will not be used to configure the API client created default retryer, or modify - // per operation call's retry max attempts. When creating a new API Clients this - // member will only be used if the Retryer Options member is nil. This value will - // be ignored if Retryer is not nil. If specified in an operation call's functional - // options with a value that is different than the constructed client's Options, - // the Client's Retryer will be wrapped to use the operation's specific - // RetryMaxAttempts value. - RetryMaxAttempts int + resolveAuthSchemeResolver(&options) - // RetryMode specifies the retry mode the API client will be created with, if - // Retryer option is not also specified. When creating a new API Clients this - // member will only be used if the Retryer Options member is nil. This value will - // be ignored if Retryer is not nil. Currently does not support per operation call - // overrides, may in the future. - RetryMode aws.RetryMode + for _, fn := range optFns { + fn(&options) + } - // Retryer guides how HTTP requests should be retried in case of recoverable - // failures. When nil the API client will use a default retryer. The kind of - // default retry created by the API client can be changed with the RetryMode - // option. - Retryer aws.Retryer + finalizeRetryMaxAttempts(&options) - // The RuntimeEnvironment configuration, only populated if the DefaultsMode is set - // to DefaultsModeAuto and is initialized using config.LoadDefaultConfig . You - // should not populate this structure programmatically, or rely on the values here - // within your applications. - RuntimeEnvironment aws.RuntimeEnvironment + ignoreAnonymousAuth(&options) - // The initial DefaultsMode used when the client options were constructed. If the - // DefaultsMode was set to aws.DefaultsModeAuto this will store what the resolved - // value was at that point in time. Currently does not support per operation call - // overrides, may in the future. - resolvedDefaultsMode aws.DefaultsMode + wrapWithAnonymousAuth(&options) - // The HTTP client to invoke API calls with. Defaults to client's default HTTP - // implementation if nil. - HTTPClient HTTPClient -} + resolveAuthSchemes(&options) -// WithAPIOptions returns a functional option for setting the Client's APIOptions -// option. -func WithAPIOptions(optFns ...func(*middleware.Stack) error) func(*Options) { - return func(o *Options) { - o.APIOptions = append(o.APIOptions, optFns...) + client := &Client{ + options: options, } -} -// Deprecated: EndpointResolver and WithEndpointResolver. Providing a value for -// this field will likely prevent you from using any endpoint-related service -// features released after the introduction of EndpointResolverV2 and BaseEndpoint. -// To migrate an EndpointResolver implementation that uses a custom endpoint, set -// the client option BaseEndpoint instead. -func WithEndpointResolver(v EndpointResolver) func(*Options) { - return func(o *Options) { - o.EndpointResolver = v - } -} + initializeTimeOffsetResolver(client) -// WithEndpointResolverV2 returns a functional option for setting the Client's -// EndpointResolverV2 option. -func WithEndpointResolverV2(v EndpointResolverV2) func(*Options) { - return func(o *Options) { - o.EndpointResolverV2 = v - } + return client } -type HTTPClient interface { - Do(*http.Request) (*http.Response, error) +// Options returns a copy of the client configuration. +// +// Callers SHOULD NOT perform mutations on any inner structures within client +// config. Config overrides should instead be made on a per-operation basis through +// functional options. +func (c *Client) Options() Options { + return c.options.Copy() } -// Copy creates a clone where the APIOptions list is deep copied. -func (o Options) Copy() Options { - to := o - to.APIOptions = make([]func(*middleware.Stack) error, len(o.APIOptions)) - copy(to.APIOptions, o.APIOptions) - - return to -} -func (c *Client) invokeOperation(ctx context.Context, opID string, params interface{}, optFns []func(*Options), stackFns ...func(*middleware.Stack, Options) error) (result interface{}, metadata middleware.Metadata, err error) { +func (c *Client) invokeOperation( + ctx context.Context, opID string, params interface{}, optFns []func(*Options), stackFns ...func(*middleware.Stack, Options) error, +) ( + result interface{}, metadata middleware.Metadata, err error, +) { ctx = middleware.ClearStackValues(ctx) + ctx = middleware.WithServiceID(ctx, ServiceID) + ctx = middleware.WithOperationName(ctx, opID) + stack := middleware.NewStack(opID, smithyhttp.NewStackRequest) options := c.options.Copy() - resolveEndpointResolverV2(&options) for _, fn := range optFns { fn(&options) } - finalizeRetryMaxAttemptOptions(&options, *c) + finalizeOperationRetryMaxAttempts(&options, *c) finalizeClientEndpointResolverOptions(&options) @@ -213,18 +255,116 @@ func (c *Client) invokeOperation(ctx context.Context, opID string, params interf } } - handler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack) - result, metadata, err = handler.Handle(ctx, params) + ctx, err = withOperationMetrics(ctx, options.MeterProvider) if err != nil { + return nil, metadata, err + } + + tracer := operationTracer(options.TracerProvider) + spanName := fmt.Sprintf("%s.%s", ServiceID, opID) + + ctx = tracing.WithOperationTracer(ctx, tracer) + + ctx, span := tracer.StartSpan(ctx, spanName, func(o *tracing.SpanOptions) { + o.Kind = tracing.SpanKindClient + o.Properties.Set("rpc.system", "aws-api") + o.Properties.Set("rpc.method", opID) + o.Properties.Set("rpc.service", ServiceID) + }) + endTimer := startMetricTimer(ctx, "client.call.duration") + defer endTimer() + defer span.End() + + handler := smithyhttp.NewClientHandlerWithOptions(options.HTTPClient, func(o *smithyhttp.ClientHandler) { + o.Meter = options.MeterProvider.Meter("github.com/aws/aws-sdk-go-v2/service/ecrpublic") + }) + decorated := middleware.DecorateHandler(handler, stack) + result, metadata, err = decorated.Handle(ctx, params) + if err != nil { + span.SetProperty("exception.type", fmt.Sprintf("%T", err)) + span.SetProperty("exception.message", err.Error()) + + var aerr smithy.APIError + if errors.As(err, &aerr) { + span.SetProperty("api.error_code", aerr.ErrorCode()) + span.SetProperty("api.error_message", aerr.ErrorMessage()) + span.SetProperty("api.error_fault", aerr.ErrorFault().String()) + } + err = &smithy.OperationError{ ServiceID: ServiceID, OperationName: opID, Err: err, } } + + span.SetProperty("error", err != nil) + if err == nil { + span.SetStatus(tracing.SpanStatusOK) + } else { + span.SetStatus(tracing.SpanStatusError) + } + return result, metadata, err } +type operationInputKey struct{} + +func setOperationInput(ctx context.Context, input interface{}) context.Context { + return middleware.WithStackValue(ctx, operationInputKey{}, input) +} + +func getOperationInput(ctx context.Context) interface{} { + return middleware.GetStackValue(ctx, operationInputKey{}) +} + +type setOperationInputMiddleware struct { +} + +func (*setOperationInputMiddleware) ID() string { + return "setOperationInput" +} + +func (m *setOperationInputMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + ctx = setOperationInput(ctx, in.Parameters) + return next.HandleSerialize(ctx, in) +} + +func addProtocolFinalizerMiddlewares(stack *middleware.Stack, options Options, operation string) error { + if err := stack.Finalize.Add(&resolveAuthSchemeMiddleware{operation: operation, options: options}, middleware.Before); err != nil { + return fmt.Errorf("add ResolveAuthScheme: %w", err) + } + if err := stack.Finalize.Insert(&getIdentityMiddleware{options: options}, "ResolveAuthScheme", middleware.After); err != nil { + return fmt.Errorf("add GetIdentity: %v", err) + } + if err := stack.Finalize.Insert(&resolveEndpointV2Middleware{options: options}, "GetIdentity", middleware.After); err != nil { + return fmt.Errorf("add ResolveEndpointV2: %v", err) + } + if err := stack.Finalize.Insert(&signRequestMiddleware{options: options}, "ResolveEndpointV2", middleware.After); err != nil { + return fmt.Errorf("add Signing: %w", err) + } + return nil +} +func resolveAuthSchemeResolver(options *Options) { + if options.AuthSchemeResolver == nil { + options.AuthSchemeResolver = &defaultAuthSchemeResolver{} + } +} + +func resolveAuthSchemes(options *Options) { + if options.AuthSchemes == nil { + options.AuthSchemes = []smithyhttp.AuthScheme{ + internalauth.NewHTTPAuthScheme("aws.auth#sigv4", &internalauthsmithy.V4SignerAdapter{ + Signer: options.HTTPSignerV4, + Logger: options.Logger, + LogSigning: options.ClientLogMode.IsSigning(), + }), + } + } +} + type noSmithyDocumentSerde = smithydocument.NoSerde type legacyEndpointContextSetter struct { @@ -296,6 +436,7 @@ func NewFromConfig(cfg aws.Config, optFns ...func(*Options)) *Client { resolveAWSEndpointResolver(cfg, &opts) resolveUseDualStackEndpoint(cfg, &opts) resolveUseFIPSEndpoint(cfg, &opts) + resolveBaseEndpoint(cfg, &opts) return New(opts, optFns...) } @@ -387,7 +528,15 @@ func resolveAWSRetryMaxAttempts(cfg aws.Config, o *Options) { o.RetryMaxAttempts = cfg.RetryMaxAttempts } -func finalizeRetryMaxAttemptOptions(o *Options, client Client) { +func finalizeRetryMaxAttempts(o *Options) { + if o.RetryMaxAttempts == 0 { + return + } + + o.Retryer = retry.AddWithMaxAttempts(o.Retryer, o.RetryMaxAttempts) +} + +func finalizeOperationRetryMaxAttempts(o *Options, client Client) { if v := o.RetryMaxAttempts; v == 0 || v == client.options.RetryMaxAttempts { return } @@ -403,24 +552,35 @@ func resolveAWSEndpointResolver(cfg aws.Config, o *Options) { } func addClientUserAgent(stack *middleware.Stack, options Options) error { - if err := awsmiddleware.AddSDKAgentKeyValue(awsmiddleware.APIMetadata, "ecrpublic", goModuleVersion)(stack); err != nil { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { return err } + ua.AddSDKAgentKeyValue(awsmiddleware.APIMetadata, "ecrpublic", goModuleVersion) if len(options.AppID) > 0 { - return awsmiddleware.AddSDKAgentKey(awsmiddleware.ApplicationIdentifier, options.AppID)(stack) + ua.AddSDKAgentKey(awsmiddleware.ApplicationIdentifier, options.AppID) } return nil } -func addHTTPSignerV4Middleware(stack *middleware.Stack, o Options) error { - mw := v4.NewSignHTTPRequestMiddleware(v4.SignHTTPRequestMiddlewareOptions{ - CredentialsProvider: o.Credentials, - Signer: o.HTTPSignerV4, - LogSigning: o.ClientLogMode.IsSigning(), - }) - return stack.Finalize.Add(mw, middleware.After) +func getOrAddRequestUserAgent(stack *middleware.Stack) (*awsmiddleware.RequestUserAgent, error) { + id := (*awsmiddleware.RequestUserAgent)(nil).ID() + mw, ok := stack.Build.Get(id) + if !ok { + mw = awsmiddleware.NewRequestUserAgent() + if err := stack.Build.Add(mw, middleware.After); err != nil { + return nil, err + } + } + + ua, ok := mw.(*awsmiddleware.RequestUserAgent) + if !ok { + return nil, fmt.Errorf("%T for %s middleware did not match expected type", mw, id) + } + + return ua, nil } type HTTPSignerV4 interface { @@ -441,12 +601,97 @@ func newDefaultV4Signer(o Options) *v4.Signer { }) } -func addRetryMiddlewares(stack *middleware.Stack, o Options) error { - mo := retry.AddRetryMiddlewaresOptions{ - Retryer: o.Retryer, - LogRetryAttempts: o.ClientLogMode.IsRetries(), +func addClientRequestID(stack *middleware.Stack) error { + return stack.Build.Add(&awsmiddleware.ClientRequestID{}, middleware.After) +} + +func addComputeContentLength(stack *middleware.Stack) error { + return stack.Build.Add(&smithyhttp.ComputeContentLength{}, middleware.After) +} + +func addRawResponseToMetadata(stack *middleware.Stack) error { + return stack.Deserialize.Add(&awsmiddleware.AddRawResponse{}, middleware.Before) +} + +func addRecordResponseTiming(stack *middleware.Stack) error { + return stack.Deserialize.Add(&awsmiddleware.RecordResponseTiming{}, middleware.After) +} + +func addSpanRetryLoop(stack *middleware.Stack, options Options) error { + return stack.Finalize.Insert(&spanRetryLoop{options: options}, "Retry", middleware.Before) +} + +type spanRetryLoop struct { + options Options +} + +func (*spanRetryLoop) ID() string { + return "spanRetryLoop" +} + +func (m *spanRetryLoop) HandleFinalize( + ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler, +) ( + middleware.FinalizeOutput, middleware.Metadata, error, +) { + tracer := operationTracer(m.options.TracerProvider) + ctx, span := tracer.StartSpan(ctx, "RetryLoop") + defer span.End() + + return next.HandleFinalize(ctx, in) +} +func addStreamingEventsPayload(stack *middleware.Stack) error { + return stack.Finalize.Add(&v4.StreamingEventsPayload{}, middleware.Before) +} + +func addUnsignedPayload(stack *middleware.Stack) error { + return stack.Finalize.Insert(&v4.UnsignedPayload{}, "ResolveEndpointV2", middleware.After) +} + +func addComputePayloadSHA256(stack *middleware.Stack) error { + return stack.Finalize.Insert(&v4.ComputePayloadSHA256{}, "ResolveEndpointV2", middleware.After) +} + +func addContentSHA256Header(stack *middleware.Stack) error { + return stack.Finalize.Insert(&v4.ContentSHA256Header{}, (*v4.ComputePayloadSHA256)(nil).ID(), middleware.After) +} + +func addIsWaiterUserAgent(o *Options) { + o.APIOptions = append(o.APIOptions, func(stack *middleware.Stack) error { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { + return err + } + + ua.AddUserAgentFeature(awsmiddleware.UserAgentFeatureWaiter) + return nil + }) +} + +func addIsPaginatorUserAgent(o *Options) { + o.APIOptions = append(o.APIOptions, func(stack *middleware.Stack) error { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { + return err + } + + ua.AddUserAgentFeature(awsmiddleware.UserAgentFeaturePaginator) + return nil + }) +} + +func addRetry(stack *middleware.Stack, o Options) error { + attempt := retry.NewAttemptMiddleware(o.Retryer, smithyhttp.RequestCloner, func(m *retry.Attempt) { + m.LogAttempts = o.ClientLogMode.IsRetries() + m.OperationMeter = o.MeterProvider.Meter("github.com/aws/aws-sdk-go-v2/service/ecrpublic") + }) + if err := stack.Finalize.Insert(attempt, "ResolveAuthScheme", middleware.Before); err != nil { + return err + } + if err := stack.Finalize.Insert(&retry.MetricsHeader{}, attempt.ID(), middleware.After); err != nil { + return err } - return retry.AddRetryMiddlewares(stack, mo) + return nil } // resolves dual-stack endpoint configuration @@ -479,12 +724,68 @@ func resolveUseFIPSEndpoint(cfg aws.Config, o *Options) error { return nil } +func resolveAccountID(identity smithyauth.Identity, mode aws.AccountIDEndpointMode) *string { + if mode == aws.AccountIDEndpointModeDisabled { + return nil + } + + if ca, ok := identity.(*internalauthsmithy.CredentialsAdapter); ok && ca.Credentials.AccountID != "" { + return aws.String(ca.Credentials.AccountID) + } + + return nil +} + +func addTimeOffsetBuild(stack *middleware.Stack, c *Client) error { + mw := internalmiddleware.AddTimeOffsetMiddleware{Offset: c.timeOffset} + if err := stack.Build.Add(&mw, middleware.After); err != nil { + return err + } + return stack.Deserialize.Insert(&mw, "RecordResponseTiming", middleware.Before) +} +func initializeTimeOffsetResolver(c *Client) { + c.timeOffset = new(atomic.Int64) +} + +func addUserAgentRetryMode(stack *middleware.Stack, options Options) error { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { + return err + } + + switch options.Retryer.(type) { + case *retry.Standard: + ua.AddUserAgentFeature(awsmiddleware.UserAgentFeatureRetryModeStandard) + case *retry.AdaptiveMode: + ua.AddUserAgentFeature(awsmiddleware.UserAgentFeatureRetryModeAdaptive) + } + return nil +} + +func resolveTracerProvider(options *Options) { + if options.TracerProvider == nil { + options.TracerProvider = &tracing.NopTracerProvider{} + } +} + +func resolveMeterProvider(options *Options) { + if options.MeterProvider == nil { + options.MeterProvider = metrics.NopMeterProvider{} + } +} + +func addRecursionDetection(stack *middleware.Stack) error { + return stack.Build.Add(&awsmiddleware.RecursionDetection{}, middleware.After) +} + func addRequestIDRetrieverMiddleware(stack *middleware.Stack) error { - return awsmiddleware.AddRequestIDRetrieverMiddleware(stack) + return stack.Deserialize.Insert(&awsmiddleware.RequestIDRetriever{}, "OperationDeserializer", middleware.Before) + } func addResponseErrorMiddleware(stack *middleware.Stack) error { - return awshttp.AddResponseErrorMiddleware(stack) + return stack.Deserialize.Insert(&awshttp.ResponseErrorWrapper{}, "RequestIDRetriever", middleware.Before) + } func addRequestResponseLogging(stack *middleware.Stack, o Options) error { @@ -496,31 +797,117 @@ func addRequestResponseLogging(stack *middleware.Stack, o Options) error { }, middleware.After) } -type endpointDisableHTTPSMiddleware struct { - EndpointDisableHTTPS bool +type disableHTTPSMiddleware struct { + DisableHTTPS bool } -func (*endpointDisableHTTPSMiddleware) ID() string { - return "endpointDisableHTTPSMiddleware" +func (*disableHTTPSMiddleware) ID() string { + return "disableHTTPS" } -func (m *endpointDisableHTTPSMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, +func (m *disableHTTPSMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, ) { req, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) } - if m.EndpointDisableHTTPS && !smithyhttp.GetHostnameImmutable(ctx) { + if m.DisableHTTPS && !smithyhttp.GetHostnameImmutable(ctx) { req.URL.Scheme = "http" } + return next.HandleFinalize(ctx, in) +} + +func addDisableHTTPSMiddleware(stack *middleware.Stack, o Options) error { + return stack.Finalize.Insert(&disableHTTPSMiddleware{ + DisableHTTPS: o.EndpointOptions.DisableHTTPS, + }, "ResolveEndpointV2", middleware.After) +} + +type spanInitializeStart struct { +} + +func (*spanInitializeStart) ID() string { + return "spanInitializeStart" +} + +func (m *spanInitializeStart) HandleInitialize( + ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler, +) ( + middleware.InitializeOutput, middleware.Metadata, error, +) { + ctx, _ = tracing.StartSpan(ctx, "Initialize") + + return next.HandleInitialize(ctx, in) +} + +type spanInitializeEnd struct { +} + +func (*spanInitializeEnd) ID() string { + return "spanInitializeEnd" +} + +func (m *spanInitializeEnd) HandleInitialize( + ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler, +) ( + middleware.InitializeOutput, middleware.Metadata, error, +) { + ctx, span := tracing.PopSpan(ctx) + span.End() + + return next.HandleInitialize(ctx, in) +} + +type spanBuildRequestStart struct { +} + +func (*spanBuildRequestStart) ID() string { + return "spanBuildRequestStart" +} + +func (m *spanBuildRequestStart) HandleSerialize( + ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler, +) ( + middleware.SerializeOutput, middleware.Metadata, error, +) { + ctx, _ = tracing.StartSpan(ctx, "BuildRequest") + return next.HandleSerialize(ctx, in) +} + +type spanBuildRequestEnd struct { +} + +func (*spanBuildRequestEnd) ID() string { + return "spanBuildRequestEnd" +} + +func (m *spanBuildRequestEnd) HandleBuild( + ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler, +) ( + middleware.BuildOutput, middleware.Metadata, error, +) { + ctx, span := tracing.PopSpan(ctx) + span.End() + return next.HandleBuild(ctx, in) } -func addendpointDisableHTTPSMiddleware(stack *middleware.Stack, o Options) error { - return stack.Serialize.Insert(&endpointDisableHTTPSMiddleware{ - EndpointDisableHTTPS: o.EndpointOptions.DisableHTTPS, - }, "OperationSerializer", middleware.Before) + +func addSpanInitializeStart(stack *middleware.Stack) error { + return stack.Initialize.Add(&spanInitializeStart{}, middleware.Before) +} + +func addSpanInitializeEnd(stack *middleware.Stack) error { + return stack.Initialize.Add(&spanInitializeEnd{}, middleware.After) +} + +func addSpanBuildRequestStart(stack *middleware.Stack) error { + return stack.Serialize.Add(&spanBuildRequestStart{}, middleware.Before) +} + +func addSpanBuildRequestEnd(stack *middleware.Stack) error { + return stack.Build.Add(&spanBuildRequestEnd{}, middleware.After) } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_BatchCheckLayerAvailability.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_BatchCheckLayerAvailability.go index d0d042e494..dc0aeccdcd 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_BatchCheckLayerAvailability.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_BatchCheckLayerAvailability.go @@ -4,14 +4,9 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecrpublic/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -19,9 +14,11 @@ import ( // Checks the availability of one or more image layers that are within a // repository in a public registry. When an image is pushed to a repository, each // image layer is checked to verify if it has been uploaded before. If it has been -// uploaded, then the image layer is skipped. This operation is used by the Amazon -// ECR proxy and is not generally used by customers for pulling and pushing images. -// In most cases, you should use the docker CLI to pull, tag, and push images. +// uploaded, then the image layer is skipped. +// +// This operation is used by the Amazon ECR proxy and is not generally used by +// customers for pulling and pushing images. In most cases, you should use the +// docker CLI to pull, tag, and push images. func (c *Client) BatchCheckLayerAvailability(ctx context.Context, params *BatchCheckLayerAvailabilityInput, optFns ...func(*Options)) (*BatchCheckLayerAvailabilityOutput, error) { if params == nil { params = &BatchCheckLayerAvailabilityInput{} @@ -73,6 +70,9 @@ type BatchCheckLayerAvailabilityOutput struct { } func (c *Client) addOperationBatchCheckLayerAvailabilityMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpBatchCheckLayerAvailability{}, middleware.After) if err != nil { return err @@ -81,34 +81,38 @@ func (c *Client) addOperationBatchCheckLayerAvailabilityMiddlewares(stack *middl if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "BatchCheckLayerAvailability"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -120,7 +124,13 @@ func (c *Client) addOperationBatchCheckLayerAvailabilityMiddlewares(stack *middl if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addBatchCheckLayerAvailabilityResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpBatchCheckLayerAvailabilityValidationMiddleware(stack); err != nil { @@ -129,7 +139,7 @@ func (c *Client) addOperationBatchCheckLayerAvailabilityMiddlewares(stack *middl if err = stack.Initialize.Add(newServiceMetadataMiddleware_opBatchCheckLayerAvailability(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -141,7 +151,19 @@ func (c *Client) addOperationBatchCheckLayerAvailabilityMiddlewares(stack *middl if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -151,130 +173,6 @@ func newServiceMetadataMiddleware_opBatchCheckLayerAvailability(region string) * return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "BatchCheckLayerAvailability", } } - -type opBatchCheckLayerAvailabilityResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opBatchCheckLayerAvailabilityResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opBatchCheckLayerAvailabilityResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addBatchCheckLayerAvailabilityResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opBatchCheckLayerAvailabilityResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_BatchDeleteImage.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_BatchDeleteImage.go index 1ec61e3f9c..01302e7712 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_BatchDeleteImage.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_BatchDeleteImage.go @@ -4,24 +4,22 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecrpublic/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Deletes a list of specified images that are within a repository in a public -// registry. Images are specified with either an imageTag or imageDigest . You can -// remove a tag from an image by specifying the image's tag in your request. When -// you remove the last tag from an image, the image is deleted from your -// repository. You can completely delete an image (and all of its tags) by -// specifying the digest of the image in your request. +// registry. Images are specified with either an imageTag or imageDigest . +// +// You can remove a tag from an image by specifying the image's tag in your +// request. When you remove the last tag from an image, the image is deleted from +// your repository. +// +// You can completely delete an image (and all of its tags) by specifying the +// digest of the image in your request. func (c *Client) BatchDeleteImage(ctx context.Context, params *BatchDeleteImageInput, optFns ...func(*Options)) (*BatchDeleteImageOutput, error) { if params == nil { params = &BatchDeleteImageInput{} @@ -73,6 +71,9 @@ type BatchDeleteImageOutput struct { } func (c *Client) addOperationBatchDeleteImageMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpBatchDeleteImage{}, middleware.After) if err != nil { return err @@ -81,34 +82,38 @@ func (c *Client) addOperationBatchDeleteImageMiddlewares(stack *middleware.Stack if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "BatchDeleteImage"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -120,7 +125,13 @@ func (c *Client) addOperationBatchDeleteImageMiddlewares(stack *middleware.Stack if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addBatchDeleteImageResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpBatchDeleteImageValidationMiddleware(stack); err != nil { @@ -129,7 +140,7 @@ func (c *Client) addOperationBatchDeleteImageMiddlewares(stack *middleware.Stack if err = stack.Initialize.Add(newServiceMetadataMiddleware_opBatchDeleteImage(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -141,7 +152,19 @@ func (c *Client) addOperationBatchDeleteImageMiddlewares(stack *middleware.Stack if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -151,130 +174,6 @@ func newServiceMetadataMiddleware_opBatchDeleteImage(region string) *awsmiddlewa return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "BatchDeleteImage", } } - -type opBatchDeleteImageResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opBatchDeleteImageResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opBatchDeleteImageResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addBatchDeleteImageResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opBatchDeleteImageResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_CompleteLayerUpload.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_CompleteLayerUpload.go index 3e93650ab5..0e5f50ea9e 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_CompleteLayerUpload.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_CompleteLayerUpload.go @@ -4,24 +4,22 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Informs Amazon ECR that the image layer upload is complete for a specified // public registry, repository name, and upload ID. You can optionally provide a -// sha256 digest of the image layer for data validation purposes. When an image is -// pushed, the CompleteLayerUpload API is called once for each new image layer to -// verify that the upload is complete. This operation is used by the Amazon ECR -// proxy and is not generally used by customers for pulling and pushing images. In -// most cases, you should use the docker CLI to pull, tag, and push images. +// sha256 digest of the image layer for data validation purposes. +// +// When an image is pushed, the CompleteLayerUpload API is called once for each +// new image layer to verify that the upload is complete. +// +// This operation is used by the Amazon ECR proxy and is not generally used by +// customers for pulling and pushing images. In most cases, you should use the +// docker CLI to pull, tag, and push images. func (c *Client) CompleteLayerUpload(ctx context.Context, params *CompleteLayerUploadInput, optFns ...func(*Options)) (*CompleteLayerUploadOutput, error) { if params == nil { params = &CompleteLayerUploadInput{} @@ -50,8 +48,7 @@ type CompleteLayerUploadInput struct { // This member is required. RepositoryName *string - // The upload ID from a previous InitiateLayerUpload operation to associate with - // the image layer. + // The upload ID from a previous InitiateLayerUpload operation to associate with the image layer. // // This member is required. UploadId *string @@ -85,6 +82,9 @@ type CompleteLayerUploadOutput struct { } func (c *Client) addOperationCompleteLayerUploadMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpCompleteLayerUpload{}, middleware.After) if err != nil { return err @@ -93,34 +93,38 @@ func (c *Client) addOperationCompleteLayerUploadMiddlewares(stack *middleware.St if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "CompleteLayerUpload"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -132,7 +136,13 @@ func (c *Client) addOperationCompleteLayerUploadMiddlewares(stack *middleware.St if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addCompleteLayerUploadResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpCompleteLayerUploadValidationMiddleware(stack); err != nil { @@ -141,7 +151,7 @@ func (c *Client) addOperationCompleteLayerUploadMiddlewares(stack *middleware.St if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCompleteLayerUpload(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -153,7 +163,19 @@ func (c *Client) addOperationCompleteLayerUploadMiddlewares(stack *middleware.St if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -163,130 +185,6 @@ func newServiceMetadataMiddleware_opCompleteLayerUpload(region string) *awsmiddl return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "CompleteLayerUpload", } } - -type opCompleteLayerUploadResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opCompleteLayerUploadResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opCompleteLayerUploadResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addCompleteLayerUploadResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opCompleteLayerUploadResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_CreateRepository.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_CreateRepository.go index 082ffca473..4ca5c18847 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_CreateRepository.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_CreateRepository.go @@ -4,21 +4,17 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecrpublic/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) -// Creates a repository in a public registry. For more information, see Amazon ECR -// repositories (https://docs.aws.amazon.com/AmazonECR/latest/userguide/Repositories.html) -// in the Amazon Elastic Container Registry User Guide. +// Creates a repository in a public registry. For more information, see [Amazon ECR repositories] in the +// Amazon Elastic Container Registry User Guide. +// +// [Amazon ECR repositories]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/Repositories.html func (c *Client) CreateRepository(ctx context.Context, params *CreateRepositoryInput, optFns ...func(*Options)) (*CreateRepositoryOutput, error) { if params == nil { params = &CreateRepositoryInput{} @@ -73,6 +69,9 @@ type CreateRepositoryOutput struct { } func (c *Client) addOperationCreateRepositoryMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateRepository{}, middleware.After) if err != nil { return err @@ -81,34 +80,38 @@ func (c *Client) addOperationCreateRepositoryMiddlewares(stack *middleware.Stack if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "CreateRepository"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -120,7 +123,13 @@ func (c *Client) addOperationCreateRepositoryMiddlewares(stack *middleware.Stack if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addCreateRepositoryResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpCreateRepositoryValidationMiddleware(stack); err != nil { @@ -129,7 +138,7 @@ func (c *Client) addOperationCreateRepositoryMiddlewares(stack *middleware.Stack if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateRepository(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -141,7 +150,19 @@ func (c *Client) addOperationCreateRepositoryMiddlewares(stack *middleware.Stack if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -151,130 +172,6 @@ func newServiceMetadataMiddleware_opCreateRepository(region string) *awsmiddlewa return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "CreateRepository", } } - -type opCreateRepositoryResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opCreateRepositoryResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opCreateRepositoryResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addCreateRepositoryResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opCreateRepositoryResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DeleteRepository.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DeleteRepository.go index 6f25f9010c..ca7cd7d3fb 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DeleteRepository.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DeleteRepository.go @@ -4,14 +4,9 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecrpublic/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -42,7 +37,7 @@ type DeleteRepositoryInput struct { // This member is required. RepositoryName *string - // The force option can be used to delete a repository that contains images. If + // The force option can be used to delete a repository that contains images. If // the force option is not used, the repository must be empty prior to deletion. Force bool @@ -66,6 +61,9 @@ type DeleteRepositoryOutput struct { } func (c *Client) addOperationDeleteRepositoryMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteRepository{}, middleware.After) if err != nil { return err @@ -74,34 +72,38 @@ func (c *Client) addOperationDeleteRepositoryMiddlewares(stack *middleware.Stack if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteRepository"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -113,7 +115,13 @@ func (c *Client) addOperationDeleteRepositoryMiddlewares(stack *middleware.Stack if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addDeleteRepositoryResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpDeleteRepositoryValidationMiddleware(stack); err != nil { @@ -122,7 +130,7 @@ func (c *Client) addOperationDeleteRepositoryMiddlewares(stack *middleware.Stack if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteRepository(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -134,7 +142,19 @@ func (c *Client) addOperationDeleteRepositoryMiddlewares(stack *middleware.Stack if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -144,130 +164,6 @@ func newServiceMetadataMiddleware_opDeleteRepository(region string) *awsmiddlewa return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "DeleteRepository", } } - -type opDeleteRepositoryResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opDeleteRepositoryResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opDeleteRepositoryResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addDeleteRepositoryResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opDeleteRepositoryResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DeleteRepositoryPolicy.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DeleteRepositoryPolicy.go index a8f26b8374..831a8483e4 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DeleteRepositoryPolicy.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DeleteRepositoryPolicy.go @@ -4,13 +4,8 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -65,6 +60,9 @@ type DeleteRepositoryPolicyOutput struct { } func (c *Client) addOperationDeleteRepositoryPolicyMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteRepositoryPolicy{}, middleware.After) if err != nil { return err @@ -73,34 +71,38 @@ func (c *Client) addOperationDeleteRepositoryPolicyMiddlewares(stack *middleware if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteRepositoryPolicy"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -112,7 +114,13 @@ func (c *Client) addOperationDeleteRepositoryPolicyMiddlewares(stack *middleware if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addDeleteRepositoryPolicyResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpDeleteRepositoryPolicyValidationMiddleware(stack); err != nil { @@ -121,7 +129,7 @@ func (c *Client) addOperationDeleteRepositoryPolicyMiddlewares(stack *middleware if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteRepositoryPolicy(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -133,7 +141,19 @@ func (c *Client) addOperationDeleteRepositoryPolicyMiddlewares(stack *middleware if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -143,130 +163,6 @@ func newServiceMetadataMiddleware_opDeleteRepositoryPolicy(region string) *awsmi return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "DeleteRepositoryPolicy", } } - -type opDeleteRepositoryPolicyResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opDeleteRepositoryPolicyResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opDeleteRepositoryPolicyResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addDeleteRepositoryPolicyResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opDeleteRepositoryPolicyResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DescribeImageTags.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DescribeImageTags.go index 49847d27c5..f43b7776f6 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DescribeImageTags.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DescribeImageTags.go @@ -4,14 +4,9 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecrpublic/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -82,6 +77,9 @@ type DescribeImageTagsOutput struct { } func (c *Client) addOperationDescribeImageTagsMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeImageTags{}, middleware.After) if err != nil { return err @@ -90,34 +88,38 @@ func (c *Client) addOperationDescribeImageTagsMiddlewares(stack *middleware.Stac if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeImageTags"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -129,7 +131,13 @@ func (c *Client) addOperationDescribeImageTagsMiddlewares(stack *middleware.Stac if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addDescribeImageTagsResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpDescribeImageTagsValidationMiddleware(stack); err != nil { @@ -138,7 +146,7 @@ func (c *Client) addOperationDescribeImageTagsMiddlewares(stack *middleware.Stac if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeImageTags(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -150,20 +158,24 @@ func (c *Client) addOperationDescribeImageTagsMiddlewares(stack *middleware.Stac if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil } -// DescribeImageTagsAPIClient is a client that implements the DescribeImageTags -// operation. -type DescribeImageTagsAPIClient interface { - DescribeImageTags(context.Context, *DescribeImageTagsInput, ...func(*Options)) (*DescribeImageTagsOutput, error) -} - -var _ DescribeImageTagsAPIClient = (*Client)(nil) - // DescribeImageTagsPaginatorOptions is the paginator options for DescribeImageTags type DescribeImageTagsPaginatorOptions struct { // The maximum number of repository results that's returned by DescribeImageTags @@ -234,6 +246,9 @@ func (p *DescribeImageTagsPaginator) NextPage(ctx context.Context, optFns ...fun } params.MaxResults = limit + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) result, err := p.client.DescribeImageTags(ctx, ¶ms, optFns...) if err != nil { return nil, err @@ -253,134 +268,18 @@ func (p *DescribeImageTagsPaginator) NextPage(ctx context.Context, optFns ...fun return result, nil } +// DescribeImageTagsAPIClient is a client that implements the DescribeImageTags +// operation. +type DescribeImageTagsAPIClient interface { + DescribeImageTags(context.Context, *DescribeImageTagsInput, ...func(*Options)) (*DescribeImageTagsOutput, error) +} + +var _ DescribeImageTagsAPIClient = (*Client)(nil) + func newServiceMetadataMiddleware_opDescribeImageTags(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "DescribeImageTags", } } - -type opDescribeImageTagsResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opDescribeImageTagsResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opDescribeImageTagsResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addDescribeImageTagsResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opDescribeImageTagsResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DescribeImages.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DescribeImages.go index 2060f6ed08..d77c2e2ac0 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DescribeImages.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DescribeImages.go @@ -4,23 +4,20 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecrpublic/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Returns metadata that's related to the images in a repository in a public -// registry. Beginning with Docker version 1.9, the Docker client compresses image -// layers before pushing them to a V2 Docker registry. The output of the docker -// images command shows the uncompressed image size. Therefore, it might return a -// larger image size than the image sizes that are returned by DescribeImages . +// registry. +// +// Beginning with Docker version 1.9, the Docker client compresses image layers +// before pushing them to a V2 Docker registry. The output of the docker images +// command shows the uncompressed image size. Therefore, it might return a larger +// image size than the image sizes that are returned by DescribeImages. func (c *Client) DescribeImages(ctx context.Context, params *DescribeImagesInput, optFns ...func(*Options)) (*DescribeImagesOutput, error) { if params == nil { params = &DescribeImagesInput{} @@ -89,6 +86,9 @@ type DescribeImagesOutput struct { } func (c *Client) addOperationDescribeImagesMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeImages{}, middleware.After) if err != nil { return err @@ -97,34 +97,38 @@ func (c *Client) addOperationDescribeImagesMiddlewares(stack *middleware.Stack, if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeImages"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -136,7 +140,13 @@ func (c *Client) addOperationDescribeImagesMiddlewares(stack *middleware.Stack, if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addDescribeImagesResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpDescribeImagesValidationMiddleware(stack); err != nil { @@ -145,7 +155,7 @@ func (c *Client) addOperationDescribeImagesMiddlewares(stack *middleware.Stack, if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeImages(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -157,20 +167,24 @@ func (c *Client) addOperationDescribeImagesMiddlewares(stack *middleware.Stack, if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil } -// DescribeImagesAPIClient is a client that implements the DescribeImages -// operation. -type DescribeImagesAPIClient interface { - DescribeImages(context.Context, *DescribeImagesInput, ...func(*Options)) (*DescribeImagesOutput, error) -} - -var _ DescribeImagesAPIClient = (*Client)(nil) - // DescribeImagesPaginatorOptions is the paginator options for DescribeImages type DescribeImagesPaginatorOptions struct { // The maximum number of repository results that's returned by DescribeImages in @@ -241,6 +255,9 @@ func (p *DescribeImagesPaginator) NextPage(ctx context.Context, optFns ...func(* } params.MaxResults = limit + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) result, err := p.client.DescribeImages(ctx, ¶ms, optFns...) if err != nil { return nil, err @@ -260,134 +277,18 @@ func (p *DescribeImagesPaginator) NextPage(ctx context.Context, optFns ...func(* return result, nil } +// DescribeImagesAPIClient is a client that implements the DescribeImages +// operation. +type DescribeImagesAPIClient interface { + DescribeImages(context.Context, *DescribeImagesInput, ...func(*Options)) (*DescribeImagesOutput, error) +} + +var _ DescribeImagesAPIClient = (*Client)(nil) + func newServiceMetadataMiddleware_opDescribeImages(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "DescribeImages", } } - -type opDescribeImagesResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opDescribeImagesResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opDescribeImagesResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addDescribeImagesResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opDescribeImagesResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DescribeRegistries.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DescribeRegistries.go index 6923ea084c..47aa6f4076 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DescribeRegistries.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DescribeRegistries.go @@ -4,14 +4,9 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecrpublic/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -48,9 +43,10 @@ type DescribeRegistriesInput struct { // request where maxResults was used and the results exceeded the value of that // parameter. Pagination continues from the end of the previous results that // returned the nextToken value. If there are no more results to return, this - // value is null . This token should be treated as an opaque identifier that is - // only used to retrieve the next items in a list and not for other programmatic - // purposes. + // value is null . + // + // This token should be treated as an opaque identifier that is only used to + // retrieve the next items in a list and not for other programmatic purposes. NextToken *string noSmithyDocumentSerde @@ -76,6 +72,9 @@ type DescribeRegistriesOutput struct { } func (c *Client) addOperationDescribeRegistriesMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeRegistries{}, middleware.After) if err != nil { return err @@ -84,34 +83,38 @@ func (c *Client) addOperationDescribeRegistriesMiddlewares(stack *middleware.Sta if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeRegistries"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -123,13 +126,19 @@ func (c *Client) addOperationDescribeRegistriesMiddlewares(stack *middleware.Sta if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addDescribeRegistriesResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeRegistries(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -141,20 +150,24 @@ func (c *Client) addOperationDescribeRegistriesMiddlewares(stack *middleware.Sta if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil } -// DescribeRegistriesAPIClient is a client that implements the DescribeRegistries -// operation. -type DescribeRegistriesAPIClient interface { - DescribeRegistries(context.Context, *DescribeRegistriesInput, ...func(*Options)) (*DescribeRegistriesOutput, error) -} - -var _ DescribeRegistriesAPIClient = (*Client)(nil) - // DescribeRegistriesPaginatorOptions is the paginator options for // DescribeRegistries type DescribeRegistriesPaginatorOptions struct { @@ -226,6 +239,9 @@ func (p *DescribeRegistriesPaginator) NextPage(ctx context.Context, optFns ...fu } params.MaxResults = limit + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) result, err := p.client.DescribeRegistries(ctx, ¶ms, optFns...) if err != nil { return nil, err @@ -245,134 +261,18 @@ func (p *DescribeRegistriesPaginator) NextPage(ctx context.Context, optFns ...fu return result, nil } +// DescribeRegistriesAPIClient is a client that implements the DescribeRegistries +// operation. +type DescribeRegistriesAPIClient interface { + DescribeRegistries(context.Context, *DescribeRegistriesInput, ...func(*Options)) (*DescribeRegistriesOutput, error) +} + +var _ DescribeRegistriesAPIClient = (*Client)(nil) + func newServiceMetadataMiddleware_opDescribeRegistries(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "DescribeRegistries", } } - -type opDescribeRegistriesResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opDescribeRegistriesResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opDescribeRegistriesResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addDescribeRegistriesResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opDescribeRegistriesResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DescribeRepositories.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DescribeRepositories.go index 4185abcc88..96642a085b 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DescribeRepositories.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_DescribeRepositories.go @@ -4,14 +4,9 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecrpublic/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -50,9 +45,10 @@ type DescribeRepositoriesInput struct { // the value of that parameter. Pagination continues from the end of the previous // results that returned the nextToken value. If there are no more results to // return, this value is null . If you specify repositories with repositoryNames , - // you can't use this option. This token should be treated as an opaque identifier - // that is only used to retrieve the next items in a list and not for other - // programmatic purposes. + // you can't use this option. + // + // This token should be treated as an opaque identifier that is only used to + // retrieve the next items in a list and not for other programmatic purposes. NextToken *string // The Amazon Web Services account ID that's associated with the registry that @@ -85,6 +81,9 @@ type DescribeRepositoriesOutput struct { } func (c *Client) addOperationDescribeRepositoriesMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeRepositories{}, middleware.After) if err != nil { return err @@ -93,34 +92,38 @@ func (c *Client) addOperationDescribeRepositoriesMiddlewares(stack *middleware.S if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeRepositories"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -132,13 +135,19 @@ func (c *Client) addOperationDescribeRepositoriesMiddlewares(stack *middleware.S if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addDescribeRepositoriesResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeRepositories(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -150,20 +159,24 @@ func (c *Client) addOperationDescribeRepositoriesMiddlewares(stack *middleware.S if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil } -// DescribeRepositoriesAPIClient is a client that implements the -// DescribeRepositories operation. -type DescribeRepositoriesAPIClient interface { - DescribeRepositories(context.Context, *DescribeRepositoriesInput, ...func(*Options)) (*DescribeRepositoriesOutput, error) -} - -var _ DescribeRepositoriesAPIClient = (*Client)(nil) - // DescribeRepositoriesPaginatorOptions is the paginator options for // DescribeRepositories type DescribeRepositoriesPaginatorOptions struct { @@ -236,6 +249,9 @@ func (p *DescribeRepositoriesPaginator) NextPage(ctx context.Context, optFns ... } params.MaxResults = limit + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) result, err := p.client.DescribeRepositories(ctx, ¶ms, optFns...) if err != nil { return nil, err @@ -255,134 +271,18 @@ func (p *DescribeRepositoriesPaginator) NextPage(ctx context.Context, optFns ... return result, nil } +// DescribeRepositoriesAPIClient is a client that implements the +// DescribeRepositories operation. +type DescribeRepositoriesAPIClient interface { + DescribeRepositories(context.Context, *DescribeRepositoriesInput, ...func(*Options)) (*DescribeRepositoriesOutput, error) +} + +var _ DescribeRepositoriesAPIClient = (*Client)(nil) + func newServiceMetadataMiddleware_opDescribeRepositories(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "DescribeRepositories", } } - -type opDescribeRepositoriesResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opDescribeRepositoriesResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opDescribeRepositoriesResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addDescribeRepositoriesResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opDescribeRepositoriesResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_GetAuthorizationToken.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_GetAuthorizationToken.go index c7b8801b50..ced2aec493 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_GetAuthorizationToken.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_GetAuthorizationToken.go @@ -4,14 +4,9 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecrpublic/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -52,6 +47,9 @@ type GetAuthorizationTokenOutput struct { } func (c *Client) addOperationGetAuthorizationTokenMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetAuthorizationToken{}, middleware.After) if err != nil { return err @@ -60,34 +58,38 @@ func (c *Client) addOperationGetAuthorizationTokenMiddlewares(stack *middleware. if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetAuthorizationToken"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -99,13 +101,19 @@ func (c *Client) addOperationGetAuthorizationTokenMiddlewares(stack *middleware. if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addGetAuthorizationTokenResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetAuthorizationToken(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -117,7 +125,19 @@ func (c *Client) addOperationGetAuthorizationTokenMiddlewares(stack *middleware. if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -127,130 +147,6 @@ func newServiceMetadataMiddleware_opGetAuthorizationToken(region string) *awsmid return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "GetAuthorizationToken", } } - -type opGetAuthorizationTokenResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opGetAuthorizationTokenResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opGetAuthorizationTokenResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addGetAuthorizationTokenResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opGetAuthorizationTokenResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_GetRegistryCatalogData.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_GetRegistryCatalogData.go index 42758d2956..3b46f123ec 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_GetRegistryCatalogData.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_GetRegistryCatalogData.go @@ -4,14 +4,9 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecrpublic/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -50,6 +45,9 @@ type GetRegistryCatalogDataOutput struct { } func (c *Client) addOperationGetRegistryCatalogDataMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetRegistryCatalogData{}, middleware.After) if err != nil { return err @@ -58,34 +56,38 @@ func (c *Client) addOperationGetRegistryCatalogDataMiddlewares(stack *middleware if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetRegistryCatalogData"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -97,13 +99,19 @@ func (c *Client) addOperationGetRegistryCatalogDataMiddlewares(stack *middleware if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addGetRegistryCatalogDataResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetRegistryCatalogData(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -115,7 +123,19 @@ func (c *Client) addOperationGetRegistryCatalogDataMiddlewares(stack *middleware if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -125,130 +145,6 @@ func newServiceMetadataMiddleware_opGetRegistryCatalogData(region string) *awsmi return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "GetRegistryCatalogData", } } - -type opGetRegistryCatalogDataResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opGetRegistryCatalogDataResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opGetRegistryCatalogDataResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addGetRegistryCatalogDataResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opGetRegistryCatalogDataResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_GetRepositoryCatalogData.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_GetRepositoryCatalogData.go index 7e2a74fb52..5f80026f18 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_GetRepositoryCatalogData.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_GetRepositoryCatalogData.go @@ -4,14 +4,9 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecrpublic/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -60,6 +55,9 @@ type GetRepositoryCatalogDataOutput struct { } func (c *Client) addOperationGetRepositoryCatalogDataMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetRepositoryCatalogData{}, middleware.After) if err != nil { return err @@ -68,34 +66,38 @@ func (c *Client) addOperationGetRepositoryCatalogDataMiddlewares(stack *middlewa if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetRepositoryCatalogData"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -107,7 +109,13 @@ func (c *Client) addOperationGetRepositoryCatalogDataMiddlewares(stack *middlewa if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addGetRepositoryCatalogDataResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpGetRepositoryCatalogDataValidationMiddleware(stack); err != nil { @@ -116,7 +124,7 @@ func (c *Client) addOperationGetRepositoryCatalogDataMiddlewares(stack *middlewa if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetRepositoryCatalogData(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -128,7 +136,19 @@ func (c *Client) addOperationGetRepositoryCatalogDataMiddlewares(stack *middlewa if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -138,130 +158,6 @@ func newServiceMetadataMiddleware_opGetRepositoryCatalogData(region string) *aws return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "GetRepositoryCatalogData", } } - -type opGetRepositoryCatalogDataResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opGetRepositoryCatalogDataResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opGetRepositoryCatalogDataResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addGetRepositoryCatalogDataResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opGetRepositoryCatalogDataResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_GetRepositoryPolicy.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_GetRepositoryPolicy.go index f104aada55..ea637e3af4 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_GetRepositoryPolicy.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_GetRepositoryPolicy.go @@ -4,13 +4,8 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -65,6 +60,9 @@ type GetRepositoryPolicyOutput struct { } func (c *Client) addOperationGetRepositoryPolicyMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetRepositoryPolicy{}, middleware.After) if err != nil { return err @@ -73,34 +71,38 @@ func (c *Client) addOperationGetRepositoryPolicyMiddlewares(stack *middleware.St if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetRepositoryPolicy"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -112,7 +114,13 @@ func (c *Client) addOperationGetRepositoryPolicyMiddlewares(stack *middleware.St if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addGetRepositoryPolicyResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpGetRepositoryPolicyValidationMiddleware(stack); err != nil { @@ -121,7 +129,7 @@ func (c *Client) addOperationGetRepositoryPolicyMiddlewares(stack *middleware.St if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetRepositoryPolicy(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -133,7 +141,19 @@ func (c *Client) addOperationGetRepositoryPolicyMiddlewares(stack *middleware.St if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -143,130 +163,6 @@ func newServiceMetadataMiddleware_opGetRepositoryPolicy(region string) *awsmiddl return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "GetRepositoryPolicy", } } - -type opGetRepositoryPolicyResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opGetRepositoryPolicyResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opGetRepositoryPolicyResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addGetRepositoryPolicyResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opGetRepositoryPolicyResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_InitiateLayerUpload.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_InitiateLayerUpload.go index ee562fbadd..a8e642aab2 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_InitiateLayerUpload.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_InitiateLayerUpload.go @@ -4,23 +4,21 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) -// Notifies Amazon ECR that you intend to upload an image layer. When an image is -// pushed, the InitiateLayerUpload API is called once for each image layer that -// hasn't already been uploaded. Whether an image layer uploads is determined by -// the BatchCheckLayerAvailability API action. This operation is used by the Amazon -// ECR proxy and is not generally used by customers for pulling and pushing images. -// In most cases, you should use the docker CLI to pull, tag, and push images. +// Notifies Amazon ECR that you intend to upload an image layer. +// +// When an image is pushed, the InitiateLayerUpload API is called once for each +// image layer that hasn't already been uploaded. Whether an image layer uploads is +// determined by the BatchCheckLayerAvailability API action. +// +// This operation is used by the Amazon ECR proxy and is not generally used by +// customers for pulling and pushing images. In most cases, you should use the +// docker CLI to pull, tag, and push images. func (c *Client) InitiateLayerUpload(ctx context.Context, params *InitiateLayerUploadInput, optFns ...func(*Options)) (*InitiateLayerUploadOutput, error) { if params == nil { params = &InitiateLayerUploadInput{} @@ -56,8 +54,8 @@ type InitiateLayerUploadOutput struct { // The size, in bytes, that Amazon ECR expects future layer part uploads to be. PartSize *int64 - // The upload ID for the layer upload. This parameter is passed to further - // UploadLayerPart and CompleteLayerUpload operations. + // The upload ID for the layer upload. This parameter is passed to further UploadLayerPart and CompleteLayerUpload + // operations. UploadId *string // Metadata pertaining to the operation's result. @@ -67,6 +65,9 @@ type InitiateLayerUploadOutput struct { } func (c *Client) addOperationInitiateLayerUploadMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpInitiateLayerUpload{}, middleware.After) if err != nil { return err @@ -75,34 +76,38 @@ func (c *Client) addOperationInitiateLayerUploadMiddlewares(stack *middleware.St if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "InitiateLayerUpload"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -114,7 +119,13 @@ func (c *Client) addOperationInitiateLayerUploadMiddlewares(stack *middleware.St if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addInitiateLayerUploadResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpInitiateLayerUploadValidationMiddleware(stack); err != nil { @@ -123,7 +134,7 @@ func (c *Client) addOperationInitiateLayerUploadMiddlewares(stack *middleware.St if err = stack.Initialize.Add(newServiceMetadataMiddleware_opInitiateLayerUpload(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -135,7 +146,19 @@ func (c *Client) addOperationInitiateLayerUploadMiddlewares(stack *middleware.St if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -145,130 +168,6 @@ func newServiceMetadataMiddleware_opInitiateLayerUpload(region string) *awsmiddl return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "InitiateLayerUpload", } } - -type opInitiateLayerUploadResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opInitiateLayerUploadResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opInitiateLayerUploadResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addInitiateLayerUploadResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opInitiateLayerUploadResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_ListTagsForResource.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_ListTagsForResource.go index 34e23ec8cb..9624524c06 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_ListTagsForResource.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_ListTagsForResource.go @@ -4,14 +4,9 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecrpublic/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -55,6 +50,9 @@ type ListTagsForResourceOutput struct { } func (c *Client) addOperationListTagsForResourceMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpListTagsForResource{}, middleware.After) if err != nil { return err @@ -63,34 +61,38 @@ func (c *Client) addOperationListTagsForResourceMiddlewares(stack *middleware.St if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "ListTagsForResource"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -102,7 +104,13 @@ func (c *Client) addOperationListTagsForResourceMiddlewares(stack *middleware.St if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addListTagsForResourceResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpListTagsForResourceValidationMiddleware(stack); err != nil { @@ -111,7 +119,7 @@ func (c *Client) addOperationListTagsForResourceMiddlewares(stack *middleware.St if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListTagsForResource(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -123,7 +131,19 @@ func (c *Client) addOperationListTagsForResourceMiddlewares(stack *middleware.St if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -133,130 +153,6 @@ func newServiceMetadataMiddleware_opListTagsForResource(region string) *awsmiddl return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "ListTagsForResource", } } - -type opListTagsForResourceResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opListTagsForResourceResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opListTagsForResourceResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addListTagsForResourceResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opListTagsForResourceResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_PutImage.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_PutImage.go index 5aa1d530a1..25f8cda005 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_PutImage.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_PutImage.go @@ -4,24 +4,23 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecrpublic/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Creates or updates the image manifest and tags that are associated with an -// image. When an image is pushed and all new image layers have been uploaded, the +// image. +// +// When an image is pushed and all new image layers have been uploaded, the // PutImage API is called once to create or update the image manifest and the tags -// that are associated with the image. This operation is used by the Amazon ECR -// proxy and is not generally used by customers for pulling and pushing images. In -// most cases, you should use the docker CLI to pull, tag, and push images. +// that are associated with the image. +// +// This operation is used by the Amazon ECR proxy and is not generally used by +// customers for pulling and pushing images. In most cases, you should use the +// docker CLI to pull, tag, and push images. func (c *Client) PutImage(ctx context.Context, params *PutImageInput, optFns ...func(*Options)) (*PutImageOutput, error) { if params == nil { params = &PutImageInput{} @@ -82,6 +81,9 @@ type PutImageOutput struct { } func (c *Client) addOperationPutImageMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpPutImage{}, middleware.After) if err != nil { return err @@ -90,34 +92,38 @@ func (c *Client) addOperationPutImageMiddlewares(stack *middleware.Stack, option if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "PutImage"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -129,7 +135,13 @@ func (c *Client) addOperationPutImageMiddlewares(stack *middleware.Stack, option if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addPutImageResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpPutImageValidationMiddleware(stack); err != nil { @@ -138,7 +150,7 @@ func (c *Client) addOperationPutImageMiddlewares(stack *middleware.Stack, option if err = stack.Initialize.Add(newServiceMetadataMiddleware_opPutImage(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -150,7 +162,19 @@ func (c *Client) addOperationPutImageMiddlewares(stack *middleware.Stack, option if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -160,130 +184,6 @@ func newServiceMetadataMiddleware_opPutImage(region string) *awsmiddleware.Regis return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "PutImage", } } - -type opPutImageResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opPutImageResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opPutImageResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addPutImageResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opPutImageResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_PutRegistryCatalogData.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_PutRegistryCatalogData.go index bc2e24c79d..233fba1575 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_PutRegistryCatalogData.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_PutRegistryCatalogData.go @@ -4,14 +4,9 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecrpublic/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -35,8 +30,10 @@ func (c *Client) PutRegistryCatalogData(ctx context.Context, params *PutRegistry type PutRegistryCatalogDataInput struct { // The display name for a public registry. The display name is shown as the - // repository author in the Amazon ECR Public Gallery. The registry display name is - // only publicly visible in the Amazon ECR Public Gallery for verified accounts. + // repository author in the Amazon ECR Public Gallery. + // + // The registry display name is only publicly visible in the Amazon ECR Public + // Gallery for verified accounts. DisplayName *string noSmithyDocumentSerde @@ -56,6 +53,9 @@ type PutRegistryCatalogDataOutput struct { } func (c *Client) addOperationPutRegistryCatalogDataMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpPutRegistryCatalogData{}, middleware.After) if err != nil { return err @@ -64,34 +64,38 @@ func (c *Client) addOperationPutRegistryCatalogDataMiddlewares(stack *middleware if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "PutRegistryCatalogData"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -103,13 +107,19 @@ func (c *Client) addOperationPutRegistryCatalogDataMiddlewares(stack *middleware if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addPutRegistryCatalogDataResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opPutRegistryCatalogData(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -121,7 +131,19 @@ func (c *Client) addOperationPutRegistryCatalogDataMiddlewares(stack *middleware if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -131,130 +153,6 @@ func newServiceMetadataMiddleware_opPutRegistryCatalogData(region string) *awsmi return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "PutRegistryCatalogData", } } - -type opPutRegistryCatalogDataResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opPutRegistryCatalogDataResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opPutRegistryCatalogDataResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addPutRegistryCatalogDataResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opPutRegistryCatalogDataResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_PutRepositoryCatalogData.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_PutRepositoryCatalogData.go index c76c4cf1ca..59bf740b22 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_PutRepositoryCatalogData.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_PutRepositoryCatalogData.go @@ -4,14 +4,9 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecrpublic/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -65,6 +60,9 @@ type PutRepositoryCatalogDataOutput struct { } func (c *Client) addOperationPutRepositoryCatalogDataMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpPutRepositoryCatalogData{}, middleware.After) if err != nil { return err @@ -73,34 +71,38 @@ func (c *Client) addOperationPutRepositoryCatalogDataMiddlewares(stack *middlewa if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "PutRepositoryCatalogData"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -112,7 +114,13 @@ func (c *Client) addOperationPutRepositoryCatalogDataMiddlewares(stack *middlewa if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addPutRepositoryCatalogDataResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpPutRepositoryCatalogDataValidationMiddleware(stack); err != nil { @@ -121,7 +129,7 @@ func (c *Client) addOperationPutRepositoryCatalogDataMiddlewares(stack *middlewa if err = stack.Initialize.Add(newServiceMetadataMiddleware_opPutRepositoryCatalogData(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -133,7 +141,19 @@ func (c *Client) addOperationPutRepositoryCatalogDataMiddlewares(stack *middlewa if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -143,130 +163,6 @@ func newServiceMetadataMiddleware_opPutRepositoryCatalogData(region string) *aws return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "PutRepositoryCatalogData", } } - -type opPutRepositoryCatalogDataResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opPutRepositoryCatalogDataResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opPutRepositoryCatalogDataResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addPutRepositoryCatalogDataResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opPutRepositoryCatalogDataResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_SetRepositoryPolicy.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_SetRepositoryPolicy.go index 72a968686f..d49bc941be 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_SetRepositoryPolicy.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_SetRepositoryPolicy.go @@ -4,20 +4,17 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Applies a repository policy to the specified public repository to control -// access permissions. For more information, see Amazon ECR Repository Policies (https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-policies.html) -// in the Amazon Elastic Container Registry User Guide. +// access permissions. For more information, see [Amazon ECR Repository Policies]in the Amazon Elastic Container +// Registry User Guide. +// +// [Amazon ECR Repository Policies]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-policies.html func (c *Client) SetRepositoryPolicy(ctx context.Context, params *SetRepositoryPolicyInput, optFns ...func(*Options)) (*SetRepositoryPolicyOutput, error) { if params == nil { params = &SetRepositoryPolicyInput{} @@ -36,8 +33,9 @@ func (c *Client) SetRepositoryPolicy(ctx context.Context, params *SetRepositoryP type SetRepositoryPolicyInput struct { // The JSON repository policy text to apply to the repository. For more - // information, see Amazon ECR Repository Policies (https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-policy-examples.html) - // in the Amazon Elastic Container Registry User Guide. + // information, see [Amazon ECR Repository Policies]in the Amazon Elastic Container Registry User Guide. + // + // [Amazon ECR Repository Policies]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-policy-examples.html // // This member is required. PolicyText *string @@ -48,8 +46,8 @@ type SetRepositoryPolicyInput struct { RepositoryName *string // If the policy that you want to set on a repository policy would prevent you - // from setting another policy in the future, you must force the - // SetRepositoryPolicy operation. This prevents accidental repository lockouts. + // from setting another policy in the future, you must force the SetRepositoryPolicyoperation. This + // prevents accidental repository lockouts. Force bool // The Amazon Web Services account ID that's associated with the registry that @@ -78,6 +76,9 @@ type SetRepositoryPolicyOutput struct { } func (c *Client) addOperationSetRepositoryPolicyMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpSetRepositoryPolicy{}, middleware.After) if err != nil { return err @@ -86,34 +87,38 @@ func (c *Client) addOperationSetRepositoryPolicyMiddlewares(stack *middleware.St if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "SetRepositoryPolicy"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -125,7 +130,13 @@ func (c *Client) addOperationSetRepositoryPolicyMiddlewares(stack *middleware.St if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addSetRepositoryPolicyResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpSetRepositoryPolicyValidationMiddleware(stack); err != nil { @@ -134,7 +145,7 @@ func (c *Client) addOperationSetRepositoryPolicyMiddlewares(stack *middleware.St if err = stack.Initialize.Add(newServiceMetadataMiddleware_opSetRepositoryPolicy(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -146,7 +157,19 @@ func (c *Client) addOperationSetRepositoryPolicyMiddlewares(stack *middleware.St if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -156,130 +179,6 @@ func newServiceMetadataMiddleware_opSetRepositoryPolicy(region string) *awsmiddl return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "SetRepositoryPolicy", } } - -type opSetRepositoryPolicyResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opSetRepositoryPolicyResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opSetRepositoryPolicyResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addSetRepositoryPolicyResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opSetRepositoryPolicyResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_TagResource.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_TagResource.go index 94fe4edf11..1dfb2dd784 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_TagResource.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_TagResource.go @@ -4,14 +4,9 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/ecrpublic/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -61,6 +56,9 @@ type TagResourceOutput struct { } func (c *Client) addOperationTagResourceMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpTagResource{}, middleware.After) if err != nil { return err @@ -69,34 +67,38 @@ func (c *Client) addOperationTagResourceMiddlewares(stack *middleware.Stack, opt if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "TagResource"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -108,7 +110,13 @@ func (c *Client) addOperationTagResourceMiddlewares(stack *middleware.Stack, opt if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addTagResourceResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpTagResourceValidationMiddleware(stack); err != nil { @@ -117,7 +125,7 @@ func (c *Client) addOperationTagResourceMiddlewares(stack *middleware.Stack, opt if err = stack.Initialize.Add(newServiceMetadataMiddleware_opTagResource(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -129,7 +137,19 @@ func (c *Client) addOperationTagResourceMiddlewares(stack *middleware.Stack, opt if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -139,130 +159,6 @@ func newServiceMetadataMiddleware_opTagResource(region string) *awsmiddleware.Re return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "TagResource", } } - -type opTagResourceResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opTagResourceResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opTagResourceResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addTagResourceResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opTagResourceResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_UntagResource.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_UntagResource.go index bff2b1c3a4..83b57e0ad9 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_UntagResource.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_UntagResource.go @@ -4,13 +4,8 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -55,6 +50,9 @@ type UntagResourceOutput struct { } func (c *Client) addOperationUntagResourceMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpUntagResource{}, middleware.After) if err != nil { return err @@ -63,34 +61,38 @@ func (c *Client) addOperationUntagResourceMiddlewares(stack *middleware.Stack, o if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "UntagResource"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -102,7 +104,13 @@ func (c *Client) addOperationUntagResourceMiddlewares(stack *middleware.Stack, o if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addUntagResourceResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpUntagResourceValidationMiddleware(stack); err != nil { @@ -111,7 +119,7 @@ func (c *Client) addOperationUntagResourceMiddlewares(stack *middleware.Stack, o if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUntagResource(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -123,7 +131,19 @@ func (c *Client) addOperationUntagResourceMiddlewares(stack *middleware.Stack, o if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -133,130 +153,6 @@ func newServiceMetadataMiddleware_opUntagResource(region string) *awsmiddleware. return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "UntagResource", } } - -type opUntagResourceResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opUntagResourceResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opUntagResourceResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addUntagResourceResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opUntagResourceResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_UploadLayerPart.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_UploadLayerPart.go index dadc5f39cc..9a81c0597f 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_UploadLayerPart.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/api_op_UploadLayerPart.go @@ -4,23 +4,21 @@ package ecrpublic import ( "context" - "errors" "fmt" - "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) -// Uploads an image layer part to Amazon ECR. When an image is pushed, each new -// image layer is uploaded in parts. The maximum size of each image layer part can -// be 20971520 bytes (about 20MB). The UploadLayerPart API is called once for each -// new image layer part. This operation is used by the Amazon ECR proxy and is not -// generally used by customers for pulling and pushing images. In most cases, you -// should use the docker CLI to pull, tag, and push images. +// Uploads an image layer part to Amazon ECR. +// +// When an image is pushed, each new image layer is uploaded in parts. The maximum +// size of each image layer part can be 20971520 bytes (about 20MB). The +// UploadLayerPart API is called once for each new image layer part. +// +// This operation is used by the Amazon ECR proxy and is not generally used by +// customers for pulling and pushing images. In most cases, you should use the +// docker CLI to pull, tag, and push images. func (c *Client) UploadLayerPart(ctx context.Context, params *UploadLayerPartInput, optFns ...func(*Options)) (*UploadLayerPartOutput, error) { if params == nil { params = &UploadLayerPartInput{} @@ -58,8 +56,8 @@ type UploadLayerPartInput struct { // This member is required. RepositoryName *string - // The upload ID from a previous InitiateLayerUpload operation to associate with - // the layer part upload. + // The upload ID from a previous InitiateLayerUpload operation to associate with the layer part + // upload. // // This member is required. UploadId *string @@ -93,6 +91,9 @@ type UploadLayerPartOutput struct { } func (c *Client) addOperationUploadLayerPartMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } err = stack.Serialize.Add(&awsAwsjson11_serializeOpUploadLayerPart{}, middleware.After) if err != nil { return err @@ -101,34 +102,38 @@ func (c *Client) addOperationUploadLayerPartMiddlewares(stack *middleware.Stack, if err != nil { return err } + if err := addProtocolFinalizerMiddlewares(stack, options, "UploadLayerPart"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { + if err = addClientRequestID(stack); err != nil { return err } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { + if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { + if err = addComputePayloadSHA256(stack); err != nil { return err } - if err = addRetryMiddlewares(stack, options); err != nil { + if err = addRetry(stack, options); err != nil { return err } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { + if err = addRawResponseToMetadata(stack); err != nil { return err } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { + if err = addRecordResponseTiming(stack); err != nil { return err } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { + if err = addSpanRetryLoop(stack, options); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { @@ -140,7 +145,13 @@ func (c *Client) addOperationUploadLayerPartMiddlewares(stack *middleware.Stack, if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } - if err = addUploadLayerPartResolveEndpointMiddleware(stack, options); err != nil { + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { return err } if err = addOpUploadLayerPartValidationMiddleware(stack); err != nil { @@ -149,7 +160,7 @@ func (c *Client) addOperationUploadLayerPartMiddlewares(stack *middleware.Stack, if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUploadLayerPart(options.Region), middleware.Before); err != nil { return err } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { + if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { @@ -161,7 +172,19 @@ func (c *Client) addOperationUploadLayerPartMiddlewares(stack *middleware.Stack, if err = addRequestResponseLogging(stack, options); err != nil { return err } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { return err } return nil @@ -171,130 +194,6 @@ func newServiceMetadataMiddleware_opUploadLayerPart(region string) *awsmiddlewar return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, - SigningName: "ecr-public", OperationName: "UploadLayerPart", } } - -type opUploadLayerPartResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opUploadLayerPartResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opUploadLayerPartResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "ecr-public" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "ecr-public" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("ecr-public") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addUploadLayerPartResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opUploadLayerPartResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/auth.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/auth.go new file mode 100644 index 0000000000..0d60de1a4e --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/auth.go @@ -0,0 +1,313 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package ecrpublic + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + smithy "github.com/aws/smithy-go" + smithyauth "github.com/aws/smithy-go/auth" + "github.com/aws/smithy-go/metrics" + "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +func bindAuthParamsRegion(_ interface{}, params *AuthResolverParameters, _ interface{}, options Options) { + params.Region = options.Region +} + +type setLegacyContextSigningOptionsMiddleware struct { +} + +func (*setLegacyContextSigningOptionsMiddleware) ID() string { + return "setLegacyContextSigningOptions" +} + +func (m *setLegacyContextSigningOptionsMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + rscheme := getResolvedAuthScheme(ctx) + schemeID := rscheme.Scheme.SchemeID() + + if sn := awsmiddleware.GetSigningName(ctx); sn != "" { + if schemeID == "aws.auth#sigv4" { + smithyhttp.SetSigV4SigningName(&rscheme.SignerProperties, sn) + } else if schemeID == "aws.auth#sigv4a" { + smithyhttp.SetSigV4ASigningName(&rscheme.SignerProperties, sn) + } + } + + if sr := awsmiddleware.GetSigningRegion(ctx); sr != "" { + if schemeID == "aws.auth#sigv4" { + smithyhttp.SetSigV4SigningRegion(&rscheme.SignerProperties, sr) + } else if schemeID == "aws.auth#sigv4a" { + smithyhttp.SetSigV4ASigningRegions(&rscheme.SignerProperties, []string{sr}) + } + } + + return next.HandleFinalize(ctx, in) +} + +func addSetLegacyContextSigningOptionsMiddleware(stack *middleware.Stack) error { + return stack.Finalize.Insert(&setLegacyContextSigningOptionsMiddleware{}, "Signing", middleware.Before) +} + +type withAnonymous struct { + resolver AuthSchemeResolver +} + +var _ AuthSchemeResolver = (*withAnonymous)(nil) + +func (v *withAnonymous) ResolveAuthSchemes(ctx context.Context, params *AuthResolverParameters) ([]*smithyauth.Option, error) { + opts, err := v.resolver.ResolveAuthSchemes(ctx, params) + if err != nil { + return nil, err + } + + opts = append(opts, &smithyauth.Option{ + SchemeID: smithyauth.SchemeIDAnonymous, + }) + return opts, nil +} + +func wrapWithAnonymousAuth(options *Options) { + if _, ok := options.AuthSchemeResolver.(*defaultAuthSchemeResolver); !ok { + return + } + + options.AuthSchemeResolver = &withAnonymous{ + resolver: options.AuthSchemeResolver, + } +} + +// AuthResolverParameters contains the set of inputs necessary for auth scheme +// resolution. +type AuthResolverParameters struct { + // The name of the operation being invoked. + Operation string + + // The region in which the operation is being invoked. + Region string +} + +func bindAuthResolverParams(ctx context.Context, operation string, input interface{}, options Options) *AuthResolverParameters { + params := &AuthResolverParameters{ + Operation: operation, + } + + bindAuthParamsRegion(ctx, params, input, options) + + return params +} + +// AuthSchemeResolver returns a set of possible authentication options for an +// operation. +type AuthSchemeResolver interface { + ResolveAuthSchemes(context.Context, *AuthResolverParameters) ([]*smithyauth.Option, error) +} + +type defaultAuthSchemeResolver struct{} + +var _ AuthSchemeResolver = (*defaultAuthSchemeResolver)(nil) + +func (*defaultAuthSchemeResolver) ResolveAuthSchemes(ctx context.Context, params *AuthResolverParameters) ([]*smithyauth.Option, error) { + if overrides, ok := operationAuthOptions[params.Operation]; ok { + return overrides(params), nil + } + return serviceAuthOptions(params), nil +} + +var operationAuthOptions = map[string]func(*AuthResolverParameters) []*smithyauth.Option{} + +func serviceAuthOptions(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + { + SchemeID: smithyauth.SchemeIDSigV4, + SignerProperties: func() smithy.Properties { + var props smithy.Properties + smithyhttp.SetSigV4SigningName(&props, "ecr-public") + smithyhttp.SetSigV4SigningRegion(&props, params.Region) + return props + }(), + }, + } +} + +type resolveAuthSchemeMiddleware struct { + operation string + options Options +} + +func (*resolveAuthSchemeMiddleware) ID() string { + return "ResolveAuthScheme" +} + +func (m *resolveAuthSchemeMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "ResolveAuthScheme") + defer span.End() + + params := bindAuthResolverParams(ctx, m.operation, getOperationInput(ctx), m.options) + options, err := m.options.AuthSchemeResolver.ResolveAuthSchemes(ctx, params) + if err != nil { + return out, metadata, fmt.Errorf("resolve auth scheme: %w", err) + } + + scheme, ok := m.selectScheme(options) + if !ok { + return out, metadata, fmt.Errorf("could not select an auth scheme") + } + + ctx = setResolvedAuthScheme(ctx, scheme) + + span.SetProperty("auth.scheme_id", scheme.Scheme.SchemeID()) + span.End() + return next.HandleFinalize(ctx, in) +} + +func (m *resolveAuthSchemeMiddleware) selectScheme(options []*smithyauth.Option) (*resolvedAuthScheme, bool) { + for _, option := range options { + if option.SchemeID == smithyauth.SchemeIDAnonymous { + return newResolvedAuthScheme(smithyhttp.NewAnonymousScheme(), option), true + } + + for _, scheme := range m.options.AuthSchemes { + if scheme.SchemeID() != option.SchemeID { + continue + } + + if scheme.IdentityResolver(m.options) != nil { + return newResolvedAuthScheme(scheme, option), true + } + } + } + + return nil, false +} + +type resolvedAuthSchemeKey struct{} + +type resolvedAuthScheme struct { + Scheme smithyhttp.AuthScheme + IdentityProperties smithy.Properties + SignerProperties smithy.Properties +} + +func newResolvedAuthScheme(scheme smithyhttp.AuthScheme, option *smithyauth.Option) *resolvedAuthScheme { + return &resolvedAuthScheme{ + Scheme: scheme, + IdentityProperties: option.IdentityProperties, + SignerProperties: option.SignerProperties, + } +} + +func setResolvedAuthScheme(ctx context.Context, scheme *resolvedAuthScheme) context.Context { + return middleware.WithStackValue(ctx, resolvedAuthSchemeKey{}, scheme) +} + +func getResolvedAuthScheme(ctx context.Context) *resolvedAuthScheme { + v, _ := middleware.GetStackValue(ctx, resolvedAuthSchemeKey{}).(*resolvedAuthScheme) + return v +} + +type getIdentityMiddleware struct { + options Options +} + +func (*getIdentityMiddleware) ID() string { + return "GetIdentity" +} + +func (m *getIdentityMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + innerCtx, span := tracing.StartSpan(ctx, "GetIdentity") + defer span.End() + + rscheme := getResolvedAuthScheme(innerCtx) + if rscheme == nil { + return out, metadata, fmt.Errorf("no resolved auth scheme") + } + + resolver := rscheme.Scheme.IdentityResolver(m.options) + if resolver == nil { + return out, metadata, fmt.Errorf("no identity resolver") + } + + identity, err := timeOperationMetric(ctx, "client.call.resolve_identity_duration", + func() (smithyauth.Identity, error) { + return resolver.GetIdentity(innerCtx, rscheme.IdentityProperties) + }, + func(o *metrics.RecordMetricOptions) { + o.Properties.Set("auth.scheme_id", rscheme.Scheme.SchemeID()) + }) + if err != nil { + return out, metadata, fmt.Errorf("get identity: %w", err) + } + + ctx = setIdentity(ctx, identity) + + span.End() + return next.HandleFinalize(ctx, in) +} + +type identityKey struct{} + +func setIdentity(ctx context.Context, identity smithyauth.Identity) context.Context { + return middleware.WithStackValue(ctx, identityKey{}, identity) +} + +func getIdentity(ctx context.Context) smithyauth.Identity { + v, _ := middleware.GetStackValue(ctx, identityKey{}).(smithyauth.Identity) + return v +} + +type signRequestMiddleware struct { + options Options +} + +func (*signRequestMiddleware) ID() string { + return "Signing" +} + +func (m *signRequestMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "SignRequest") + defer span.End() + + req, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, fmt.Errorf("unexpected transport type %T", in.Request) + } + + rscheme := getResolvedAuthScheme(ctx) + if rscheme == nil { + return out, metadata, fmt.Errorf("no resolved auth scheme") + } + + identity := getIdentity(ctx) + if identity == nil { + return out, metadata, fmt.Errorf("no identity") + } + + signer := rscheme.Scheme.Signer() + if signer == nil { + return out, metadata, fmt.Errorf("no signer") + } + + _, err = timeOperationMetric(ctx, "client.call.signing_duration", func() (any, error) { + return nil, signer.SignRequest(ctx, req, identity, rscheme.SignerProperties) + }, func(o *metrics.RecordMetricOptions) { + o.Properties.Set("auth.scheme_id", rscheme.Scheme.SchemeID()) + }) + if err != nil { + return out, metadata, fmt.Errorf("sign request: %w", err) + } + + span.End() + return next.HandleFinalize(ctx, in) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/deserializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/deserializers.go index 0ef759a1ca..e8796324de 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/deserializers.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/deserializers.go @@ -14,11 +14,21 @@ import ( "github.com/aws/smithy-go/middleware" "github.com/aws/smithy-go/ptr" smithytime "github.com/aws/smithy-go/time" + "github.com/aws/smithy-go/tracing" smithyhttp "github.com/aws/smithy-go/transport/http" "io" "strings" + "time" ) +func deserializeS3Expires(v string) (*time.Time, error) { + t, err := smithytime.ParseHTTPDate(v) + if err != nil { + return nil, nil + } + return &t, nil +} + type awsAwsjson11_deserializeOpBatchCheckLayerAvailability struct { } @@ -34,6 +44,10 @@ func (m *awsAwsjson11_deserializeOpBatchCheckLayerAvailability) HandleDeserializ return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -87,9 +101,6 @@ func awsAwsjson11_deserializeOpErrorBatchCheckLayerAvailability(response *smithy errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -97,7 +108,7 @@ func awsAwsjson11_deserializeOpErrorBatchCheckLayerAvailability(response *smithy body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -109,13 +120,12 @@ func awsAwsjson11_deserializeOpErrorBatchCheckLayerAvailability(response *smithy } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -157,6 +167,10 @@ func (m *awsAwsjson11_deserializeOpBatchDeleteImage) HandleDeserialize(ctx conte return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -210,9 +224,6 @@ func awsAwsjson11_deserializeOpErrorBatchDeleteImage(response *smithyhttp.Respon errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -220,7 +231,7 @@ func awsAwsjson11_deserializeOpErrorBatchDeleteImage(response *smithyhttp.Respon body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -232,13 +243,12 @@ func awsAwsjson11_deserializeOpErrorBatchDeleteImage(response *smithyhttp.Respon } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -277,6 +287,10 @@ func (m *awsAwsjson11_deserializeOpCompleteLayerUpload) HandleDeserialize(ctx co return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -330,9 +344,6 @@ func awsAwsjson11_deserializeOpErrorCompleteLayerUpload(response *smithyhttp.Res errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -340,7 +351,7 @@ func awsAwsjson11_deserializeOpErrorCompleteLayerUpload(response *smithyhttp.Res body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -352,13 +363,12 @@ func awsAwsjson11_deserializeOpErrorCompleteLayerUpload(response *smithyhttp.Res } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("EmptyUploadException", errorCode): return awsAwsjson11_deserializeErrorEmptyUploadException(response, errorBody) @@ -415,6 +425,10 @@ func (m *awsAwsjson11_deserializeOpCreateRepository) HandleDeserialize(ctx conte return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -468,9 +482,6 @@ func awsAwsjson11_deserializeOpErrorCreateRepository(response *smithyhttp.Respon errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -478,7 +489,7 @@ func awsAwsjson11_deserializeOpErrorCreateRepository(response *smithyhttp.Respon body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -490,13 +501,12 @@ func awsAwsjson11_deserializeOpErrorCreateRepository(response *smithyhttp.Respon } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -544,6 +554,10 @@ func (m *awsAwsjson11_deserializeOpDeleteRepository) HandleDeserialize(ctx conte return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -597,9 +611,6 @@ func awsAwsjson11_deserializeOpErrorDeleteRepository(response *smithyhttp.Respon errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -607,7 +618,7 @@ func awsAwsjson11_deserializeOpErrorDeleteRepository(response *smithyhttp.Respon body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -619,13 +630,12 @@ func awsAwsjson11_deserializeOpErrorDeleteRepository(response *smithyhttp.Respon } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -667,6 +677,10 @@ func (m *awsAwsjson11_deserializeOpDeleteRepositoryPolicy) HandleDeserialize(ctx return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -720,9 +734,6 @@ func awsAwsjson11_deserializeOpErrorDeleteRepositoryPolicy(response *smithyhttp. errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -730,7 +741,7 @@ func awsAwsjson11_deserializeOpErrorDeleteRepositoryPolicy(response *smithyhttp. body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -742,13 +753,12 @@ func awsAwsjson11_deserializeOpErrorDeleteRepositoryPolicy(response *smithyhttp. } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -790,6 +800,10 @@ func (m *awsAwsjson11_deserializeOpDescribeImages) HandleDeserialize(ctx context return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -843,9 +857,6 @@ func awsAwsjson11_deserializeOpErrorDescribeImages(response *smithyhttp.Response errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -853,7 +864,7 @@ func awsAwsjson11_deserializeOpErrorDescribeImages(response *smithyhttp.Response body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -865,13 +876,12 @@ func awsAwsjson11_deserializeOpErrorDescribeImages(response *smithyhttp.Response } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("ImageNotFoundException", errorCode): return awsAwsjson11_deserializeErrorImageNotFoundException(response, errorBody) @@ -913,6 +923,10 @@ func (m *awsAwsjson11_deserializeOpDescribeImageTags) HandleDeserialize(ctx cont return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -966,9 +980,6 @@ func awsAwsjson11_deserializeOpErrorDescribeImageTags(response *smithyhttp.Respo errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -976,7 +987,7 @@ func awsAwsjson11_deserializeOpErrorDescribeImageTags(response *smithyhttp.Respo body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -988,13 +999,12 @@ func awsAwsjson11_deserializeOpErrorDescribeImageTags(response *smithyhttp.Respo } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -1033,6 +1043,10 @@ func (m *awsAwsjson11_deserializeOpDescribeRegistries) HandleDeserialize(ctx con return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -1086,9 +1100,6 @@ func awsAwsjson11_deserializeOpErrorDescribeRegistries(response *smithyhttp.Resp errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -1096,7 +1107,7 @@ func awsAwsjson11_deserializeOpErrorDescribeRegistries(response *smithyhttp.Resp body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1108,13 +1119,12 @@ func awsAwsjson11_deserializeOpErrorDescribeRegistries(response *smithyhttp.Resp } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -1150,6 +1160,10 @@ func (m *awsAwsjson11_deserializeOpDescribeRepositories) HandleDeserialize(ctx c return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -1203,9 +1217,6 @@ func awsAwsjson11_deserializeOpErrorDescribeRepositories(response *smithyhttp.Re errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -1213,7 +1224,7 @@ func awsAwsjson11_deserializeOpErrorDescribeRepositories(response *smithyhttp.Re body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1225,13 +1236,12 @@ func awsAwsjson11_deserializeOpErrorDescribeRepositories(response *smithyhttp.Re } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -1270,6 +1280,10 @@ func (m *awsAwsjson11_deserializeOpGetAuthorizationToken) HandleDeserialize(ctx return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -1323,9 +1337,6 @@ func awsAwsjson11_deserializeOpErrorGetAuthorizationToken(response *smithyhttp.R errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -1333,7 +1344,7 @@ func awsAwsjson11_deserializeOpErrorGetAuthorizationToken(response *smithyhttp.R body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1345,13 +1356,12 @@ func awsAwsjson11_deserializeOpErrorGetAuthorizationToken(response *smithyhttp.R } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -1387,6 +1397,10 @@ func (m *awsAwsjson11_deserializeOpGetRegistryCatalogData) HandleDeserialize(ctx return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -1440,9 +1454,6 @@ func awsAwsjson11_deserializeOpErrorGetRegistryCatalogData(response *smithyhttp. errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -1450,7 +1461,7 @@ func awsAwsjson11_deserializeOpErrorGetRegistryCatalogData(response *smithyhttp. body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1462,13 +1473,12 @@ func awsAwsjson11_deserializeOpErrorGetRegistryCatalogData(response *smithyhttp. } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("ServerException", errorCode): return awsAwsjson11_deserializeErrorServerException(response, errorBody) @@ -1501,6 +1511,10 @@ func (m *awsAwsjson11_deserializeOpGetRepositoryCatalogData) HandleDeserialize(c return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -1554,9 +1568,6 @@ func awsAwsjson11_deserializeOpErrorGetRepositoryCatalogData(response *smithyhtt errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -1564,7 +1575,7 @@ func awsAwsjson11_deserializeOpErrorGetRepositoryCatalogData(response *smithyhtt body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1576,13 +1587,12 @@ func awsAwsjson11_deserializeOpErrorGetRepositoryCatalogData(response *smithyhtt } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -1624,6 +1634,10 @@ func (m *awsAwsjson11_deserializeOpGetRepositoryPolicy) HandleDeserialize(ctx co return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -1677,9 +1691,6 @@ func awsAwsjson11_deserializeOpErrorGetRepositoryPolicy(response *smithyhttp.Res errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -1687,7 +1698,7 @@ func awsAwsjson11_deserializeOpErrorGetRepositoryPolicy(response *smithyhttp.Res body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1699,13 +1710,12 @@ func awsAwsjson11_deserializeOpErrorGetRepositoryPolicy(response *smithyhttp.Res } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -1747,6 +1757,10 @@ func (m *awsAwsjson11_deserializeOpInitiateLayerUpload) HandleDeserialize(ctx co return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -1800,9 +1814,6 @@ func awsAwsjson11_deserializeOpErrorInitiateLayerUpload(response *smithyhttp.Res errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -1810,7 +1821,7 @@ func awsAwsjson11_deserializeOpErrorInitiateLayerUpload(response *smithyhttp.Res body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1822,13 +1833,12 @@ func awsAwsjson11_deserializeOpErrorInitiateLayerUpload(response *smithyhttp.Res } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -1870,6 +1880,10 @@ func (m *awsAwsjson11_deserializeOpListTagsForResource) HandleDeserialize(ctx co return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -1923,9 +1937,6 @@ func awsAwsjson11_deserializeOpErrorListTagsForResource(response *smithyhttp.Res errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -1933,7 +1944,7 @@ func awsAwsjson11_deserializeOpErrorListTagsForResource(response *smithyhttp.Res body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1945,13 +1956,12 @@ func awsAwsjson11_deserializeOpErrorListTagsForResource(response *smithyhttp.Res } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -1990,6 +2000,10 @@ func (m *awsAwsjson11_deserializeOpPutImage) HandleDeserialize(ctx context.Conte return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -2043,9 +2057,6 @@ func awsAwsjson11_deserializeOpErrorPutImage(response *smithyhttp.Response, meta errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -2053,7 +2064,7 @@ func awsAwsjson11_deserializeOpErrorPutImage(response *smithyhttp.Response, meta body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -2065,13 +2076,12 @@ func awsAwsjson11_deserializeOpErrorPutImage(response *smithyhttp.Response, meta } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("ImageAlreadyExistsException", errorCode): return awsAwsjson11_deserializeErrorImageAlreadyExistsException(response, errorBody) @@ -2131,6 +2141,10 @@ func (m *awsAwsjson11_deserializeOpPutRegistryCatalogData) HandleDeserialize(ctx return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -2184,9 +2198,6 @@ func awsAwsjson11_deserializeOpErrorPutRegistryCatalogData(response *smithyhttp. errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -2194,7 +2205,7 @@ func awsAwsjson11_deserializeOpErrorPutRegistryCatalogData(response *smithyhttp. body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -2206,13 +2217,12 @@ func awsAwsjson11_deserializeOpErrorPutRegistryCatalogData(response *smithyhttp. } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -2248,6 +2258,10 @@ func (m *awsAwsjson11_deserializeOpPutRepositoryCatalogData) HandleDeserialize(c return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -2301,9 +2315,6 @@ func awsAwsjson11_deserializeOpErrorPutRepositoryCatalogData(response *smithyhtt errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -2311,7 +2322,7 @@ func awsAwsjson11_deserializeOpErrorPutRepositoryCatalogData(response *smithyhtt body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -2323,13 +2334,12 @@ func awsAwsjson11_deserializeOpErrorPutRepositoryCatalogData(response *smithyhtt } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -2368,6 +2378,10 @@ func (m *awsAwsjson11_deserializeOpSetRepositoryPolicy) HandleDeserialize(ctx co return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -2421,9 +2435,6 @@ func awsAwsjson11_deserializeOpErrorSetRepositoryPolicy(response *smithyhttp.Res errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -2431,7 +2442,7 @@ func awsAwsjson11_deserializeOpErrorSetRepositoryPolicy(response *smithyhttp.Res body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -2443,13 +2454,12 @@ func awsAwsjson11_deserializeOpErrorSetRepositoryPolicy(response *smithyhttp.Res } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -2488,6 +2498,10 @@ func (m *awsAwsjson11_deserializeOpTagResource) HandleDeserialize(ctx context.Co return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -2541,9 +2555,6 @@ func awsAwsjson11_deserializeOpErrorTagResource(response *smithyhttp.Response, m errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -2551,7 +2562,7 @@ func awsAwsjson11_deserializeOpErrorTagResource(response *smithyhttp.Response, m body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -2563,13 +2574,12 @@ func awsAwsjson11_deserializeOpErrorTagResource(response *smithyhttp.Response, m } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -2614,6 +2624,10 @@ func (m *awsAwsjson11_deserializeOpUntagResource) HandleDeserialize(ctx context. return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -2667,9 +2681,6 @@ func awsAwsjson11_deserializeOpErrorUntagResource(response *smithyhttp.Response, errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -2677,7 +2688,7 @@ func awsAwsjson11_deserializeOpErrorUntagResource(response *smithyhttp.Response, body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -2689,13 +2700,12 @@ func awsAwsjson11_deserializeOpErrorUntagResource(response *smithyhttp.Response, } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidParameterException", errorCode): return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) @@ -2740,6 +2750,10 @@ func (m *awsAwsjson11_deserializeOpUploadLayerPart) HandleDeserialize(ctx contex return out, metadata, err } + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} @@ -2793,9 +2807,6 @@ func awsAwsjson11_deserializeOpErrorUploadLayerPart(response *smithyhttp.Respons errorMessage := errorCode headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) @@ -2803,7 +2814,7 @@ func awsAwsjson11_deserializeOpErrorUploadLayerPart(response *smithyhttp.Respons body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) + bodyInfo, err := getProtocolErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -2815,13 +2826,12 @@ func awsAwsjson11_deserializeOpErrorUploadLayerPart(response *smithyhttp.Respons } errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) } - if len(message) != 0 { - errorMessage = message + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message } - switch { case strings.EqualFold("InvalidLayerPartException", errorCode): return awsAwsjson11_deserializeErrorInvalidLayerPartException(response, errorBody) @@ -3811,7 +3821,7 @@ func awsAwsjson11_deserializeDocumentEmptyUploadException(v **types.EmptyUploadE for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -3923,7 +3933,7 @@ func awsAwsjson11_deserializeDocumentImageAlreadyExistsException(v **types.Image for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -4107,7 +4117,7 @@ func awsAwsjson11_deserializeDocumentImageDigestDoesNotMatchException(v **types. for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -4318,7 +4328,7 @@ func awsAwsjson11_deserializeDocumentImageNotFoundException(v **types.ImageNotFo for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -4358,7 +4368,7 @@ func awsAwsjson11_deserializeDocumentImageTagAlreadyExistsException(v **types.Im for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -4529,7 +4539,7 @@ func awsAwsjson11_deserializeDocumentInvalidLayerException(v **types.InvalidLaye for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -4582,7 +4592,7 @@ func awsAwsjson11_deserializeDocumentInvalidLayerPartException(v **types.Invalid sv.LastValidByteReceived = ptr.Int64(i64) } - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -4649,7 +4659,7 @@ func awsAwsjson11_deserializeDocumentInvalidParameterException(v **types.Invalid for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -4689,7 +4699,7 @@ func awsAwsjson11_deserializeDocumentInvalidTagParameterException(v **types.Inva for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -4800,7 +4810,7 @@ func awsAwsjson11_deserializeDocumentLayerAlreadyExistsException(v **types.Layer for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -4966,7 +4976,7 @@ func awsAwsjson11_deserializeDocumentLayerPartTooSmallException(v **types.LayerP for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -5006,7 +5016,7 @@ func awsAwsjson11_deserializeDocumentLayersNotFoundException(v **types.LayersNot for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -5046,7 +5056,7 @@ func awsAwsjson11_deserializeDocumentLimitExceededException(v **types.LimitExcee for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -5209,7 +5219,7 @@ func awsAwsjson11_deserializeDocumentReferencedImagesNotFoundException(v **types for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -5496,7 +5506,7 @@ func awsAwsjson11_deserializeDocumentRegistryNotFoundException(v **types.Registr for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -5619,7 +5629,7 @@ func awsAwsjson11_deserializeDocumentRepositoryAlreadyExistsException(v **types. for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -5745,7 +5755,7 @@ func awsAwsjson11_deserializeDocumentRepositoryCatalogDataNotFoundException(v ** for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -5819,7 +5829,7 @@ func awsAwsjson11_deserializeDocumentRepositoryNotEmptyException(v **types.Repos for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -5859,7 +5869,7 @@ func awsAwsjson11_deserializeDocumentRepositoryNotFoundException(v **types.Repos for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -5899,7 +5909,7 @@ func awsAwsjson11_deserializeDocumentRepositoryPolicyNotFoundException(v **types for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -5939,7 +5949,7 @@ func awsAwsjson11_deserializeDocumentServerException(v **types.ServerException, for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -6062,7 +6072,7 @@ func awsAwsjson11_deserializeDocumentTooManyTagsException(v **types.TooManyTagsE for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -6102,7 +6112,7 @@ func awsAwsjson11_deserializeDocumentUnsupportedCommandException(v **types.Unsup for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -6142,7 +6152,7 @@ func awsAwsjson11_deserializeDocumentUploadNotFoundException(v **types.UploadNot for key, value := range shape { switch key { - case "message": + case "message", "Message": if value != nil { jtv, ok := value.(string) if !ok { @@ -7177,3 +7187,32 @@ func awsAwsjson11_deserializeOpDocumentUploadLayerPartOutput(v **UploadLayerPart *v = sv return nil } + +type protocolErrorInfo struct { + Type string `json:"__type"` + Message string + Code any // nonstandard for awsjson but some services do present the type here +} + +func getProtocolErrorInfo(decoder *json.Decoder) (protocolErrorInfo, error) { + var errInfo protocolErrorInfo + if err := decoder.Decode(&errInfo); err != nil { + if err == io.EOF { + return errInfo, nil + } + return errInfo, err + } + + return errInfo, nil +} + +func resolveProtocolErrorType(headerType string, bodyInfo protocolErrorInfo) (string, bool) { + if len(headerType) != 0 { + return headerType, true + } else if len(bodyInfo.Type) != 0 { + return bodyInfo.Type, true + } else if code, ok := bodyInfo.Code.(string); ok && len(code) != 0 { + return code, true + } + return "", false +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/doc.go index 8706038fd3..0b5c51054c 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/doc.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/doc.go @@ -3,13 +3,15 @@ // Package ecrpublic provides the API client, operations, and parameter types for // Amazon Elastic Container Registry Public. // -// Amazon Elastic Container Registry Public Amazon Elastic Container Registry -// Public (Amazon ECR Public) is a managed container image registry service. Amazon -// ECR provides both public and private registries to host your container images. -// You can use the Docker CLI or your preferred client to push, pull, and manage -// images. Amazon ECR provides a secure, scalable, and reliable registry for your -// Docker or Open Container Initiative (OCI) images. Amazon ECR supports public -// repositories with this API. For information about the Amazon ECR API for private -// repositories, see Amazon Elastic Container Registry API Reference (https://docs.aws.amazon.com/AmazonECR/latest/APIReference/Welcome.html) -// . +// # Amazon Elastic Container Registry Public +// +// Amazon Elastic Container Registry Public (Amazon ECR Public) is a managed +// container image registry service. Amazon ECR provides both public and private +// registries to host your container images. You can use the Docker CLI or your +// preferred client to push, pull, and manage images. Amazon ECR provides a secure, +// scalable, and reliable registry for your Docker or Open Container Initiative +// (OCI) images. Amazon ECR supports public repositories with this API. For +// information about the Amazon ECR API for private repositories, see [Amazon Elastic Container Registry API Reference]. +// +// [Amazon Elastic Container Registry API Reference]: https://docs.aws.amazon.com/AmazonECR/latest/APIReference/Welcome.html package ecrpublic diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/endpoints.go index b2ed730700..39d8005662 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/endpoints.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/endpoints.go @@ -8,14 +8,19 @@ import ( "fmt" "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + internalConfig "github.com/aws/aws-sdk-go-v2/internal/configsources" + "github.com/aws/aws-sdk-go-v2/internal/endpoints" "github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn" internalendpoints "github.com/aws/aws-sdk-go-v2/service/ecrpublic/internal/endpoints" + smithyauth "github.com/aws/smithy-go/auth" smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/aws/smithy-go/middleware" "github.com/aws/smithy-go/ptr" + "github.com/aws/smithy-go/tracing" smithyhttp "github.com/aws/smithy-go/transport/http" "net/http" "net/url" + "os" "strings" ) @@ -194,70 +199,29 @@ func resolveEndpointResolverV2(options *Options) { } } -// Utility function to aid with translating pseudo-regions to classical regions -// with the appropriate setting indicated by the pseudo-region -func mapPseudoRegion(pr string) (region string, fips aws.FIPSEndpointState) { - const fipsInfix = "-fips-" - const fipsPrefix = "fips-" - const fipsSuffix = "-fips" - - if strings.Contains(pr, fipsInfix) || - strings.Contains(pr, fipsPrefix) || - strings.Contains(pr, fipsSuffix) { - region = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll( - pr, fipsInfix, "-"), fipsPrefix, ""), fipsSuffix, "") - fips = aws.FIPSEndpointStateEnabled - } else { - region = pr +func resolveBaseEndpoint(cfg aws.Config, o *Options) { + if cfg.BaseEndpoint != nil { + o.BaseEndpoint = cfg.BaseEndpoint } - return region, fips -} - -// builtInParameterResolver is the interface responsible for resolving BuiltIn -// values during the sourcing of EndpointParameters -type builtInParameterResolver interface { - ResolveBuiltIns(*EndpointParameters) error -} - -// builtInResolver resolves modeled BuiltIn values using only the members defined -// below. -type builtInResolver struct { - // The AWS region used to dispatch the request. - Region string - - // Sourced BuiltIn value in a historical enabled or disabled state. - UseDualStack aws.DualStackEndpointState + _, g := os.LookupEnv("AWS_ENDPOINT_URL") + _, s := os.LookupEnv("AWS_ENDPOINT_URL_ECR_PUBLIC") - // Sourced BuiltIn value in a historical enabled or disabled state. - UseFIPS aws.FIPSEndpointState + if g && !s { + return + } - // Base endpoint that can potentially be modified during Endpoint resolution. - Endpoint *string + value, found, err := internalConfig.ResolveServiceBaseEndpoint(context.Background(), "ECR PUBLIC", cfg.ConfigSources) + if found && err == nil { + o.BaseEndpoint = &value + } } -// Invoked at runtime to resolve BuiltIn Values. Only resolution code specific to -// each BuiltIn value is generated. -func (b *builtInResolver) ResolveBuiltIns(params *EndpointParameters) error { - - region, _ := mapPseudoRegion(b.Region) - if len(region) == 0 { - return fmt.Errorf("Could not resolve AWS::Region") - } else { - params.Region = aws.String(region) - } - if b.UseDualStack == aws.DualStackEndpointStateEnabled { - params.UseDualStack = aws.Bool(true) - } else { - params.UseDualStack = aws.Bool(false) +func bindRegion(region string) *string { + if region == "" { + return nil } - if b.UseFIPS == aws.FIPSEndpointStateEnabled { - params.UseFIPS = aws.Bool(true) - } else { - params.UseFIPS = aws.Bool(false) - } - params.Endpoint = b.Endpoint - return nil + return aws.String(endpoints.MapFIPSRegion(region)) } // EndpointParameters provides the parameters that influence how endpoints are @@ -325,6 +289,17 @@ func (p EndpointParameters) WithDefaults() EndpointParameters { return p } +type stringSlice []string + +func (s stringSlice) Get(i int) *string { + if i < 0 || i >= len(s) { + return nil + } + + v := s[i] + return &v +} + // EndpointResolverV2 provides the interface for resolving service endpoints. type EndpointResolverV2 interface { // ResolveEndpoint attempts to resolve the endpoint with the provided options, @@ -410,7 +385,7 @@ func (r *resolver) ResolveEndpoint( } } if _UseFIPS == true { - if true == _PartitionResult.SupportsFIPS { + if _PartitionResult.SupportsFIPS == true { uriString := func() string { var out strings.Builder out.WriteString("https://api.ecr-public-fips.") @@ -478,3 +453,85 @@ func (r *resolver) ResolveEndpoint( } return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Missing Region") } + +type endpointParamsBinder interface { + bindEndpointParams(*EndpointParameters) +} + +func bindEndpointParams(ctx context.Context, input interface{}, options Options) *EndpointParameters { + params := &EndpointParameters{} + + params.Region = bindRegion(options.Region) + params.UseDualStack = aws.Bool(options.EndpointOptions.UseDualStackEndpoint == aws.DualStackEndpointStateEnabled) + params.UseFIPS = aws.Bool(options.EndpointOptions.UseFIPSEndpoint == aws.FIPSEndpointStateEnabled) + params.Endpoint = options.BaseEndpoint + + if b, ok := input.(endpointParamsBinder); ok { + b.bindEndpointParams(params) + } + + return params +} + +type resolveEndpointV2Middleware struct { + options Options +} + +func (*resolveEndpointV2Middleware) ID() string { + return "ResolveEndpointV2" +} + +func (m *resolveEndpointV2Middleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "ResolveEndpoint") + defer span.End() + + if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { + return next.HandleFinalize(ctx, in) + } + + req, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) + } + + if m.options.EndpointResolverV2 == nil { + return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") + } + + params := bindEndpointParams(ctx, getOperationInput(ctx), m.options) + endpt, err := timeOperationMetric(ctx, "client.call.resolve_endpoint_duration", + func() (smithyendpoints.Endpoint, error) { + return m.options.EndpointResolverV2.ResolveEndpoint(ctx, *params) + }) + if err != nil { + return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) + } + + span.SetProperty("client.call.resolved_endpoint", endpt.URI.String()) + + if endpt.URI.RawPath == "" && req.URL.RawPath != "" { + endpt.URI.RawPath = endpt.URI.Path + } + req.URL.Scheme = endpt.URI.Scheme + req.URL.Host = endpt.URI.Host + req.URL.Path = smithyhttp.JoinPath(endpt.URI.Path, req.URL.Path) + req.URL.RawPath = smithyhttp.JoinPath(endpt.URI.RawPath, req.URL.RawPath) + for k := range endpt.Headers { + req.Header.Set(k, endpt.Headers.Get(k)) + } + + rscheme := getResolvedAuthScheme(ctx) + if rscheme == nil { + return out, metadata, fmt.Errorf("no resolved auth scheme") + } + + opts, _ := smithyauth.GetAuthOptions(&endpt.Properties) + for _, o := range opts { + rscheme.SignerProperties.SetAll(&o.SignerProperties) + } + + span.End() + return next.HandleFinalize(ctx, in) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/generated.json b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/generated.json index 067ae4319e..f11524a5fe 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/generated.json +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/generated.json @@ -3,8 +3,7 @@ "github.com/aws/aws-sdk-go-v2": "v1.4.0", "github.com/aws/aws-sdk-go-v2/internal/configsources": "v0.0.0-00010101000000-000000000000", "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2": "v2.0.0-00010101000000-000000000000", - "github.com/aws/smithy-go": "v1.4.0", - "github.com/google/go-cmp": "v0.5.4" + "github.com/aws/smithy-go": "v1.4.0" }, "files": [ "api_client.go", @@ -32,15 +31,19 @@ "api_op_TagResource.go", "api_op_UntagResource.go", "api_op_UploadLayerPart.go", + "auth.go", "deserializers.go", "doc.go", "endpoints.go", + "endpoints_config_test.go", "endpoints_test.go", "generated.json", "internal/endpoints/endpoints.go", "internal/endpoints/endpoints_test.go", + "options.go", "protocol_test.go", "serializers.go", + "snapshot_test.go", "types/enums.go", "types/errors.go", "types/types.go", diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/go_module_metadata.go index 10b100d2f1..8fd54c55f3 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/go_module_metadata.go @@ -3,4 +3,4 @@ package ecrpublic // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.18.2" +const goModuleVersion = "1.31.2" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/internal/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/internal/endpoints/endpoints.go index 7f12229598..9a16fe412b 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/internal/endpoints/endpoints.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/internal/endpoints/endpoints.go @@ -94,7 +94,7 @@ var partitionRegexp = struct { AwsUsGov *regexp.Regexp }{ - Aws: regexp.MustCompile("^(us|eu|ap|sa|ca|me|af|il)\\-\\w+\\-\\d+$"), + Aws: regexp.MustCompile("^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$"), AwsCn: regexp.MustCompile("^cn\\-\\w+\\-\\d+$"), AwsIso: regexp.MustCompile("^us\\-iso\\-\\w+\\-\\d+$"), AwsIsoB: regexp.MustCompile("^us\\-isob\\-\\w+\\-\\d+$"), @@ -147,6 +147,15 @@ var defaultPartitions = endpoints.Partitions{ Region: "us-east-1", }, }, + endpoints.EndpointKey{ + Region: "us-east-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "ecr-public.us-east-1.api.aws", + CredentialScope: endpoints.CredentialScope{ + Region: "us-east-1", + }, + }, endpoints.EndpointKey{ Region: "us-west-2", }: endpoints.Endpoint{ diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/options.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/options.go new file mode 100644 index 0000000000..c10ee3d0cf --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/options.go @@ -0,0 +1,232 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package ecrpublic + +import ( + "context" + "github.com/aws/aws-sdk-go-v2/aws" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + internalauthsmithy "github.com/aws/aws-sdk-go-v2/internal/auth/smithy" + smithyauth "github.com/aws/smithy-go/auth" + "github.com/aws/smithy-go/logging" + "github.com/aws/smithy-go/metrics" + "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" + "net/http" +) + +type HTTPClient interface { + Do(*http.Request) (*http.Response, error) +} + +type Options struct { + // Set of options to modify how an operation is invoked. These apply to all + // operations invoked for this client. Use functional options on operation call to + // modify this list for per operation behavior. + APIOptions []func(*middleware.Stack) error + + // The optional application specific identifier appended to the User-Agent header. + AppID string + + // This endpoint will be given as input to an EndpointResolverV2. It is used for + // providing a custom base endpoint that is subject to modifications by the + // processing EndpointResolverV2. + BaseEndpoint *string + + // Configures the events that will be sent to the configured logger. + ClientLogMode aws.ClientLogMode + + // The credentials object to use when signing requests. + Credentials aws.CredentialsProvider + + // The configuration DefaultsMode that the SDK should use when constructing the + // clients initial default settings. + DefaultsMode aws.DefaultsMode + + // The endpoint options to be used when attempting to resolve an endpoint. + EndpointOptions EndpointResolverOptions + + // The service endpoint resolver. + // + // Deprecated: Deprecated: EndpointResolver and WithEndpointResolver. Providing a + // value for this field will likely prevent you from using any endpoint-related + // service features released after the introduction of EndpointResolverV2 and + // BaseEndpoint. + // + // To migrate an EndpointResolver implementation that uses a custom endpoint, set + // the client option BaseEndpoint instead. + EndpointResolver EndpointResolver + + // Resolves the endpoint used for a particular service operation. This should be + // used over the deprecated EndpointResolver. + EndpointResolverV2 EndpointResolverV2 + + // Signature Version 4 (SigV4) Signer + HTTPSignerV4 HTTPSignerV4 + + // The logger writer interface to write logging messages to. + Logger logging.Logger + + // The client meter provider. + MeterProvider metrics.MeterProvider + + // The region to send requests to. (Required) + Region string + + // RetryMaxAttempts specifies the maximum number attempts an API client will call + // an operation that fails with a retryable error. A value of 0 is ignored, and + // will not be used to configure the API client created default retryer, or modify + // per operation call's retry max attempts. + // + // If specified in an operation call's functional options with a value that is + // different than the constructed client's Options, the Client's Retryer will be + // wrapped to use the operation's specific RetryMaxAttempts value. + RetryMaxAttempts int + + // RetryMode specifies the retry mode the API client will be created with, if + // Retryer option is not also specified. + // + // When creating a new API Clients this member will only be used if the Retryer + // Options member is nil. This value will be ignored if Retryer is not nil. + // + // Currently does not support per operation call overrides, may in the future. + RetryMode aws.RetryMode + + // Retryer guides how HTTP requests should be retried in case of recoverable + // failures. When nil the API client will use a default retryer. The kind of + // default retry created by the API client can be changed with the RetryMode + // option. + Retryer aws.Retryer + + // The RuntimeEnvironment configuration, only populated if the DefaultsMode is set + // to DefaultsModeAuto and is initialized using config.LoadDefaultConfig . You + // should not populate this structure programmatically, or rely on the values here + // within your applications. + RuntimeEnvironment aws.RuntimeEnvironment + + // The client tracer provider. + TracerProvider tracing.TracerProvider + + // The initial DefaultsMode used when the client options were constructed. If the + // DefaultsMode was set to aws.DefaultsModeAuto this will store what the resolved + // value was at that point in time. + // + // Currently does not support per operation call overrides, may in the future. + resolvedDefaultsMode aws.DefaultsMode + + // The HTTP client to invoke API calls with. Defaults to client's default HTTP + // implementation if nil. + HTTPClient HTTPClient + + // The auth scheme resolver which determines how to authenticate for each + // operation. + AuthSchemeResolver AuthSchemeResolver + + // The list of auth schemes supported by the client. + AuthSchemes []smithyhttp.AuthScheme +} + +// Copy creates a clone where the APIOptions list is deep copied. +func (o Options) Copy() Options { + to := o + to.APIOptions = make([]func(*middleware.Stack) error, len(o.APIOptions)) + copy(to.APIOptions, o.APIOptions) + + return to +} + +func (o Options) GetIdentityResolver(schemeID string) smithyauth.IdentityResolver { + if schemeID == "aws.auth#sigv4" { + return getSigV4IdentityResolver(o) + } + if schemeID == "smithy.api#noAuth" { + return &smithyauth.AnonymousIdentityResolver{} + } + return nil +} + +// WithAPIOptions returns a functional option for setting the Client's APIOptions +// option. +func WithAPIOptions(optFns ...func(*middleware.Stack) error) func(*Options) { + return func(o *Options) { + o.APIOptions = append(o.APIOptions, optFns...) + } +} + +// Deprecated: EndpointResolver and WithEndpointResolver. Providing a value for +// this field will likely prevent you from using any endpoint-related service +// features released after the introduction of EndpointResolverV2 and BaseEndpoint. +// +// To migrate an EndpointResolver implementation that uses a custom endpoint, set +// the client option BaseEndpoint instead. +func WithEndpointResolver(v EndpointResolver) func(*Options) { + return func(o *Options) { + o.EndpointResolver = v + } +} + +// WithEndpointResolverV2 returns a functional option for setting the Client's +// EndpointResolverV2 option. +func WithEndpointResolverV2(v EndpointResolverV2) func(*Options) { + return func(o *Options) { + o.EndpointResolverV2 = v + } +} + +func getSigV4IdentityResolver(o Options) smithyauth.IdentityResolver { + if o.Credentials != nil { + return &internalauthsmithy.CredentialsProviderAdapter{Provider: o.Credentials} + } + return nil +} + +// WithSigV4SigningName applies an override to the authentication workflow to +// use the given signing name for SigV4-authenticated operations. +// +// This is an advanced setting. The value here is FINAL, taking precedence over +// the resolved signing name from both auth scheme resolution and endpoint +// resolution. +func WithSigV4SigningName(name string) func(*Options) { + fn := func(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, + ) { + return next.HandleInitialize(awsmiddleware.SetSigningName(ctx, name), in) + } + return func(o *Options) { + o.APIOptions = append(o.APIOptions, func(s *middleware.Stack) error { + return s.Initialize.Add( + middleware.InitializeMiddlewareFunc("withSigV4SigningName", fn), + middleware.Before, + ) + }) + } +} + +// WithSigV4SigningRegion applies an override to the authentication workflow to +// use the given signing region for SigV4-authenticated operations. +// +// This is an advanced setting. The value here is FINAL, taking precedence over +// the resolved signing region from both auth scheme resolution and endpoint +// resolution. +func WithSigV4SigningRegion(region string) func(*Options) { + fn := func(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, + ) { + return next.HandleInitialize(awsmiddleware.SetSigningRegion(ctx, region), in) + } + return func(o *Options) { + o.APIOptions = append(o.APIOptions, func(s *middleware.Stack) error { + return s.Initialize.Add( + middleware.InitializeMiddlewareFunc("withSigV4SigningRegion", fn), + middleware.Before, + ) + }) + } +} + +func ignoreAnonymousAuth(options *Options) { + if aws.IsCredentialsProvider(options.Credentials, (*aws.AnonymousCredentials)(nil)) { + options.Credentials = nil + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/serializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/serializers.go index 4fd9a7dc31..51bdd17e57 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/serializers.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/serializers.go @@ -11,6 +11,7 @@ import ( "github.com/aws/smithy-go/encoding/httpbinding" smithyjson "github.com/aws/smithy-go/encoding/json" "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/tracing" smithyhttp "github.com/aws/smithy-go/transport/http" "path" ) @@ -25,6 +26,10 @@ func (*awsAwsjson11_serializeOpBatchCheckLayerAvailability) ID() string { func (m *awsAwsjson11_serializeOpBatchCheckLayerAvailability) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -67,6 +72,8 @@ func (m *awsAwsjson11_serializeOpBatchCheckLayerAvailability) HandleSerialize(ct } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -80,6 +87,10 @@ func (*awsAwsjson11_serializeOpBatchDeleteImage) ID() string { func (m *awsAwsjson11_serializeOpBatchDeleteImage) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -122,6 +133,8 @@ func (m *awsAwsjson11_serializeOpBatchDeleteImage) HandleSerialize(ctx context.C } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -135,6 +148,10 @@ func (*awsAwsjson11_serializeOpCompleteLayerUpload) ID() string { func (m *awsAwsjson11_serializeOpCompleteLayerUpload) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -177,6 +194,8 @@ func (m *awsAwsjson11_serializeOpCompleteLayerUpload) HandleSerialize(ctx contex } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -190,6 +209,10 @@ func (*awsAwsjson11_serializeOpCreateRepository) ID() string { func (m *awsAwsjson11_serializeOpCreateRepository) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -232,6 +255,8 @@ func (m *awsAwsjson11_serializeOpCreateRepository) HandleSerialize(ctx context.C } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -245,6 +270,10 @@ func (*awsAwsjson11_serializeOpDeleteRepository) ID() string { func (m *awsAwsjson11_serializeOpDeleteRepository) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -287,6 +316,8 @@ func (m *awsAwsjson11_serializeOpDeleteRepository) HandleSerialize(ctx context.C } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -300,6 +331,10 @@ func (*awsAwsjson11_serializeOpDeleteRepositoryPolicy) ID() string { func (m *awsAwsjson11_serializeOpDeleteRepositoryPolicy) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -342,6 +377,8 @@ func (m *awsAwsjson11_serializeOpDeleteRepositoryPolicy) HandleSerialize(ctx con } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -355,6 +392,10 @@ func (*awsAwsjson11_serializeOpDescribeImages) ID() string { func (m *awsAwsjson11_serializeOpDescribeImages) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -397,6 +438,8 @@ func (m *awsAwsjson11_serializeOpDescribeImages) HandleSerialize(ctx context.Con } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -410,6 +453,10 @@ func (*awsAwsjson11_serializeOpDescribeImageTags) ID() string { func (m *awsAwsjson11_serializeOpDescribeImageTags) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -452,6 +499,8 @@ func (m *awsAwsjson11_serializeOpDescribeImageTags) HandleSerialize(ctx context. } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -465,6 +514,10 @@ func (*awsAwsjson11_serializeOpDescribeRegistries) ID() string { func (m *awsAwsjson11_serializeOpDescribeRegistries) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -507,6 +560,8 @@ func (m *awsAwsjson11_serializeOpDescribeRegistries) HandleSerialize(ctx context } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -520,6 +575,10 @@ func (*awsAwsjson11_serializeOpDescribeRepositories) ID() string { func (m *awsAwsjson11_serializeOpDescribeRepositories) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -562,6 +621,8 @@ func (m *awsAwsjson11_serializeOpDescribeRepositories) HandleSerialize(ctx conte } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -575,6 +636,10 @@ func (*awsAwsjson11_serializeOpGetAuthorizationToken) ID() string { func (m *awsAwsjson11_serializeOpGetAuthorizationToken) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -617,6 +682,8 @@ func (m *awsAwsjson11_serializeOpGetAuthorizationToken) HandleSerialize(ctx cont } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -630,6 +697,10 @@ func (*awsAwsjson11_serializeOpGetRegistryCatalogData) ID() string { func (m *awsAwsjson11_serializeOpGetRegistryCatalogData) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -672,6 +743,8 @@ func (m *awsAwsjson11_serializeOpGetRegistryCatalogData) HandleSerialize(ctx con } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -685,6 +758,10 @@ func (*awsAwsjson11_serializeOpGetRepositoryCatalogData) ID() string { func (m *awsAwsjson11_serializeOpGetRepositoryCatalogData) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -727,6 +804,8 @@ func (m *awsAwsjson11_serializeOpGetRepositoryCatalogData) HandleSerialize(ctx c } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -740,6 +819,10 @@ func (*awsAwsjson11_serializeOpGetRepositoryPolicy) ID() string { func (m *awsAwsjson11_serializeOpGetRepositoryPolicy) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -782,6 +865,8 @@ func (m *awsAwsjson11_serializeOpGetRepositoryPolicy) HandleSerialize(ctx contex } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -795,6 +880,10 @@ func (*awsAwsjson11_serializeOpInitiateLayerUpload) ID() string { func (m *awsAwsjson11_serializeOpInitiateLayerUpload) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -837,6 +926,8 @@ func (m *awsAwsjson11_serializeOpInitiateLayerUpload) HandleSerialize(ctx contex } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -850,6 +941,10 @@ func (*awsAwsjson11_serializeOpListTagsForResource) ID() string { func (m *awsAwsjson11_serializeOpListTagsForResource) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -892,6 +987,8 @@ func (m *awsAwsjson11_serializeOpListTagsForResource) HandleSerialize(ctx contex } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -905,6 +1002,10 @@ func (*awsAwsjson11_serializeOpPutImage) ID() string { func (m *awsAwsjson11_serializeOpPutImage) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -947,6 +1048,8 @@ func (m *awsAwsjson11_serializeOpPutImage) HandleSerialize(ctx context.Context, } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -960,6 +1063,10 @@ func (*awsAwsjson11_serializeOpPutRegistryCatalogData) ID() string { func (m *awsAwsjson11_serializeOpPutRegistryCatalogData) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1002,6 +1109,8 @@ func (m *awsAwsjson11_serializeOpPutRegistryCatalogData) HandleSerialize(ctx con } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1015,6 +1124,10 @@ func (*awsAwsjson11_serializeOpPutRepositoryCatalogData) ID() string { func (m *awsAwsjson11_serializeOpPutRepositoryCatalogData) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1057,6 +1170,8 @@ func (m *awsAwsjson11_serializeOpPutRepositoryCatalogData) HandleSerialize(ctx c } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1070,6 +1185,10 @@ func (*awsAwsjson11_serializeOpSetRepositoryPolicy) ID() string { func (m *awsAwsjson11_serializeOpSetRepositoryPolicy) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1112,6 +1231,8 @@ func (m *awsAwsjson11_serializeOpSetRepositoryPolicy) HandleSerialize(ctx contex } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1125,6 +1246,10 @@ func (*awsAwsjson11_serializeOpTagResource) ID() string { func (m *awsAwsjson11_serializeOpTagResource) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1167,6 +1292,8 @@ func (m *awsAwsjson11_serializeOpTagResource) HandleSerialize(ctx context.Contex } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1180,6 +1307,10 @@ func (*awsAwsjson11_serializeOpUntagResource) ID() string { func (m *awsAwsjson11_serializeOpUntagResource) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1222,6 +1353,8 @@ func (m *awsAwsjson11_serializeOpUntagResource) HandleSerialize(ctx context.Cont } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } @@ -1235,6 +1368,10 @@ func (*awsAwsjson11_serializeOpUploadLayerPart) ID() string { func (m *awsAwsjson11_serializeOpUploadLayerPart) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() request, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} @@ -1277,6 +1414,8 @@ func (m *awsAwsjson11_serializeOpUploadLayerPart) HandleSerialize(ctx context.Co } in.Request = request + endTimer() + span.End() return next.HandleSerialize(ctx, in) } func awsAwsjson11_serializeDocumentArchitectureList(v []string, value smithyjson.Value) error { diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/types/enums.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/types/enums.go index d80a052447..bc9ab658cc 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/types/enums.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/types/enums.go @@ -16,8 +16,9 @@ const ( ) // Values returns all known values for ImageFailureCode. Note that this can be -// expanded in the future, and so it is only as up to date as the client. The -// ordering of this slice is not guaranteed to be stable across updates. +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. func (ImageFailureCode) Values() []ImageFailureCode { return []ImageFailureCode{ "InvalidImageDigest", @@ -39,8 +40,9 @@ const ( ) // Values returns all known values for LayerAvailability. Note that this can be -// expanded in the future, and so it is only as up to date as the client. The -// ordering of this slice is not guaranteed to be stable across updates. +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. func (LayerAvailability) Values() []LayerAvailability { return []LayerAvailability{ "AVAILABLE", @@ -57,8 +59,9 @@ const ( ) // Values returns all known values for LayerFailureCode. Note that this can be -// expanded in the future, and so it is only as up to date as the client. The -// ordering of this slice is not guaranteed to be stable across updates. +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. func (LayerFailureCode) Values() []LayerFailureCode { return []LayerFailureCode{ "InvalidLayerDigest", @@ -76,8 +79,9 @@ const ( ) // Values returns all known values for RegistryAliasStatus. Note that this can be -// expanded in the future, and so it is only as up to date as the client. The -// ordering of this slice is not guaranteed to be stable across updates. +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. func (RegistryAliasStatus) Values() []RegistryAliasStatus { return []RegistryAliasStatus{ "ACTIVE", diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/types/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/types/errors.go index 24f4d43c76..349db08f23 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/types/errors.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/types/errors.go @@ -334,8 +334,10 @@ func (e *LayersNotFoundException) ErrorCode() string { func (e *LayersNotFoundException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } // The operation didn't succeed because it would have exceeded a service limit for -// your account. For more information, see Amazon ECR Service Quotas (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service-quotas.html) -// in the Amazon Elastic Container Registry User Guide. +// your account. For more information, see [Amazon ECR Service Quotas]in the Amazon Elastic Container +// Registry User Guide. +// +// [Amazon ECR Service Quotas]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/service-quotas.html type LimitExceededException struct { Message *string diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/types/types.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/types/types.go index b24a2f4e4b..50f55e9fd0 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/types/types.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ecrpublic/types/types.go @@ -60,12 +60,15 @@ type ImageDetail struct { // current image was pushed to the repository at. ImagePushedAt *time.Time - // The size, in bytes, of the image in the repository. If the image is a manifest - // list, this is the max size of all manifests in the list. Beginning with Docker - // version 1.9, the Docker client compresses image layers before pushing them to a - // V2 Docker registry. The output of the docker images command shows the - // uncompressed image size, so it might return a larger image size than the image - // sizes that are returned by DescribeImages . + // The size, in bytes, of the image in the repository. + // + // If the image is a manifest list, this is the max size of all manifests in the + // list. + // + // Beginning with Docker version 1.9, the Docker client compresses image layers + // before pushing them to a V2 Docker registry. The output of the docker images + // command shows the uncompressed image size, so it might return a larger image + // size than the image sizes that are returned by DescribeImages. ImageSizeInBytes *int64 // The list of tags that's associated with this image. @@ -158,8 +161,7 @@ type LayerFailure struct { noSmithyDocumentSerde } -// An object that describes the image tag details that are returned by a -// DescribeImageTags action. +// An object that describes the image tag details that are returned by a DescribeImageTags action. type ReferencedImageDetail struct { // The artifact media type of the image. @@ -175,12 +177,15 @@ type ReferencedImageDetail struct { // current image tag was pushed to the repository at. ImagePushedAt *time.Time - // The size, in bytes, of the image in the repository. If the image is a manifest - // list, this is the max size of all manifests in the list. Beginning with Docker - // version 1.9, the Docker client compresses image layers before pushing them to a - // V2 Docker registry. The output of the docker images command shows the - // uncompressed image size, so it might return a larger image size than the image - // sizes that are returned by DescribeImages . + // The size, in bytes, of the image in the repository. + // + // If the image is a manifest list, this is the max size of all manifests in the + // list. + // + // Beginning with Docker version 1.9, the Docker client compresses image layers + // before pushing them to a V2 Docker registry. The output of the docker images + // command shows the uncompressed image size, so it might return a larger image + // size than the image sizes that are returned by DescribeImages. ImageSizeInBytes *int64 noSmithyDocumentSerde @@ -223,8 +228,10 @@ type Registry struct { // An object representing the aliases for a public registry. A public registry is // given an alias when it's created. However, a custom alias can be set using the -// Amazon ECR console. For more information, see Registries (https://docs.aws.amazon.com/AmazonECR/latest/userguide/Registries.html) -// in the Amazon Elastic Container Registry User Guide. +// Amazon ECR console. For more information, see [Registries]in the Amazon Elastic Container +// Registry User Guide. +// +// [Registries]: https://docs.aws.amazon.com/AmazonECR/latest/userguide/Registries.html type RegistryAlias struct { // Indicates whether the registry alias is the default alias for the registry. @@ -242,8 +249,10 @@ type RegistryAlias struct { // Indicates whether the registry alias is the primary alias for the registry. If // true, the alias is the primary registry alias and is displayed in both the // repository URL and the image URI used in the docker pull commands on the Amazon - // ECR Public Gallery. A registry alias that isn't the primary registry alias can - // be used in the repository URI in a docker pull command. + // ECR Public Gallery. + // + // A registry alias that isn't the primary registry alias can be used in the + // repository URI in a docker pull command. // // This member is required. PrimaryRegistryAlias bool @@ -260,8 +269,10 @@ type RegistryAlias struct { type RegistryCatalogData struct { // The display name for a public registry. This appears on the Amazon ECR Public - // Gallery. Only accounts that have the verified account badge can have a registry - // display name. + // Gallery. + // + // Only accounts that have the verified account badge can have a registry display + // name. DisplayName *string noSmithyDocumentSerde @@ -301,9 +312,10 @@ type RepositoryCatalogData struct { // in the repository details on the Amazon ECR Public Gallery. AboutText *string - // The architecture tags that are associated with the repository. Only supported - // operating system tags appear publicly in the Amazon ECR Public Gallery. For more - // information, see RepositoryCatalogDataInput . + // The architecture tags that are associated with the repository. + // + // Only supported operating system tags appear publicly in the Amazon ECR Public + // Gallery. For more information, see RepositoryCatalogDataInput. Architectures []string // The short description of the repository. @@ -316,9 +328,10 @@ type RepositoryCatalogData struct { // Marketplace. MarketplaceCertified *bool - // The operating system tags that are associated with the repository. Only - // supported operating system tags appear publicly in the Amazon ECR Public - // Gallery. For more information, see RepositoryCatalogDataInput . + // The operating system tags that are associated with the repository. + // + // Only supported operating system tags appear publicly in the Amazon ECR Public + // Gallery. For more information, see RepositoryCatalogDataInput. OperatingSystems []string // The longform usage details of the contents of the repository. The usage text @@ -338,13 +351,18 @@ type RepositoryCatalogDataInput struct { // The system architecture that the images in the repository are compatible with. // On the Amazon ECR Public Gallery, the following supported architectures appear - // as badges on the repository and are used as search filters. If an unsupported - // tag is added to your repository catalog data, it's associated with the - // repository and can be retrieved using the API but isn't discoverable in the - // Amazon ECR Public Gallery. + // as badges on the repository and are used as search filters. + // + // If an unsupported tag is added to your repository catalog data, it's associated + // with the repository and can be retrieved using the API but isn't discoverable in + // the Amazon ECR Public Gallery. + // // - ARM + // // - ARM 64 + // // - x86 + // // - x86-64 Architectures []string @@ -353,17 +371,22 @@ type RepositoryCatalogDataInput struct { // ECR Public Gallery. Description *string - // The base64-encoded repository logo payload. The repository logo is only - // publicly visible in the Amazon ECR Public Gallery for verified accounts. + // The base64-encoded repository logo payload. + // + // The repository logo is only publicly visible in the Amazon ECR Public Gallery + // for verified accounts. LogoImageBlob []byte // The operating systems that the images in the repository are compatible with. On // the Amazon ECR Public Gallery, the following supported operating systems appear - // as badges on the repository and are used as search filters. If an unsupported - // tag is added to your repository catalog data, it's associated with the - // repository and can be retrieved using the API but isn't discoverable in the - // Amazon ECR Public Gallery. + // as badges on the repository and are used as search filters. + // + // If an unsupported tag is added to your repository catalog data, it's associated + // with the repository and can be retrieved using the API but isn't discoverable in + // the Amazon ECR Public Gallery. + // // - Linux + // // - Windows OperatingSystems []string diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/CHANGELOG.md index 8ab28d3a98..ef78753a92 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/CHANGELOG.md @@ -1,3 +1,7 @@ +# v1.12.2 (2025-01-24) + +* **Dependency Update**: Upgrade to smithy-go v1.22.2. + # v1.12.1 (2024-11-18) * **Dependency Update**: Update to smithy-go v1.22.1. diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/go_module_metadata.go index 1514acbe34..cbf79b401d 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/go_module_metadata.go @@ -3,4 +3,4 @@ package acceptencoding // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.12.1" +const goModuleVersion = "1.12.2" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/CHANGELOG.md index 962ab791f4..3d98e3c1d9 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/CHANGELOG.md @@ -1,3 +1,28 @@ +# v1.12.13 (2025-02-05) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.12.12 (2025-01-31) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.12.11 (2025-01-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.12.10 (2025-01-24) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.22.2. + +# v1.12.9 (2025-01-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.12.8 (2025-01-09) + +* **Dependency Update**: Updated to the latest SDK module versions + # v1.12.7 (2024-12-19) * **Dependency Update**: Updated to the latest SDK module versions diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/go_module_metadata.go index 4c54f6428c..99ccc6c3b6 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/go_module_metadata.go @@ -3,4 +3,4 @@ package presignedurl // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.12.7" +const goModuleVersion = "1.12.13" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/CHANGELOG.md index 95b2d47ab5..ea71c3b03b 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/CHANGELOG.md @@ -1,3 +1,32 @@ +# v1.24.15 (2025-02-05) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.24.14 (2025-01-31) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.24.13 (2025-01-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.24.12 (2025-01-24) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.22.2. + +# v1.24.11 (2025-01-17) + +* **Bug Fix**: Fix bug where credentials weren't refreshed during retry loop. + +# v1.24.10 (2025-01-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.24.9 (2025-01-09) + +* **Dependency Update**: Updated to the latest SDK module versions + # v1.24.8 (2024-12-19) * **Dependency Update**: Updated to the latest SDK module versions diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_client.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_client.go index 644ee1e058..0b244f142c 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_client.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_client.go @@ -684,7 +684,7 @@ func addRetry(stack *middleware.Stack, o Options) error { m.LogAttempts = o.ClientLogMode.IsRetries() m.OperationMeter = o.MeterProvider.Meter("github.com/aws/aws-sdk-go-v2/service/sso") }) - if err := stack.Finalize.Insert(attempt, "Signing", middleware.Before); err != nil { + if err := stack.Finalize.Insert(attempt, "ResolveAuthScheme", middleware.Before); err != nil { return err } if err := stack.Finalize.Insert(&retry.MetricsHeader{}, attempt.ID(), middleware.After); err != nil { diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/go_module_metadata.go index 46dacd1e8f..697a8a84a7 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/go_module_metadata.go @@ -3,4 +3,4 @@ package sso // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.24.8" +const goModuleVersion = "1.24.15" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/CHANGELOG.md index 8fbaed84d7..cd1774eb3e 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/CHANGELOG.md @@ -1,3 +1,33 @@ +# v1.28.14 (2025-02-05) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.28.13 (2025-01-31) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.28.12 (2025-01-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.28.11 (2025-01-24) + +* **Documentation**: Fixed typos in the descriptions. +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.22.2. + +# v1.28.10 (2025-01-17) + +* **Bug Fix**: Fix bug where credentials weren't refreshed during retry loop. + +# v1.28.9 (2025-01-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.28.8 (2025-01-09) + +* **Dependency Update**: Updated to the latest SDK module versions + # v1.28.7 (2024-12-19) * **Dependency Update**: Updated to the latest SDK module versions diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_client.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_client.go index 0b05bf6c73..9b7f4acc84 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_client.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_client.go @@ -684,7 +684,7 @@ func addRetry(stack *middleware.Stack, o Options) error { m.LogAttempts = o.ClientLogMode.IsRetries() m.OperationMeter = o.MeterProvider.Meter("github.com/aws/aws-sdk-go-v2/service/ssooidc") }) - if err := stack.Finalize.Insert(attempt, "Signing", middleware.Before); err != nil { + if err := stack.Finalize.Insert(attempt, "ResolveAuthScheme", middleware.Before); err != nil { return err } if err := stack.Finalize.Insert(&retry.MetricsHeader{}, attempt.ID(), middleware.After); err != nil { diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_CreateToken.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_CreateToken.go index 5fb8d2ab94..2ab3524479 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_CreateToken.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_CreateToken.go @@ -12,7 +12,7 @@ import ( // Creates and returns access and refresh tokens for clients that are // authenticated using client secrets. The access token can be used to fetch -// short-term credentials for the assigned AWS accounts or to access application +// short-lived credentials for the assigned AWS accounts or to access application // APIs using bearer authentication. func (c *Client) CreateToken(ctx context.Context, params *CreateTokenInput, optFns ...func(*Options)) (*CreateTokenOutput, error) { if params == nil { @@ -43,22 +43,21 @@ type CreateTokenInput struct { // This member is required. ClientSecret *string - // Supports the following OAuth grant types: Device Code and Refresh Token. - // Specify either of the following values, depending on the grant type that you - // want: + // Supports the following OAuth grant types: Authorization Code, Device Code, and + // Refresh Token. Specify one of the following values, depending on the grant type + // that you want: + // + // * Authorization Code - authorization_code // // * Device Code - urn:ietf:params:oauth:grant-type:device_code // // * Refresh Token - refresh_token // - // For information about how to obtain the device code, see the StartDeviceAuthorization topic. - // // This member is required. GrantType *string // Used only when calling this API for the Authorization Code grant type. The - // short-term code is used to identify this authorization request. This grant type - // is currently unsupported for the CreateTokenAPI. + // short-lived code is used to identify this authorization request. Code *string // Used only when calling this API for the Authorization Code grant type. This @@ -66,9 +65,9 @@ type CreateTokenInput struct { // challenge value the client passed at authorization time. CodeVerifier *string - // Used only when calling this API for the Device Code grant type. This short-term - // code is used to identify this authorization request. This comes from the result - // of the StartDeviceAuthorizationAPI. + // Used only when calling this API for the Device Code grant type. This + // short-lived code is used to identify this authorization request. This comes from + // the result of the StartDeviceAuthorizationAPI. DeviceCode *string // Used only when calling this API for the Authorization Code grant type. This @@ -77,7 +76,7 @@ type CreateTokenInput struct { RedirectUri *string // Used only when calling this API for the Refresh Token grant type. This token is - // used to refresh short-term tokens, such as the access token, that might expire. + // used to refresh short-lived tokens, such as the access token, that might expire. // // For more information about the features and limitations of the current IAM // Identity Center OIDC implementation, see Considerations for Using this Guide in diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_CreateTokenWithIAM.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_CreateTokenWithIAM.go index 8abd43690d..e5253ce884 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_CreateTokenWithIAM.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_CreateTokenWithIAM.go @@ -12,7 +12,7 @@ import ( // Creates and returns access and refresh tokens for clients and applications that // are authenticated using IAM entities. The access token can be used to fetch -// short-term credentials for the assigned Amazon Web Services accounts or to +// short-lived credentials for the assigned Amazon Web Services accounts or to // access application APIs using bearer authentication. func (c *Client) CreateTokenWithIAM(ctx context.Context, params *CreateTokenWithIAMInput, optFns ...func(*Options)) (*CreateTokenWithIAMOutput, error) { if params == nil { @@ -59,7 +59,7 @@ type CreateTokenWithIAMInput struct { Assertion *string // Used only when calling this API for the Authorization Code grant type. This - // short-term code is used to identify this authorization request. The code is + // short-lived code is used to identify this authorization request. The code is // obtained through a redirect from IAM Identity Center to a redirect URI persisted // in the Authorization Code GrantOptions for the application. Code *string @@ -75,7 +75,7 @@ type CreateTokenWithIAMInput struct { RedirectUri *string // Used only when calling this API for the Refresh Token grant type. This token is - // used to refresh short-term tokens, such as the access token, that might expire. + // used to refresh short-lived tokens, such as the access token, that might expire. // // For more information about the features and limitations of the current IAM // Identity Center OIDC implementation, see Considerations for Using this Guide in diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_RegisterClient.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_RegisterClient.go index 03a3594be0..2022270db2 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_RegisterClient.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_RegisterClient.go @@ -10,9 +10,9 @@ import ( smithyhttp "github.com/aws/smithy-go/transport/http" ) -// Registers a client with IAM Identity Center. This allows clients to initiate -// device authorization. The output should be persisted for reuse through many -// authentication requests. +// Registers a public client with IAM Identity Center. This allows clients to +// perform authorization using the authorization code grant with Proof Key for Code +// Exchange (PKCE) or the device code grant. func (c *Client) RegisterClient(ctx context.Context, params *RegisterClientInput, optFns ...func(*Options)) (*RegisterClientOutput, error) { if params == nil { params = &RegisterClientInput{} @@ -48,7 +48,15 @@ type RegisterClientInput struct { EntitledApplicationArn *string // The list of OAuth 2.0 grant types that are defined by the client. This list is - // used to restrict the token granting flows available to the client. + // used to restrict the token granting flows available to the client. Supports the + // following OAuth 2.0 grant types: Authorization Code, Device Code, and Refresh + // Token. + // + // * Authorization Code - authorization_code + // + // * Device Code - urn:ietf:params:oauth:grant-type:device_code + // + // * Refresh Token - refresh_token GrantTypes []string // The IAM Identity Center Issuer URL associated with an instance of IAM Identity diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/doc.go index 1d258e5677..f3510b18c5 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/doc.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/doc.go @@ -8,9 +8,12 @@ // Center. The service also enables the client to fetch the user’s access token // upon successful authentication and authorization with IAM Identity Center. // -// IAM Identity Center uses the sso and identitystore API namespaces. +// # API namespaces // -// # Considerations for Using This Guide +// IAM Identity Center uses the sso and identitystore API namespaces. IAM Identity +// Center OpenID Connect uses the sso-oidc namespace. +// +// # Considerations for using this guide // // Before you begin using this guide, we recommend that you first review the // following important information about how the IAM Identity Center OIDC service diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/go_module_metadata.go index 84251218b2..3094b12a73 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/go_module_metadata.go @@ -3,4 +3,4 @@ package ssooidc // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.28.7" +const goModuleVersion = "1.28.14" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/CHANGELOG.md index c72a40981e..9f4f530771 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/CHANGELOG.md @@ -1,3 +1,48 @@ +# v1.33.14 (2025-02-05) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.33.13 (2025-02-04) + +* No change notes available for this release. + +# v1.33.12 (2025-01-31) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.33.11 (2025-01-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.33.10 (2025-01-24) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.22.2. + +# v1.33.9 (2025-01-17) + +* **Bug Fix**: Fix bug where credentials weren't refreshed during retry loop. + +# v1.33.8 (2025-01-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.33.7 (2025-01-14) + +* No change notes available for this release. + +# v1.33.6 (2025-01-10) + +* **Documentation**: Fixed typos in the descriptions. + +# v1.33.5 (2025-01-09) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.33.4 (2025-01-08) + +* No change notes available for this release. + # v1.33.3 (2024-12-19) * **Dependency Update**: Updated to the latest SDK module versions diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_client.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_client.go index 4e678ce2ae..25787325f2 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_client.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_client.go @@ -688,7 +688,7 @@ func addRetry(stack *middleware.Stack, o Options) error { m.LogAttempts = o.ClientLogMode.IsRetries() m.OperationMeter = o.MeterProvider.Meter("github.com/aws/aws-sdk-go-v2/service/sts") }) - if err := stack.Finalize.Insert(attempt, "Signing", middleware.Before); err != nil { + if err := stack.Finalize.Insert(attempt, "ResolveAuthScheme", middleware.Before); err != nil { return err } if err := stack.Finalize.Insert(&retry.MetricsHeader{}, attempt.ID(), middleware.After); err != nil { diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRole.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRole.go index 8838f4fb8a..d056327746 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRole.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRole.go @@ -295,7 +295,7 @@ type AssumeRoleInput struct { // // The regex used to validate this parameter is a string of characters consisting // of upper- and lower-case alphanumeric characters with no spaces. You can also - // include underscores or any of the following characters: =,.@-. You cannot use a + // include underscores or any of the following characters: +=,.@-. You cannot use a // value that begins with the text aws: . This prefix is reserved for Amazon Web // Services internal use. // diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithWebIdentity.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithWebIdentity.go index 803cded5a4..0ae4bc173e 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithWebIdentity.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithWebIdentity.go @@ -198,8 +198,9 @@ type AssumeRoleWithWebIdentityInput struct { // identity provider. Your application must get this token by authenticating the // user who is using your application with a web identity provider before the // application makes an AssumeRoleWithWebIdentity call. Timestamps in the token - // must be formatted as either an integer or a long integer. Only tokens with RSA - // algorithms (RS256) are supported. + // must be formatted as either an integer or a long integer. Tokens must be signed + // using either RSA keys (RS256, RS384, or RS512) or ECDSA keys (ES256, ES384, or + // ES512). // // This member is required. WebIdentityToken *string diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoot.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoot.go index 537ab87527..cd976e573a 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoot.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoot.go @@ -12,14 +12,14 @@ import ( ) // Returns a set of short term credentials you can use to perform privileged tasks -// in a member account. +// on a member account in your organization. // -// Before you can launch a privileged session, you must have enabled centralized -// root access in your organization. For steps to enable this feature, see [Centralize root access for member accounts]in the -// IAM User Guide. +// Before you can launch a privileged session, you must have centralized root +// access in your organization. For steps to enable this feature, see [Centralize root access for member accounts]in the IAM +// User Guide. // -// The global endpoint is not supported for AssumeRoot. You must send this request -// to a Regional STS endpoint. For more information, see [Endpoints]. +// The STS global endpoint is not supported for AssumeRoot. You must send this +// request to a Regional STS endpoint. For more information, see [Endpoints]. // // You can track AssumeRoot in CloudTrail logs to determine what actions were // performed in a session. For more information, see [Track privileged tasks in CloudTrail]in the IAM User Guide. @@ -51,8 +51,7 @@ type AssumeRootInput struct { // The identity based policy that scopes the session to the privileged tasks that // can be performed. You can use one of following Amazon Web Services managed - // policies to scope root session actions. You can add additional customer managed - // policies to further limit the permissions for the root session. + // policies to scope root session actions. // // [IAMAuditRootUserCredentials] // diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/go_module_metadata.go index c55eca63a7..8e3322f29b 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/go_module_metadata.go @@ -3,4 +3,4 @@ package sts // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.33.3" +const goModuleVersion = "1.33.14" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/internal/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/internal/endpoints/endpoints.go index 9fe930b8d7..8fc2012a69 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/internal/endpoints/endpoints.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/internal/endpoints/endpoints.go @@ -175,6 +175,9 @@ var defaultPartitions = endpoints.Partitions{ endpoints.EndpointKey{ Region: "ap-southeast-5", }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "ap-southeast-7", + }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "aws-global", }: endpoints.Endpoint{ @@ -222,6 +225,9 @@ var defaultPartitions = endpoints.Partitions{ endpoints.EndpointKey{ Region: "me-south-1", }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "mx-central-1", + }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "sa-east-1", }: endpoints.Endpoint{}, @@ -438,6 +444,14 @@ var defaultPartitions = endpoints.Partitions{ }, RegionRegex: partitionRegexp.AwsIsoF, IsRegionalized: true, + Endpoints: endpoints.Endpoints{ + endpoints.EndpointKey{ + Region: "us-isof-east-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "us-isof-south-1", + }: endpoints.Endpoint{}, + }, }, { ID: "aws-us-gov", diff --git a/vendor/github.com/aws/smithy-go/CHANGELOG.md b/vendor/github.com/aws/smithy-go/CHANGELOG.md index 56b19e3a1c..de39171cf0 100644 --- a/vendor/github.com/aws/smithy-go/CHANGELOG.md +++ b/vendor/github.com/aws/smithy-go/CHANGELOG.md @@ -1,3 +1,13 @@ +# Release (2025-01-21) + +## General Highlights +* **Dependency Update**: Updated to the latest SDK module versions + +## Module Highlights +* `github.com/aws/smithy-go`: v1.22.2 + * **Bug Fix**: Fix HTTP metrics data race. + * **Bug Fix**: Replace usages of deprecated ioutil package. + # Release (2024-11-15) ## General Highlights diff --git a/vendor/github.com/aws/smithy-go/CONTRIBUTING.md b/vendor/github.com/aws/smithy-go/CONTRIBUTING.md index c4b6a1c508..1f8d01ff6a 100644 --- a/vendor/github.com/aws/smithy-go/CONTRIBUTING.md +++ b/vendor/github.com/aws/smithy-go/CONTRIBUTING.md @@ -39,6 +39,37 @@ To send us a pull request, please: GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). +### Changelog Documents + +(You can SKIP this step if you are only changing the code generator, and not the runtime). + +When submitting a pull request please include a changelog file on a folder named `.changelog`. +These are used to generate the content `CHANGELOG.md` and Release Notes. The format of the file is as follows: + +``` +{ + "id": "12345678-1234-1234-1234-123456789012" + "type": "bugfix" + "collapse": true + "description": "Fix improper use of printf-style functions.", + "modules": [ + "." + ] +} +``` + +* id: a UUID. This should also be used for the name of the file, so if your id is `12345678-1234-1234-1234-123456789012` the file should be named `12345678-1234-1234-1234-123456789012.json/` +* type: one of the following: + * bugfix: Fixing an existing bug + * Feature: Adding a new feature to an existing service + * Release: Releasing a new module + * Dependency: Updating dependencies + * Announcement: Making an announcement, like deprecation of a module +* collapse: whether this change should appear separately on the release notes on every module listed on `modules` (`"collapse": false`), or if it should show up as a single entry (`"collapse": true`) + * For the smithy-go repository this should always be `false` +* description: Description of this change. Most of the times is the same as the title of the PR +* modules: which Go modules does this change impact. The root module is expressed as "." + ## Finding contributions to work on Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start. diff --git a/vendor/github.com/aws/smithy-go/Makefile b/vendor/github.com/aws/smithy-go/Makefile index e66fa8cace..a3c2cf173d 100644 --- a/vendor/github.com/aws/smithy-go/Makefile +++ b/vendor/github.com/aws/smithy-go/Makefile @@ -98,5 +98,12 @@ module-version: ############## .PHONY: install-changelog +external-changelog: + mkdir -p .changelog + cp changelog-template.json .changelog/00000000-0000-0000-0000-000000000000.json + @echo "Generate a new UUID and update the file at .changelog/00000000-0000-0000-0000-000000000000.json" + @echo "Make sure to rename the file with your new id, like .changelog/12345678-1234-1234-1234-123456789012.json" + @echo "See CONTRIBUTING.md 'Changelog Documents' and an example at https://github.com/aws/smithy-go/pull/543/files" + install-changelog: go install ${REPOTOOLS_MODULE}/cmd/changelog@${REPOTOOLS_VERSION} diff --git a/vendor/github.com/aws/smithy-go/changelog-template.json b/vendor/github.com/aws/smithy-go/changelog-template.json new file mode 100644 index 0000000000..d36e2b3e1a --- /dev/null +++ b/vendor/github.com/aws/smithy-go/changelog-template.json @@ -0,0 +1,9 @@ +{ + "id": "00000000-0000-0000-0000-000000000000", + "type": "feature|bugfix|dependency", + "description": "Description of your changes", + "collapse": false, + "modules": [ + "." + ] +} diff --git a/vendor/github.com/aws/smithy-go/go_module_metadata.go b/vendor/github.com/aws/smithy-go/go_module_metadata.go index 212eae4fab..a51ceca4ce 100644 --- a/vendor/github.com/aws/smithy-go/go_module_metadata.go +++ b/vendor/github.com/aws/smithy-go/go_module_metadata.go @@ -3,4 +3,4 @@ package smithy // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.22.1" +const goModuleVersion = "1.22.2" diff --git a/vendor/github.com/aws/smithy-go/transport/http/host.go b/vendor/github.com/aws/smithy-go/transport/http/host.go index 6b290fec03..db9801bea5 100644 --- a/vendor/github.com/aws/smithy-go/transport/http/host.go +++ b/vendor/github.com/aws/smithy-go/transport/http/host.go @@ -69,7 +69,7 @@ func ValidPortNumber(port string) bool { return true } -// ValidHostLabel returns whether the label is a valid RFC 3986 host abel. +// ValidHostLabel returns whether the label is a valid RFC 3986 host label. func ValidHostLabel(label string) bool { if l := len(label); l == 0 || l > 63 { return false diff --git a/vendor/github.com/aws/smithy-go/transport/http/metrics.go b/vendor/github.com/aws/smithy-go/transport/http/metrics.go index ab1101394c..d1beaa595d 100644 --- a/vendor/github.com/aws/smithy-go/transport/http/metrics.go +++ b/vendor/github.com/aws/smithy-go/transport/http/metrics.go @@ -5,6 +5,7 @@ import ( "crypto/tls" "net/http" "net/http/httptrace" + "sync/atomic" "time" "github.com/aws/smithy-go/metrics" @@ -42,10 +43,10 @@ type timedClientDo struct { } func (c *timedClientDo) Do(r *http.Request) (*http.Response, error) { - c.hm.doStart = now() + c.hm.doStart.Store(now()) resp, err := c.ClientDo.Do(r) - c.hm.DoRequestDuration.Record(r.Context(), elapsed(c.hm.doStart)) + c.hm.DoRequestDuration.Record(r.Context(), c.hm.doStart.Elapsed()) return resp, err } @@ -58,10 +59,10 @@ type httpMetrics struct { DoRequestDuration metrics.Float64Histogram // client.http.do_request_duration TimeToFirstByte metrics.Float64Histogram // client.http.time_to_first_byte - doStart time.Time - dnsStart time.Time - connectStart time.Time - tlsStart time.Time + doStart safeTime + dnsStart safeTime + connectStart safeTime + tlsStart safeTime } func newHTTPMetrics(meter metrics.Meter) (*httpMetrics, error) { @@ -115,15 +116,15 @@ func newHTTPMetrics(meter metrics.Meter) (*httpMetrics, error) { } func (m *httpMetrics) DNSStart(httptrace.DNSStartInfo) { - m.dnsStart = now() + m.dnsStart.Store(now()) } func (m *httpMetrics) ConnectStart(string, string) { - m.connectStart = now() + m.connectStart.Store(now()) } func (m *httpMetrics) TLSHandshakeStart() { - m.tlsStart = now() + m.tlsStart.Store(now()) } func (m *httpMetrics) GotConn(ctx context.Context) func(httptrace.GotConnInfo) { @@ -140,25 +141,25 @@ func (m *httpMetrics) PutIdleConn(ctx context.Context) func(error) { func (m *httpMetrics) DNSDone(ctx context.Context) func(httptrace.DNSDoneInfo) { return func(httptrace.DNSDoneInfo) { - m.DNSLookupDuration.Record(ctx, elapsed(m.dnsStart)) + m.DNSLookupDuration.Record(ctx, m.dnsStart.Elapsed()) } } func (m *httpMetrics) ConnectDone(ctx context.Context) func(string, string, error) { return func(string, string, error) { - m.ConnectDuration.Record(ctx, elapsed(m.connectStart)) + m.ConnectDuration.Record(ctx, m.connectStart.Elapsed()) } } func (m *httpMetrics) TLSHandshakeDone(ctx context.Context) func(tls.ConnectionState, error) { return func(tls.ConnectionState, error) { - m.TLSHandshakeDuration.Record(ctx, elapsed(m.tlsStart)) + m.TLSHandshakeDuration.Record(ctx, m.tlsStart.Elapsed()) } } func (m *httpMetrics) GotFirstResponseByte(ctx context.Context) func() { return func() { - m.TimeToFirstByte.Record(ctx, elapsed(m.doStart)) + m.TimeToFirstByte.Record(ctx, m.doStart.Elapsed()) } } @@ -177,8 +178,21 @@ func (m *httpMetrics) addConnIdle(ctx context.Context, incr int64) { }) } -func elapsed(start time.Time) float64 { +type safeTime struct { + atomic.Value // time.Time +} + +func (st *safeTime) Store(v time.Time) { + st.Value.Store(v) +} + +func (st *safeTime) Load() time.Time { + t, _ := st.Value.Load().(time.Time) + return t +} + +func (st *safeTime) Elapsed() float64 { end := now() - elapsed := end.Sub(start) + elapsed := end.Sub(st.Load()) return float64(elapsed) / 1e9 } diff --git a/vendor/github.com/aws/smithy-go/transport/http/middleware_close_response_body.go b/vendor/github.com/aws/smithy-go/transport/http/middleware_close_response_body.go index 1d3b218a12..914338f2e7 100644 --- a/vendor/github.com/aws/smithy-go/transport/http/middleware_close_response_body.go +++ b/vendor/github.com/aws/smithy-go/transport/http/middleware_close_response_body.go @@ -2,10 +2,10 @@ package http import ( "context" + "io" + "github.com/aws/smithy-go/logging" "github.com/aws/smithy-go/middleware" - "io" - "io/ioutil" ) // AddErrorCloseResponseBodyMiddleware adds the middleware to automatically @@ -30,7 +30,7 @@ func (m *errorCloseResponseBodyMiddleware) HandleDeserialize( if err != nil { if resp, ok := out.RawResponse.(*Response); ok && resp != nil && resp.Body != nil { // Consume the full body to prevent TCP connection resets on some platforms - _, _ = io.Copy(ioutil.Discard, resp.Body) + _, _ = io.Copy(io.Discard, resp.Body) // Do not validate that the response closes successfully. resp.Body.Close() } @@ -64,7 +64,7 @@ func (m *closeResponseBody) HandleDeserialize( if resp, ok := out.RawResponse.(*Response); ok { // Consume the full body to prevent TCP connection resets on some platforms - _, copyErr := io.Copy(ioutil.Discard, resp.Body) + _, copyErr := io.Copy(io.Discard, resp.Body) if copyErr != nil { middleware.GetLogger(ctx).Logf(logging.Warn, "failed to discard remaining HTTP response body, this may affect connection reuse") } diff --git a/vendor/github.com/aws/smithy-go/transport/http/request.go b/vendor/github.com/aws/smithy-go/transport/http/request.go index 7177d6f957..5cbf6f10ac 100644 --- a/vendor/github.com/aws/smithy-go/transport/http/request.go +++ b/vendor/github.com/aws/smithy-go/transport/http/request.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "net/http" "net/url" "strings" @@ -167,7 +166,7 @@ func (r *Request) Build(ctx context.Context) *http.Request { switch stream := r.stream.(type) { case *io.PipeReader: - req.Body = ioutil.NopCloser(stream) + req.Body = io.NopCloser(stream) req.ContentLength = -1 default: // HTTP Client Request must only have a non-nil body if the @@ -175,7 +174,7 @@ func (r *Request) Build(ctx context.Context) *http.Request { // Client will interpret a non-nil body and ContentLength 0 as // "unknown". This is unwanted behavior. if req.ContentLength != 0 && r.stream != nil { - req.Body = iointernal.NewSafeReadCloser(ioutil.NopCloser(stream)) + req.Body = iointernal.NewSafeReadCloser(io.NopCloser(stream)) } } diff --git a/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/api/client.go b/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/api/client.go index 02ed9762dd..ae452396b4 100644 --- a/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/api/client.go +++ b/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/api/client.go @@ -1,4 +1,4 @@ -// Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may // not use this file except in compliance with the License. A copy of the @@ -37,7 +37,7 @@ const ( ecrPublicEndpoint = proxyEndpointScheme + ecrPublicName ) -var ecrPattern = regexp.MustCompile(`(^[a-zA-Z0-9][a-zA-Z0-9-_]*)\.dkr\.ecr(-fips)?\.([a-zA-Z0-9][a-zA-Z0-9-_]*)\.amazonaws\.com(\.cn)?$`) +var ecrPattern = regexp.MustCompile(`^(\d{12})\.dkr\.ecr(\-fips)?\.([a-zA-Z0-9][a-zA-Z0-9-_]*)\.(amazonaws\.com(\.cn)?|sc2s\.sgov\.gov|c2s\.ic\.gov|cloud\.adc-e\.uk|csp\.hci\.ic\.gov)$`) type Service string diff --git a/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/api/factory.go b/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/api/factory.go index 110a6c3bdd..58626d4e07 100644 --- a/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/api/factory.go +++ b/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/api/factory.go @@ -1,4 +1,4 @@ -// Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may // not use this file except in compliance with the License. A copy of the diff --git a/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/cache/build.go b/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/cache/build.go index 8aa21287dc..8647378cca 100644 --- a/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/cache/build.go +++ b/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/cache/build.go @@ -1,4 +1,4 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may // not use this file except in compliance with the License. A copy of the diff --git a/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/cache/credentials.go b/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/cache/credentials.go index 0b74c0f310..90568777a0 100644 --- a/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/cache/credentials.go +++ b/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/cache/credentials.go @@ -1,4 +1,4 @@ -// Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may // not use this file except in compliance with the License. A copy of the diff --git a/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/cache/file.go b/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/cache/file.go index 19dc33bb5e..81fcf0f285 100644 --- a/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/cache/file.go +++ b/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/cache/file.go @@ -1,4 +1,4 @@ -// Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may // not use this file except in compliance with the License. A copy of the diff --git a/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/cache/null.go b/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/cache/null.go index 64a7212bd3..7ea633bcf1 100644 --- a/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/cache/null.go +++ b/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/cache/null.go @@ -1,4 +1,4 @@ -// Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may // not use this file except in compliance with the License. A copy of the diff --git a/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/config/cache_dir.go b/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/config/cache_dir.go index d7c2ee6446..8bad184538 100644 --- a/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/config/cache_dir.go +++ b/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/config/cache_dir.go @@ -1,4 +1,4 @@ -// Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may // not use this file except in compliance with the License. A copy of the diff --git a/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/config/log.go b/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/config/log.go index 771611bad2..e4c0b5b2d2 100644 --- a/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/config/log.go +++ b/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/config/log.go @@ -1,4 +1,4 @@ -// Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may // not use this file except in compliance with the License. A copy of the diff --git a/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/ecr.go b/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/ecr.go index 461e3090a3..5fbbd0eca9 100644 --- a/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/ecr.go +++ b/vendor/github.com/awslabs/amazon-ecr-credential-helper/ecr-login/ecr.go @@ -1,4 +1,4 @@ -// Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may // not use this file except in compliance with the License. A copy of the @@ -17,6 +17,7 @@ import ( "errors" "fmt" "io" + "os" "github.com/sirupsen/logrus" @@ -70,14 +71,38 @@ func NewECRHelper(opts ...Option) *ECRHelper { // ensure ECRHelper adheres to the credentials.Helper interface var _ credentials.Helper = (*ECRHelper)(nil) -func (ECRHelper) Add(creds *credentials.Credentials) error { - // This does not seem to get called - return notImplemented +func shouldIgnoreCredsStorage() bool { + return os.Getenv("AWS_ECR_IGNORE_CREDS_STORAGE") == "true" } -func (ECRHelper) Delete(serverURL string) error { - // This does not seem to get called - return notImplemented +// Add tries to store credentials when docker requests it. This usually happens during `docker login` calls. In our context, +// storing arbitrary user given credentials makes no sense. +func (self ECRHelper) Add(creds *credentials.Credentials) error { + if shouldIgnoreCredsStorage() { + self.logger. + WithField("serverURL", creds.ServerURL). + Warning("Ignoring request to store credentials since AWS_ECR_IGNORE_CREDS_STORAGE env variable is set." + + "ecr-login does not require 'docker login', and does not support persisting temporary ECR-issued credentials.") + return nil + } else { + self.logger.Warning("Add() is not supported by the ecr-login credentials helper as all issued credentials are temporary. Consider setting the AWS_ECR_IGNORE_CREDS_STORAGE env variable (see documentation for details).") + return notImplemented + } +} + +// Delete tries to delete credentials when docker requests it. This usually happens during `docker logout` calls. In our context, we +// don't store arbitrary user given credentials so deleting them makes no sense. +func (self ECRHelper) Delete(serverURL string) error { + if shouldIgnoreCredsStorage() { + self.logger. + WithField("serverURL", serverURL). + Warning("Ignoring request to store credentials since AWS_ECR_IGNORE_CREDS_STORAGE env variable is set." + + "ecr-login does not require 'docker login', and does not support persisting temporary ECR-issued credentials.") + return nil + } else { + self.logger.Warning("Delete() credentials is not supported by the ecr-login credentials helper as all issued credentials are temporary. Consider setting the AWS_ECR_IGNORE_CREDS_STORAGE env variable (see documentation for details).") + return notImplemented + } } func (self ECRHelper) Get(serverURL string) (string, string, error) { diff --git a/vendor/github.com/buildkite/agent/v3/api/artifacts.go b/vendor/github.com/buildkite/agent/v3/api/artifacts.go index 3554971165..351345de9d 100644 --- a/vendor/github.com/buildkite/agent/v3/api/artifacts.go +++ b/vendor/github.com/buildkite/agent/v3/api/artifacts.go @@ -51,25 +51,47 @@ type Artifact struct { } type ArtifactBatch struct { - ID string `json:"id"` - Artifacts []*Artifact `json:"artifacts"` - UploadDestination string `json:"upload_destination"` + ID string `json:"id"` + Artifacts []*Artifact `json:"artifacts"` + UploadDestination string `json:"upload_destination"` + MultipartSupported bool `json:"multipart_supported,omitempty"` } +// ArtifactUploadInstructions describes how to upload an artifact to Buildkite +// artifact storage. type ArtifactUploadInstructions struct { - Data map[string]string `json:"data"` - Action struct { - URL string `json:"url,omitempty"` - Method string `json:"method"` - Path string `json:"path"` - FileInput string `json:"file_input"` - } + // Used for a single-part upload. + Action ArtifactUploadAction `json:"action"` + + // Used for a multi-part upload. + Actions []ArtifactUploadAction `json:"actions"` + + // Contains other data necessary for interpreting instructions. + Data map[string]string `json:"data"` +} + +// ArtifactUploadAction describes one action needed to upload an artifact or +// part of an artifact to Buildkite artifact storage. +type ArtifactUploadAction struct { + URL string `json:"url,omitempty"` + Method string `json:"method"` + Path string `json:"path"` + FileInput string `json:"file_input"` + PartNumber int `json:"part_number,omitempty"` } type ArtifactBatchCreateResponse struct { - ID string `json:"id"` - ArtifactIDs []string `json:"artifact_ids"` - UploadInstructions *ArtifactUploadInstructions `json:"upload_instructions"` + ID string `json:"id"` + ArtifactIDs []string `json:"artifact_ids"` + + // These instructions apply to all artifacts. The template contains + // variable interpolations such as ${artifact:path}. + InstructionsTemplate *ArtifactUploadInstructions `json:"upload_instructions"` + + // These instructions apply to specific artifacts, necessary for multipart + // uploads. It overrides InstructionTemplate and should not contain + // interpolations. Map: artifact ID -> instructions for that artifact. + PerArtifactInstructions map[string]*ArtifactUploadInstructions `json:"per_artifact_instructions"` } // ArtifactSearchOptions specifies the optional parameters to the @@ -82,18 +104,29 @@ type ArtifactSearchOptions struct { IncludeDuplicates bool `url:"include_duplicates,omitempty"` } -type ArtifactBatchUpdateArtifact struct { - ID string `json:"id"` - State string `json:"state"` +// ArtifactState represents the state of a single artifact, when calling UpdateArtifacts. +type ArtifactState struct { + ID string `json:"id"` + State string `json:"state"` + Multipart bool `json:"multipart,omitempty"` + // If this artifact was a multipart upload and is complete, we need the + // the ETag from each uploaded part so that they can be joined together. + MultipartETags []ArtifactPartETag `json:"multipart_etags,omitempty"` +} + +// ArtifactPartETag associates an ETag to a part number for a multipart upload. +type ArtifactPartETag struct { + PartNumber int `json:"part_number"` + ETag string `json:"etag"` } type ArtifactBatchUpdateRequest struct { - Artifacts []*ArtifactBatchUpdateArtifact `json:"artifacts"` + Artifacts []ArtifactState `json:"artifacts"` } // CreateArtifacts takes a slice of artifacts, and creates them on Buildkite as a batch. -func (c *Client) CreateArtifacts(ctx context.Context, jobId string, batch *ArtifactBatch) (*ArtifactBatchCreateResponse, *Response, error) { - u := fmt.Sprintf("jobs/%s/artifacts", railsPathEscape(jobId)) +func (c *Client) CreateArtifacts(ctx context.Context, jobID string, batch *ArtifactBatch) (*ArtifactBatchCreateResponse, *Response, error) { + u := fmt.Sprintf("jobs/%s/artifacts", railsPathEscape(jobID)) req, err := c.newRequest(ctx, "POST", u, batch) if err != nil { @@ -109,13 +142,11 @@ func (c *Client) CreateArtifacts(ctx context.Context, jobId string, batch *Artif return createResponse, resp, err } -// Updates a particular artifact -func (c *Client) UpdateArtifacts(ctx context.Context, jobId string, artifactStates map[string]string) (*Response, error) { - u := fmt.Sprintf("jobs/%s/artifacts", railsPathEscape(jobId)) - payload := ArtifactBatchUpdateRequest{} - - for id, state := range artifactStates { - payload.Artifacts = append(payload.Artifacts, &ArtifactBatchUpdateArtifact{id, state}) +// UpdateArtifacts updates Buildkite with one or more artifact states. +func (c *Client) UpdateArtifacts(ctx context.Context, jobID string, artifactStates []ArtifactState) (*Response, error) { + u := fmt.Sprintf("jobs/%s/artifacts", railsPathEscape(jobID)) + payload := ArtifactBatchUpdateRequest{ + Artifacts: artifactStates, } req, err := c.newRequest(ctx, "PUT", u, payload) @@ -123,17 +154,12 @@ func (c *Client) UpdateArtifacts(ctx context.Context, jobId string, artifactStat return nil, err } - resp, err := c.doRequest(req, nil) - if err != nil { - return resp, err - } - - return resp, err + return c.doRequest(req, nil) } // SearchArtifacts searches Buildkite for a set of artifacts -func (c *Client) SearchArtifacts(ctx context.Context, buildId string, opt *ArtifactSearchOptions) ([]*Artifact, *Response, error) { - u := fmt.Sprintf("builds/%s/artifacts/search", railsPathEscape(buildId)) +func (c *Client) SearchArtifacts(ctx context.Context, buildID string, opt *ArtifactSearchOptions) ([]*Artifact, *Response, error) { + u := fmt.Sprintf("builds/%s/artifacts/search", railsPathEscape(buildID)) u, err := addOptions(u, opt) if err != nil { return nil, nil, err diff --git a/vendor/github.com/buildkite/agent/v3/api/auth.go b/vendor/github.com/buildkite/agent/v3/api/auth.go deleted file mode 100644 index 1fb28da103..0000000000 --- a/vendor/github.com/buildkite/agent/v3/api/auth.go +++ /dev/null @@ -1,37 +0,0 @@ -package api - -import ( - "fmt" - "net/http" -) - -type canceler interface { - CancelRequest(*http.Request) -} - -// authenticatedTransport manages injection of the API token -type authenticatedTransport struct { - // The Token used for authentication. This can either the be - // organizations registration token, or the agents access token. - Token string - - // Delegate is the underlying HTTP transport - Delegate http.RoundTripper -} - -// RoundTrip invoked each time a request is made -func (t authenticatedTransport) RoundTrip(req *http.Request) (*http.Response, error) { - if t.Token == "" { - return nil, fmt.Errorf("Invalid token, empty string supplied") - } - - req.Header.Set("Authorization", fmt.Sprintf("Token %s", t.Token)) - - return t.Delegate.RoundTrip(req) -} - -// CancelRequest cancels an in-flight request by closing its connection. -func (t *authenticatedTransport) CancelRequest(req *http.Request) { - cancelableTransport := t.Delegate.(canceler) - cancelableTransport.CancelRequest(req) -} diff --git a/vendor/github.com/buildkite/agent/v3/api/builds.go b/vendor/github.com/buildkite/agent/v3/api/builds.go new file mode 100644 index 0000000000..6da8ef03ae --- /dev/null +++ b/vendor/github.com/buildkite/agent/v3/api/builds.go @@ -0,0 +1,28 @@ +package api + +import ( + "context" + "fmt" +) + +type Build struct { + UUID string `json:"uuid"` +} + +// CancelBuild cancels a build with the given UUID +func (c *Client) CancelBuild(ctx context.Context, uuid string) (*Build, *Response, error) { + u := fmt.Sprintf("builds/%s/cancel", railsPathEscape(uuid)) + + req, err := c.newRequest(ctx, "POST", u, nil) + if err != nil { + return nil, nil, err + } + + build := new(Build) + resp, err := c.doRequest(req, build) + if err != nil { + return nil, resp, err + } + + return build, resp, nil +} diff --git a/vendor/github.com/buildkite/agent/v3/api/client.go b/vendor/github.com/buildkite/agent/v3/api/client.go index 643911cded..9803437b2d 100644 --- a/vendor/github.com/buildkite/agent/v3/api/client.go +++ b/vendor/github.com/buildkite/agent/v3/api/client.go @@ -11,13 +11,13 @@ import ( "fmt" "io" "net/http" - "net/http/httputil" "net/url" "reflect" "strconv" "strings" "time" + "github.com/buildkite/agent/v3/internal/agenthttp" "github.com/buildkite/agent/v3/logger" "github.com/google/go-querystring/query" ) @@ -45,6 +45,9 @@ type Config struct { // If true, requests and responses will be dumped and set to the logger DebugHTTP bool + // If true timings for each request will be logged + TraceHTTP bool + // The http client used, leave nil for the default HTTPClient *http.Client @@ -74,38 +77,22 @@ func NewClient(l logger.Logger, conf Config) *Client { conf.UserAgent = defaultUserAgent } - httpClient := conf.HTTPClient - if conf.HTTPClient == nil { - - // use the default transport as it is optimized and configured for http2 - // and will avoid accidents in the future - tr := http.DefaultTransport.(*http.Transport).Clone() - - if conf.DisableHTTP2 { - tr.ForceAttemptHTTP2 = false - tr.TLSNextProto = make(map[string]func(authority string, c *tls.Conn) http.RoundTripper) - // The default TLSClientConfig has h2 in NextProtos, so the negotiated TLS connection will assume h2 support. - // see https://github.com/golang/go/issues/50571 - tr.TLSClientConfig.NextProtos = []string{"http/1.1"} - } - - if conf.TLSConfig != nil { - tr.TLSClientConfig = conf.TLSConfig - } - - httpClient = &http.Client{ - Timeout: 60 * time.Second, - Transport: &authenticatedTransport{ - Token: conf.Token, - Delegate: tr, - }, + if conf.HTTPClient != nil { + return &Client{ + logger: l, + client: conf.HTTPClient, + conf: conf, } } return &Client{ logger: l, - client: httpClient, - conf: conf, + client: agenthttp.NewClient( + agenthttp.WithAuthToken(conf.Token), + agenthttp.WithAllowHTTP2(!conf.DisableHTTP2), + agenthttp.WithTLSConfig(conf.TLSConfig), + ), + conf: conf, } } @@ -232,58 +219,20 @@ func newResponse(r *http.Response) *Response { // interface, the raw response body will be written to v, without attempting to // first decode it. func (c *Client) doRequest(req *http.Request, v any) (*Response, error) { - var err error - - if c.conf.DebugHTTP { - // If the request is a multi-part form, then it's probably a - // file upload, in which case we don't want to spewing out the - // file contents into the debug log (especially if it's been - // gzipped) - var requestDump []byte - if strings.Contains(req.Header.Get("Content-Type"), "multipart/form-data") { - requestDump, err = httputil.DumpRequestOut(req, false) - } else { - requestDump, err = httputil.DumpRequestOut(req, true) - } - - if err != nil { - c.logger.Debug("ERR: %s\n%s", err, string(requestDump)) - } else { - c.logger.Debug("%s", string(requestDump)) - } - } - - ts := time.Now() - c.logger.Debug("%s %s", req.Method, req.URL) - - resp, err := c.client.Do(req) + resp, err := agenthttp.Do(c.logger, c.client, req, + agenthttp.WithDebugHTTP(c.conf.DebugHTTP), + agenthttp.WithTraceHTTP(c.conf.TraceHTTP), + ) if err != nil { return nil, err } - - c.logger.WithFields( - logger.StringField("proto", resp.Proto), - logger.IntField("status", resp.StatusCode), - logger.DurationField("Δ", time.Since(ts)), - ).Debug("↳ %s %s", req.Method, req.URL) - defer resp.Body.Close() defer io.Copy(io.Discard, resp.Body) response := newResponse(resp) - if c.conf.DebugHTTP { - responseDump, err := httputil.DumpResponse(resp, true) - if err != nil { - c.logger.Debug("\nERR: %s\n%s", err, string(responseDump)) - } else { - c.logger.Debug("\n%s", string(responseDump)) - } - } - - err = checkResponse(resp) - if err != nil { + if err := checkResponse(resp); err != nil { // even though there was an error, we still return the response // in case the caller wants to inspect it further return response, err @@ -303,7 +252,7 @@ func (c *Client) doRequest(req *http.Request, v any) (*Response, error) { } } - return response, err + return response, nil } // ErrorResponse provides a message. diff --git a/vendor/github.com/buildkite/agent/v3/api/oidc.go b/vendor/github.com/buildkite/agent/v3/api/oidc.go index d11e35726c..b28378894e 100644 --- a/vendor/github.com/buildkite/agent/v3/api/oidc.go +++ b/vendor/github.com/buildkite/agent/v3/api/oidc.go @@ -10,21 +10,24 @@ type OIDCToken struct { } type OIDCTokenRequest struct { - Job string - Audience string - Lifetime int - Claims []string + Job string + Audience string + Lifetime int + Claims []string + AWSSessionTags []string } func (c *Client) OIDCToken(ctx context.Context, methodReq *OIDCTokenRequest) (*OIDCToken, *Response, error) { m := &struct { - Audience string `json:"audience,omitempty"` - Lifetime int `json:"lifetime,omitempty"` - Claims []string `json:"claims,omitempty"` + Audience string `json:"audience,omitempty"` + Lifetime int `json:"lifetime,omitempty"` + Claims []string `json:"claims,omitempty"` + AWSSessionTags []string `json:"aws_session_tags,omitempty"` }{ - Audience: methodReq.Audience, - Lifetime: methodReq.Lifetime, - Claims: methodReq.Claims, + Audience: methodReq.Audience, + Lifetime: methodReq.Lifetime, + Claims: methodReq.Claims, + AWSSessionTags: methodReq.AWSSessionTags, } u := fmt.Sprintf("jobs/%s/oidc/tokens", railsPathEscape(methodReq.Job)) diff --git a/vendor/github.com/buildkite/agent/v3/api/steps.go b/vendor/github.com/buildkite/agent/v3/api/steps.go index b8ab745e79..dcf758478b 100644 --- a/vendor/github.com/buildkite/agent/v3/api/steps.go +++ b/vendor/github.com/buildkite/agent/v3/api/steps.go @@ -54,3 +54,31 @@ func (c *Client) StepUpdate(ctx context.Context, stepIdOrKey string, stepUpdate return c.doRequest(req, nil) } + +type StepCancel struct { + Build string `json:"build_id"` + Force bool `json:"force"` + ForceGracePeriodSeconds int64 `json:"force_grace_period"` +} + +type StepCancelResponse struct { + UUID string `json:"uuid"` +} + +// StepCancel cancels a step +func (c *Client) StepCancel(ctx context.Context, stepIdOrKey string, stepCancel *StepCancel) (*StepCancelResponse, *Response, error) { + u := fmt.Sprintf("steps/%s/cancel", railsPathEscape(stepIdOrKey)) + + req, err := c.newRequest(ctx, "POST", u, stepCancel) + if err != nil { + return nil, nil, err + } + + stepCancelResponse := new(StepCancelResponse) + resp, err := c.doRequest(req, stepCancelResponse) + if err != nil { + return nil, resp, err + } + + return stepCancelResponse, resp, nil +} diff --git a/vendor/github.com/buildkite/agent/v3/internal/agenthttp/auth.go b/vendor/github.com/buildkite/agent/v3/internal/agenthttp/auth.go new file mode 100644 index 0000000000..9e34f80017 --- /dev/null +++ b/vendor/github.com/buildkite/agent/v3/internal/agenthttp/auth.go @@ -0,0 +1,85 @@ +package agenthttp + +import ( + "fmt" + "net/http" +) + +// authenticatedTransport manages injection of the API token into every request. +// Using a transport to inject credentials into every request like this is +// ugly because http.RoundTripper has specific requirements, but has +// precedent (e.g. https://github.com/golang/oauth2/blob/master/transport.go). +type authenticatedTransport struct { + // If set, the header "Authorization: Token %s" will be added to all requests. + // Mutually incompatible with Bearer. + Token string + + // If set, the header "Authorization: Bearer %s" will be added to all requests. + // Mutually incompatible with Token. + Bearer string + + // Delegate is the underlying HTTP transport + Delegate http.RoundTripper +} + +// RoundTrip invoked each time a request is made. +func (t authenticatedTransport) RoundTrip(req *http.Request) (*http.Response, error) { + // Per net/http#RoundTripper: + // + // "RoundTrip must always close the body, including on errors, ..." + reqBodyClosed := false + if req.Body != nil { + defer func() { + if !reqBodyClosed { + req.Body.Close() + } + }() + } + + if t.Token == "" && t.Bearer == "" { + return nil, fmt.Errorf("Invalid token, empty string supplied") + } + + // Per net/http#RoundTripper: + // + // "RoundTrip should not modify the request, except for + // consuming and closing the Request's Body. RoundTrip may + // read fields of the request in a separate goroutine. Callers + // should not mutate or reuse the request until the Response's + // Body has been closed." + // + // But we can pass a _different_ request to t.Delegate.RoundTrip. + // req.Clone does a sufficiently deep clone (including Header which we + // modify). + req = req.Clone(req.Context()) + switch { + case t.Token != "": + req.Header.Set("Authorization", "Token "+t.Token) + case t.Bearer != "": + req.Header.Set("Authorization", "Bearer "+t.Bearer) + } + + // req.Body is assumed to be closed by the delegate. + reqBodyClosed = true + return t.Delegate.RoundTrip(req) +} + +// CancelRequest forwards the call to t.Delegate, if it implements CancelRequest +// itself. +func (t *authenticatedTransport) CancelRequest(req *http.Request) { + canceler, ok := t.Delegate.(interface{ CancelRequest(*http.Request) }) + if !ok { + return + } + canceler.CancelRequest(req) +} + +// CloseIdleConnections forwards the call to t.Delegate, if it implements +// CloseIdleConnections itself. +func (t *authenticatedTransport) CloseIdleConnections() { + closer, ok := t.Delegate.(interface{ CloseIdleConnections() }) + if !ok { + return + } + closer.CloseIdleConnections() +} diff --git a/vendor/github.com/buildkite/agent/v3/internal/agenthttp/client.go b/vendor/github.com/buildkite/agent/v3/internal/agenthttp/client.go new file mode 100644 index 0000000000..6cead16292 --- /dev/null +++ b/vendor/github.com/buildkite/agent/v3/internal/agenthttp/client.go @@ -0,0 +1,138 @@ +// Package agenthttp creates standard Go [net/http.Client]s with common config +// options. +package agenthttp + +import ( + "crypto/tls" + "net/http" + "sync" + "time" + + "golang.org/x/net/http2" +) + +// NewClient creates a HTTP client. Note that the default timeout is 60 seconds; +// for some use cases (e.g. artifact operations) use [WithNoTimeout]. +func NewClient(opts ...ClientOption) *http.Client { + conf := clientConfig{ + // This spells out the defaults, even if some of them are zero values. + Bearer: "", + Token: "", + AllowHTTP2: true, + Timeout: 60 * time.Second, + TLSConfig: nil, + } + for _, opt := range opts { + opt(&conf) + } + + cacheKey := transportCacheKey{ + AllowHTTP2: conf.AllowHTTP2, + TLSConfig: conf.TLSConfig, + } + + transportCacheMu.Lock() + transport := transportCache[cacheKey] + if transport == nil { + transport = newTransport(&conf) + transportCache[cacheKey] = transport + } + transportCacheMu.Unlock() + + if conf.Bearer == "" && conf.Token == "" { + // No credentials, no authenticatedTransport wrapper. + return &http.Client{ + Timeout: conf.Timeout, + Transport: transport, + } + } + + // Wrap the transport in authenticatedTransport. + return &http.Client{ + Timeout: conf.Timeout, + Transport: &authenticatedTransport{ + Bearer: conf.Bearer, + Token: conf.Token, + Delegate: transport, + }, + } +} + +// Various NewClient options. +func WithAuthBearer(b string) ClientOption { return func(c *clientConfig) { c.Bearer = b } } +func WithAuthToken(t string) ClientOption { return func(c *clientConfig) { c.Token = t } } +func WithAllowHTTP2(a bool) ClientOption { return func(c *clientConfig) { c.AllowHTTP2 = a } } +func WithTimeout(d time.Duration) ClientOption { return func(c *clientConfig) { c.Timeout = d } } +func WithNoTimeout(c *clientConfig) { c.Timeout = 0 } +func WithTLSConfig(t *tls.Config) ClientOption { return func(c *clientConfig) { c.TLSConfig = t } } + +type ClientOption = func(*clientConfig) + +func newTransport(conf *clientConfig) *http.Transport { + // Base any modifications on the default transport. + transport := http.DefaultTransport.(*http.Transport).Clone() + // Allow override of TLSConfig. This must be set prior to calling + // http2.ConfigureTransports. + if conf.TLSConfig != nil { + transport.TLSClientConfig = conf.TLSConfig + } + + if conf.AllowHTTP2 { + // There is a bug in http2 on Linux regarding using dead connections. + // This is a workaround. See https://github.com/golang/go/issues/59690 + // + // Note that http2.ConfigureTransports alters its argument in order to + // supply http2 functionality, and the http2.Transport does not support + // HTTP/1.1 as a protocol, so we get slightly odd-looking code where + // we use `transport` later on instead of the just-returned `tr2`. + // tr2 is needed merely to configure the http2 option. + tr2, err := http2.ConfigureTransports(transport) + if err != nil { + // ConfigureTransports is documented to only return an error if + // the transport arg was already HTTP2-enabled, which it should not + // have been... + panic("http2.ConfigureTransports: " + err.Error()) + } + if tr2 != nil { + tr2.ReadIdleTimeout = 30 * time.Second + } + } else { + transport.TLSNextProto = make(map[string]func(string, *tls.Conn) http.RoundTripper) + // The default TLSClientConfig has h2 in NextProtos, so the + // negotiated TLS connection will assume h2 support. + // see https://github.com/golang/go/issues/50571 + transport.TLSClientConfig.NextProtos = []string{"http/1.1"} + } + + return transport +} + +type clientConfig struct { + // The authentication token/ bearer credential to use + // For agent API usage, Token is usually an agent registration or access token + // For GraphQL usage, Bearer is usually a user token + Token string + Bearer string + + // If false, HTTP2 is disabled + AllowHTTP2 bool + + // Timeout used as the client timeout. + Timeout time.Duration + + // optional TLS configuration primarily used for testing + TLSConfig *tls.Config +} + +// The underlying http.Transport is cached, mainly so that multiple clients with +// the same options can reuse connections. The options that affect the transport +// are also usually the same throughout the process. +type transportCacheKey struct { + AllowHTTP2 bool + TLSConfig *tls.Config +} + +var ( + transportCacheMu sync.Mutex + transportCache = make(map[transportCacheKey]*http.Transport) +) diff --git a/vendor/github.com/buildkite/agent/v3/internal/agenthttp/do.go b/vendor/github.com/buildkite/agent/v3/internal/agenthttp/do.go new file mode 100644 index 0000000000..6d60e2e26f --- /dev/null +++ b/vendor/github.com/buildkite/agent/v3/internal/agenthttp/do.go @@ -0,0 +1,186 @@ +package agenthttp + +import ( + "crypto/tls" + "fmt" + "net/http" + "net/http/httptrace" + "net/http/httputil" + "net/textproto" + "strconv" + "strings" + "time" + + "github.com/buildkite/agent/v3/logger" +) + +// Do wraps the http.Client's Do method with debug logging and tracing options. +func Do(l logger.Logger, client *http.Client, req *http.Request, opts ...DoOption) (*http.Response, error) { + var cfg doConfig + for _, opt := range opts { + opt(&cfg) + } + + if cfg.debugHTTP { + // If the request is a multi-part form, then it's probably a + // file upload, in which case we don't want to spewing out the + // file contents into the debug log (especially if it's been + // gzipped) + dumpBody := !strings.Contains(req.Header.Get("Content-Type"), "multipart/form-data") + requestDump, err := httputil.DumpRequestOut(req, dumpBody) + if err != nil { + l.Debug("ERR: %s\n%s", err, string(requestDump)) + } else { + l.Debug("%s", string(requestDump)) + } + } + + tracer := &tracer{Logger: l} + if cfg.traceHTTP { + // Inject a custom http tracer + req = traceHTTPRequest(req, tracer) + tracer.Start() + } + + ts := time.Now() + + l.Debug("%s %s", req.Method, req.URL) + + resp, err := client.Do(req) + if err != nil { + if cfg.traceHTTP { + tracer.EmitTraceToLog(logger.ERROR) + } + return nil, err + } + + l.WithFields( + logger.StringField("proto", resp.Proto), + logger.IntField("status", resp.StatusCode), + logger.DurationField("Δ", time.Since(ts)), + ).Debug("↳ %s %s", req.Method, req.URL) + + if cfg.debugHTTP { + responseDump, err := httputil.DumpResponse(resp, true) + if err != nil { + l.Debug("\nERR: %s\n%s", err, string(responseDump)) + } else { + l.Debug("\n%s", string(responseDump)) + } + } + if cfg.traceHTTP { + tracer.EmitTraceToLog(logger.DEBUG) + } + + return resp, err +} + +type DoOption = func(*doConfig) + +type doConfig struct { + debugHTTP bool + traceHTTP bool +} + +func WithDebugHTTP(d bool) DoOption { return func(c *doConfig) { c.debugHTTP = d } } +func WithTraceHTTP(t bool) DoOption { return func(c *doConfig) { c.traceHTTP = t } } + +type traceEvent struct { + event string + since time.Duration +} + +type tracer struct { + startTime time.Time + logger.Logger +} + +func (t *tracer) Start() { + t.startTime = time.Now() +} + +func (t *tracer) LogTiming(event string) { + t.Logger = t.Logger.WithFields(logger.DurationField(event, time.Since(t.startTime))) +} + +func (t *tracer) LogField(key, value string) { + t.Logger = t.Logger.WithFields(logger.StringField(key, value)) +} + +func (t *tracer) LogDuration(event string, d time.Duration) { + t.Logger = t.Logger.WithFields(logger.DurationField(event, d)) +} + +// Currently logger.Logger doesn't give us a way to set the level we want to emit logs at dynamically +func (t *tracer) EmitTraceToLog(level logger.Level) { + msg := "HTTP Timing Trace" + switch level { + case logger.DEBUG: + t.Debug(msg) + case logger.INFO: + t.Info(msg) + case logger.WARN: + t.Warn(msg) + case logger.ERROR: + t.Error(msg) + } +} + +func traceHTTPRequest(req *http.Request, t *tracer) *http.Request { + trace := &httptrace.ClientTrace{ + GetConn: func(hostPort string) { + t.LogField("hostPort", hostPort) + t.LogTiming("getConn") + }, + GotConn: func(info httptrace.GotConnInfo) { + t.LogTiming("gotConn") + t.LogField("reused", strconv.FormatBool(info.Reused)) + t.LogField("idle", strconv.FormatBool(info.WasIdle)) + t.LogDuration("idleTime", info.IdleTime) + t.LogField("localAddr", info.Conn.LocalAddr().String()) + }, + PutIdleConn: func(err error) { + t.LogTiming("putIdleConn") + if err != nil { + t.LogField("putIdleConnectionError", err.Error()) + } + }, + GotFirstResponseByte: func() { + t.LogTiming("gotFirstResponseByte") + }, + Got1xxResponse: func(code int, header textproto.MIMEHeader) error { + t.LogTiming("got1xxResponse") + return nil + }, + DNSStart: func(_ httptrace.DNSStartInfo) { + t.LogTiming("dnsStart") + }, + DNSDone: func(_ httptrace.DNSDoneInfo) { + t.LogTiming("dnsDone") + }, + ConnectStart: func(network, addr string) { + t.LogTiming(fmt.Sprintf("connectStart.%s.%s", network, addr)) + }, + ConnectDone: func(network, addr string, _ error) { + t.LogTiming(fmt.Sprintf("connectDone.%s.%s", network, addr)) + }, + TLSHandshakeStart: func() { + t.LogTiming("tlsHandshakeStart") + }, + TLSHandshakeDone: func(_ tls.ConnectionState, _ error) { + t.LogTiming("tlsHandshakeDone") + }, + WroteHeaders: func() { + t.LogTiming("wroteHeaders") + }, + WroteRequest: func(_ httptrace.WroteRequestInfo) { + t.LogTiming("wroteRequest") + }, + } + + req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace)) + + t.LogField("uri", req.URL.String()) + t.LogField("method", req.Method) + return req +} diff --git a/vendor/github.com/buildkite/agent/v3/version/VERSION b/vendor/github.com/buildkite/agent/v3/version/VERSION index 0f15d1494c..71a2483d30 100644 --- a/vendor/github.com/buildkite/agent/v3/version/VERSION +++ b/vendor/github.com/buildkite/agent/v3/version/VERSION @@ -1 +1 @@ -3.81.0 +3.92.1 diff --git a/vendor/github.com/buildkite/agent/v3/version/version.go b/vendor/github.com/buildkite/agent/v3/version/version.go index d93d5ee0dd..ac515e225a 100644 --- a/vendor/github.com/buildkite/agent/v3/version/version.go +++ b/vendor/github.com/buildkite/agent/v3/version/version.go @@ -38,6 +38,10 @@ func BuildNumber() string { return buildNumber } +func IsDevelopmentBuild() bool { + return buildNumber == "x" +} + // commitInfo returns a string consisting of the commit hash and whether the the build was made in a // `dirty` working directory or not. A dirty working directory is one that has uncommitted changes // to files that git would track. diff --git a/vendor/github.com/buildkite/go-pipeline/README.md b/vendor/github.com/buildkite/go-pipeline/README.md index 96d25a9f06..0d7a10ea24 100644 --- a/vendor/github.com/buildkite/go-pipeline/README.md +++ b/vendor/github.com/buildkite/go-pipeline/README.md @@ -3,7 +3,7 @@ [![Build status](https://badge.buildkite.com/1fad7fb9610283e4955ea4ec4c88faca52162b637fea61821e.svg)](https://buildkite.com/buildkite/go-pipeline) [![Go Reference](https://pkg.go.dev/badge/github.com/buildkite/go-pipeline.svg)](https://pkg.go.dev/github.com/buildkite/go-pipeline) -`go-pipeline` is a Go libary used for building and modifying Buildkite pipelines in golang. It's used internally by the [Buildkite Agent](https://github.com/buildkite/agent) to inspect and sign pipelines prior to uploading them, but is also useful for building tools that generate pipelines. +`go-pipeline` is a Go library used for building and modifying Buildkite pipelines in golang. It's used internally by the [Buildkite Agent](https://github.com/buildkite/agent) to inspect and sign pipelines prior to uploading them, but is also useful for building tools that generate pipelines. ## Installation diff --git a/vendor/github.com/buildkite/go-pipeline/ordered/unmarshal.go b/vendor/github.com/buildkite/go-pipeline/ordered/unmarshal.go index 4358e6a021..d528f348d2 100644 --- a/vendor/github.com/buildkite/go-pipeline/ordered/unmarshal.go +++ b/vendor/github.com/buildkite/go-pipeline/ordered/unmarshal.go @@ -16,6 +16,7 @@ import ( var ( ErrIntoNonPointer = errors.New("cannot unmarshal into non-pointer") ErrIntoNil = errors.New("cannot unmarshal into nil") + ErrNotSettable = errors.New("target value not settable") ErrIncompatibleTypes = errors.New("incompatible types") ErrUnsupportedSrc = errors.New("cannot unmarshal from src") ErrMultipleInlineFields = errors.New(`multiple fields tagged with yaml:",inline"`) @@ -163,10 +164,16 @@ func Unmarshal(src, dst any) error { if sdst.Kind() != reflect.Slice { return fmt.Errorf("%w: cannot unmarshal []any into %T", ErrIncompatibleTypes, dst) } - etype := sdst.Type().Elem() // E = Type of the slice's elements + stype := sdst.Type() // stype = []E = the type of the slice + etype := stype.Elem() // etype = E = Type of the slice's elements + if sdst.IsNil() { + // src isn't nil, so the output slice shouldn't be either. + // Use MakeSlice to preallocate the exact size required. + sdst = reflect.MakeSlice(stype, 0, len(tsrc)) + } var warns []error for i, a := range tsrc { - x := reflect.New(etype) // *E + x := reflect.New(etype) // x := new(E) (type *E) err := Unmarshal(a, x.Interface()) if w := warning.As(err); w != nil { warns = append(warns, w.Wrapf("while unmarshaling item at index %d of %d", i, len(tsrc))) @@ -236,42 +243,63 @@ func (m *Map[K, V]) decodeInto(target any) error { if !ok { return fmt.Errorf("%w: cannot unmarshal from %T, want K=string, V=any", ErrIncompatibleTypes, m) } + // Note: m, and therefore tm, can be nil at this moment. // Work out the kind of target being used. // Dereference the target to find the inner value, if needed. targetValue := reflect.ValueOf(target) - var innerValue reflect.Value switch targetValue.Kind() { case reflect.Pointer: // Passed a pointer to something. + if tm == nil { + if targetValue.IsNil() { + return nil // nothing to do + } + if !targetValue.CanSet() { + return ErrNotSettable + } + targetValue.SetZero() // which is nil + return nil + } if targetValue.IsNil() { return ErrIntoNil } - innerValue = targetValue.Elem() + targetValue = targetValue.Elem() case reflect.Map: - // Passed a map directly. - innerValue = targetValue - if innerValue.IsNil() { - return ErrIntoNil - } + // Continue below. default: return fmt.Errorf("%w: cannot unmarshal %T into %T, want map or *struct{...}", ErrIncompatibleTypes, m, target) } - switch innerValue.Kind() { + switch targetValue.Kind() { case reflect.Map: // Process the map directly. - mapType := innerValue.Type() + mapType := targetValue.Type() // For simplicity, require the key type to be string. if keyType := mapType.Key(); keyType.Kind() != reflect.String { return fmt.Errorf("%w for map key: cannot unmarshal %T into %T", ErrIncompatibleTypes, m, target) } - // If target is a pointer to a nil map (with type), create a new map. - if innerValue.IsNil() { - innerValue.Set(reflect.MakeMapWithSize(mapType, tm.Len())) + // If tm is nil, then set the target to nil. + if tm == nil { + if targetValue.IsNil() { + // Nothing to do. + return nil + } + if !targetValue.CanSet() { + return ErrNotSettable + } + targetValue.SetZero() // which is nil + return nil + } + // Otherwise, if target is a pointer to a nil map (with type), create a new map. + if targetValue.IsNil() { + if !targetValue.CanSet() { + return ErrNotSettable + } + targetValue.Set(reflect.MakeMapWithSize(mapType, tm.Len())) } valueType := mapType.Elem() @@ -285,7 +313,7 @@ func (m *Map[K, V]) decodeInto(target any) error { return fmt.Errorf("unmarshaling value for key %q: %w", k, err) } - innerValue.SetMapIndex(reflect.ValueOf(k), nv.Elem()) + targetValue.SetMapIndex(reflect.ValueOf(k), nv.Elem()) return nil }); err != nil { return err @@ -300,7 +328,7 @@ func (m *Map[K, V]) decodeInto(target any) error { // These are the (accessible by reflection) fields it has. // This includes non-exported fields. - fields := reflect.VisibleFields(innerValue.Type()) + fields := reflect.VisibleFields(targetValue.Type()) var inlineField reflect.StructField outlineKeys := make(map[string]struct{}) @@ -362,7 +390,7 @@ func (m *Map[K, V]) decodeInto(target any) error { // Now load value into the field recursively. // Get a pointer to the field. This works because target is a pointer. - ptrToField := innerValue.FieldByIndex(field.Index).Addr() + ptrToField := targetValue.FieldByIndex(field.Index).Addr() err := Unmarshal(value, ptrToField.Interface()) if w := warning.As(err); w != nil { warns = append(warns, w.Wrapf("while unmarshaling the value for key %q into struct field %q", key, field.Name)) @@ -377,7 +405,7 @@ func (m *Map[K, V]) decodeInto(target any) error { // The rest is handling the ",inline" field. // We support any field that Unmarshal can unmarshal tm into. - inlinePtr := innerValue.FieldByIndex(inlineField.Index).Addr() + inlinePtr := targetValue.FieldByIndex(inlineField.Index).Addr() // Copy all values that weren't non-inline fields into a temporary map. // This is just to avoid mutating tm. diff --git a/vendor/github.com/buildkite/go-pipeline/step_command_matrix.go b/vendor/github.com/buildkite/go-pipeline/step_command_matrix.go index e5e6b62fc7..ba75e74f18 100644 --- a/vendor/github.com/buildkite/go-pipeline/step_command_matrix.go +++ b/vendor/github.com/buildkite/go-pipeline/step_command_matrix.go @@ -147,7 +147,9 @@ func (m *Matrix) validatePermutation(p MatrixPermutation) error { // Check that the dimensions in the permutation are unique and defined in // the matrix setup. for dim := range p { - if len(m.Setup[dim]) == 0 { + // An empty but non-nil setup dimension is valid (all values may be + // given by adjustment tuples). + if m.Setup[dim] == nil { return fmt.Errorf("%w: %q", errPermutationUnknownDimension, dim) } } @@ -180,7 +182,9 @@ func (m *Matrix) validatePermutation(p MatrixPermutation) error { return fmt.Errorf("%w: %d != %d", errAdjustmentLengthMismatch, len(adj.With), len(m.Setup)) } for dim := range adj.With { - if len(m.Setup[dim]) == 0 { + // An empty but non-nil setup dimension is valid (all values may be + // given by adjustment tuples). + if m.Setup[dim] == nil { return fmt.Errorf("%w: %q", errAdjustmentUnknownDimension, dim) } } diff --git a/vendor/github.com/buildkite/interpolate/interpolate.go b/vendor/github.com/buildkite/interpolate/interpolate.go index 7a24fd812a..307956491b 100644 --- a/vendor/github.com/buildkite/interpolate/interpolate.go +++ b/vendor/github.com/buildkite/interpolate/interpolate.go @@ -1,8 +1,8 @@ package interpolate import ( - "bytes" "fmt" + "strings" ) // Interpolate takes a set of environment and interpolates it into the provided string using shell script expansions @@ -28,7 +28,13 @@ func Identifiers(str string) ([]string, error) { // An expansion is something that takes in ENV and returns a string or an error type Expansion interface { + // Expand expands the expansion using variables from env. Expand(env Env) (string, error) + + // Identifiers returns any variable names referenced within the expansion. + // Escaped expansions do something special and return identifiers + // (starting with $) that *would* become referenced after a round of + // unescaping. Identifiers() []string } @@ -84,15 +90,17 @@ func (e UnsetValueExpansion) Expand(env Env) (string, error) { // EscapedExpansion is an expansion that is delayed until later on (usually by a later process) type EscapedExpansion struct { - Identifier string + // PotentialIdentifier is an identifier for the purpose of Identifiers, + // but not for the purpose of Expand. + PotentialIdentifier string } func (e EscapedExpansion) Identifiers() []string { - return []string{"$" + e.Identifier} + return []string{"$" + e.PotentialIdentifier} } func (e EscapedExpansion) Expand(Env) (string, error) { - return "$" + e.Identifier, nil + return "$", nil } // SubstringExpansion returns a substring (or slice) of the env @@ -193,7 +201,7 @@ func (e Expression) Identifiers() []string { } func (e Expression) Expand(env Env) (string, error) { - buf := &bytes.Buffer{} + var buf strings.Builder for _, item := range e { if item.Expansion != nil { @@ -201,9 +209,9 @@ func (e Expression) Expand(env Env) (string, error) { if err != nil { return "", err } - _, _ = buf.WriteString(result) + buf.WriteString(result) } else { - _, _ = buf.WriteString(item.Text) + buf.WriteString(item.Text) } } diff --git a/vendor/github.com/buildkite/interpolate/parser.go b/vendor/github.com/buildkite/interpolate/parser.go index e02cc7d4c4..e28511b23e 100644 --- a/vendor/github.com/buildkite/interpolate/parser.go +++ b/vendor/github.com/buildkite/interpolate/parser.go @@ -87,7 +87,7 @@ func (p *Parser) parseExpression(stop ...rune) (Expression, error) { return nil, err } - expr = append(expr, ee) + expr = append(expr, ExpressionItem{Expansion: ee}) continue } @@ -100,11 +100,12 @@ func (p *Parser) parseExpression(stop ...rune) (Expression, error) { // If we run into a dollar sign and it's not the last char, it's an expansion if c == '$' && p.pos < (len(p.input)-1) { - expansion, err := p.parseExpansion() + expressionItem, err := p.parseExpansion() if err != nil { return nil, err } - expr = append(expr, ExpressionItem{Expansion: expansion}) + + expr = append(expr, expressionItem) continue } @@ -122,47 +123,74 @@ func (p *Parser) parseExpression(stop ...rune) (Expression, error) { return expr, nil } -func (p *Parser) parseEscapedExpansion() (ExpressionItem, error) { +// parseEscapedExpansion attempts to extract a *potential* identifier or brace +// expression from the text following the escaped dollarsign. +func (p *Parser) parseEscapedExpansion() (EscapedExpansion, error) { + // Since it's not an expansion, we should treat the following text as text. + start := p.pos + defer func() { p.pos = start }() + next := p.peekRune() switch { case next == '{': - // if it's an escaped brace expansion, (eg $${MY_COOL_VAR:-5}) consume text until the close brace - id := p.scanUntil(func(r rune) bool { return r == '}' }) - id = id + string(p.nextRune()) // we know that the next rune is a close brace, chuck it on the end - return ExpressionItem{Expansion: EscapedExpansion{Identifier: id}}, nil + // it *could be* an escaped brace expansion + if _, err := p.parseBraceExpansion(); err != nil { + return EscapedExpansion{}, nil + } + // it was! instead of storing the expansion itself, store the string + // that produced it. + return EscapedExpansion{PotentialIdentifier: p.input[start:p.pos]}, nil case unicode.IsLetter(next): - // it's an escaped identifier (eg $$MY_COOL_VAR) + // it *could be* an escaped identifier (eg $$MY_COOL_VAR) id, err := p.scanIdentifier() if err != nil { - return ExpressionItem{}, err + // this should never happen, since scanIdentifier only errors if the + // first rune is not a letter, and we just checked that. + return EscapedExpansion{}, nil } - return ExpressionItem{Expansion: EscapedExpansion{Identifier: id}}, nil + return EscapedExpansion{PotentialIdentifier: id}, nil default: - // there's no identifier or brace afterward, so it's probably a literal escaped dollar sign - // just return a text item with the dollar sign - return ExpressionItem{Text: "$"}, nil + // there's no identifier or brace afterward, so it's probably a literal + // escaped dollar sign + return EscapedExpansion{}, nil } } -func (p *Parser) parseExpansion() (Expansion, error) { +func (p *Parser) parseExpansion() (ExpressionItem, error) { + var empty ExpressionItem + if c := p.nextRune(); c != '$' { - return nil, fmt.Errorf("Expected expansion to start with $, got %c", c) + return empty, fmt.Errorf("Expected expansion to start with $, got %c", c) } + c := p.peekRune() + // if we have an open brace, this is a brace expansion - if c := p.peekRune(); c == '{' { - return p.parseBraceExpansion() + if c == '{' { + expansion, err := p.parseBraceExpansion() + if err != nil { + return empty, err + } + return ExpressionItem{Expansion: expansion}, nil + } + + // if not a letter, it's a literal dollar sign + if !unicode.IsLetter(c) { + return ExpressionItem{Text: "$"}, nil } + // otherwise, it's a variable expansion identifier, err := p.scanIdentifier() if err != nil { - return nil, err + return empty, err } - return VariableExpansion{Identifier: identifier}, nil + return ExpressionItem{Expansion: VariableExpansion{ + Identifier: identifier, + }}, nil } func (p *Parser) parseBraceExpansion() (Expansion, error) { @@ -177,7 +205,9 @@ func (p *Parser) parseBraceExpansion() (Expansion, error) { if c := p.peekRune(); c == '}' { _ = p.nextRune() - return VariableExpansion{Identifier: identifier}, nil + return VariableExpansion{ + Identifier: identifier, + }, nil } var operator string @@ -298,8 +328,8 @@ func (p *Parser) scanIdentifier() (string, error) { if c := p.peekRune(); !unicode.IsLetter(c) { return "", fmt.Errorf("Expected identifier to start with a letter, got %c", c) } - var notIdentifierChar = func(r rune) bool { - return (!unicode.IsLetter(r) && !unicode.IsNumber(r) && r != '_') + notIdentifierChar := func(r rune) bool { + return !(unicode.IsLetter(r) || unicode.IsNumber(r) || r == '_') } return p.scanUntil(notIdentifierChar), nil } diff --git a/vendor/github.com/buildkite/roko/retrier.go b/vendor/github.com/buildkite/roko/retrier.go index 2c6f9333f7..17213ab43d 100644 --- a/vendor/github.com/buildkite/roko/retrier.go +++ b/vendor/github.com/buildkite/roko/retrier.go @@ -10,12 +10,13 @@ import ( var defaultRandom = rand.New(rand.NewSource(time.Now().UnixNano())) -const jitterInterval = 1000 * time.Millisecond +const defaultJitterInterval = 1000 * time.Millisecond type Retrier struct { maxAttempts int attemptCount int jitter bool + jitterRange jitterRange forever bool rand *rand.Rand @@ -24,9 +25,11 @@ type Retrier struct { intervalCalculator Strategy strategyType string - manualInterval *time.Duration + nextInterval time.Duration } +type jitterRange struct{ min, max time.Duration } + type Strategy func(*Retrier) time.Duration const ( @@ -119,6 +122,26 @@ func WithStrategy(strategy Strategy, strategyType string) retrierOpt { func WithJitter() retrierOpt { return func(r *Retrier) { r.jitter = true + r.jitterRange = jitterRange{min: 0, max: defaultJitterInterval} + } +} + +// WithJitterRange enables jitter as [WithJitter] does, but allows the user to specify the range of the jitter as a +// half-open range [min, max) of time.Duration values. The jitter will be a random value in the range [min, max) added +// to the interval calculated by the retry strategy. The jitter will be recalculated for each retry. Both min and max may +// be negative, but min must be less than max. min and max may both be zero, which is equivalent to disabling jitter. +// If a negative jitter causes a negative interval, the interval will be clamped to zero. +func WithJitterRange(min, max time.Duration) retrierOpt { + if min >= max { + panic("min must be less than max") + } + + return func(r *Retrier) { + r.jitter = true + r.jitterRange = jitterRange{ + min: min, + max: max, + } } } @@ -161,7 +184,7 @@ func NewRetrier(opts ...retrierOpt) *Retrier { oldJitter := r.jitter r.jitter = false // Temporarily turn off jitter while we check if the interval is 0 - if r.forever && r.strategyType == constantStrategy && r.NextInterval() == 0 { + if r.forever && r.strategyType == constantStrategy && r.intervalCalculator(r) == 0 { panic("retriers using the constant strategy that run forever must have an interval") } r.jitter = oldJitter // and now set it back to what it was previously @@ -169,12 +192,16 @@ func NewRetrier(opts ...retrierOpt) *Retrier { return r } -// Jitter returns a duration in the interval (0, 1] s if jitter is enabled, or 0 s if it's not +// Jitter returns a duration in the interval in the range [0, r.jitterRange.max - r.jitterRange.min). When no jitter range +// is defined, the default range is [0, 1 second). The jitter is recalculated for each retry. +// If jitter is disabled, this method will always return 0. func (r *Retrier) Jitter() time.Duration { if !r.jitter { return 0 } - return time.Duration((1.0 - r.rand.Float64()) * float64(jitterInterval)) + + min, max := float64(r.jitterRange.min), float64(r.jitterRange.max) + return time.Duration(min + (max-min)*rand.Float64()) } // MarkAttempt increments the attempt count for the retrier. This affects ShouldGiveUp, and also affects the retry interval @@ -190,7 +217,7 @@ func (r *Retrier) Break() { // SetNextInterval overrides the strategy for the interval before the next try func (r *Retrier) SetNextInterval(d time.Duration) { - r.manualInterval = &d + r.nextInterval = d } // ShouldGiveUp returns whether the retrier should stop trying do do the thing it's been asked to do @@ -208,14 +235,9 @@ func (r *Retrier) ShouldGiveUp() bool { return r.attemptCount >= r.maxAttempts } -// NextInterval returns the next interval that the retrier will use. Behind the scenes, it calls the function generated -// by either retrier's strategy +// NextInterval returns the length of time that the retrier will wait before the next retry func (r *Retrier) NextInterval() time.Duration { - if r.manualInterval != nil { - return *r.manualInterval - } - - return r.intervalCalculator(r) + return r.nextInterval } func (r *Retrier) String() string { @@ -231,9 +253,8 @@ func (r *Retrier) String() string { return str } - nextInterval := r.NextInterval() - if nextInterval > 0 { - str = str + fmt.Sprintf(" Retrying in %s", nextInterval) + if r.nextInterval > 0 { + str = str + fmt.Sprintf(" Retrying in %s", r.nextInterval) } else { str = str + " Retrying immediately" } @@ -255,21 +276,16 @@ func (r *Retrier) Do(callback func(*Retrier) error) error { // DoWithContext is a context-aware variant of Do. func (r *Retrier) DoWithContext(ctx context.Context, callback func(*Retrier) error) error { for { + // Calculate the next interval before we do work - this way, the calls to r.NextInterval() in the callback will be + // accurate and include the calculated jitter, if present + r.nextInterval = r.intervalCalculator(r) + // Perform the action the user has requested we retry err := callback(r) if err == nil { return nil } - // Calculate the next interval before we increment the attempt count - // In the exponential case, if we didn't do this, we'd skip the first interval - // ie, we would wait 2^1, 2^2, 2^3, ..., 2^n+1 seconds (bad) - // instead of 2^0, 2^1, 2^2, ..., 2^n seconds (good) - nextInterval := r.NextInterval() - - // Reset the manualInterval now that the nextInterval has been acquired. - r.manualInterval = nil - r.MarkAttempt() // If the last callback called r.Break(), or if we've hit our call limit, bail out and return the last error we got @@ -277,7 +293,7 @@ func (r *Retrier) DoWithContext(ctx context.Context, callback func(*Retrier) err return err } - if err := r.sleepOrDone(ctx, nextInterval); err != nil { + if err := r.sleepOrDone(ctx, r.nextInterval); err != nil { return err } } diff --git a/vendor/github.com/emicklei/proto/CHANGES.md b/vendor/github.com/emicklei/proto/CHANGES.md index a55dc66cd7..d586b94230 100644 --- a/vendor/github.com/emicklei/proto/CHANGES.md +++ b/vendor/github.com/emicklei/proto/CHANGES.md @@ -1,3 +1,28 @@ +## v1.13.4 (2024-12-17) + +- fixed handling identifiers known as numbers by scanner (PR #146) + +## v1.13.3 (2024-12-04) + +- fixed inline comment in option (#143) + +## v1.13.2 (2024-01-24) + +- allow keyword as field name (such as message,service, etc) + +## v1.13.1 (2024-01-24) + +- allow embedded comment in between normal field parts (#131) + +## v1.13.0 (2023-12-09) + +- walk options in Enum fields (#140) + +## v1.12.2 (2023-11-02) + +- allow comments in array of literals of option (#138) +- adds Comment field in Literal + ## v1.12.1 (2023-07-18) - add IsDeprecated on EnumField diff --git a/vendor/github.com/emicklei/proto/README.md b/vendor/github.com/emicklei/proto/README.md index 0986d34dd5..c99a320b85 100644 --- a/vendor/github.com/emicklei/proto/README.md +++ b/vendor/github.com/emicklei/proto/README.md @@ -1,6 +1,5 @@ # proto -[![Build Status](https://api.travis-ci.com/emicklei/proto.svg?branch=master)](https://travis-ci.com/github/emicklei/proto) [![Go Report Card](https://goreportcard.com/badge/github.com/emicklei/proto)](https://goreportcard.com/report/github.com/emicklei/proto) [![GoDoc](https://pkg.go.dev/badge/github.com/emicklei/proto)](https://pkg.go.dev/github.com/emicklei/proto) [![codecov](https://codecov.io/gh/emicklei/proto/branch/master/graph/badge.svg)](https://codecov.io/gh/emicklei/proto) diff --git a/vendor/github.com/emicklei/proto/enum.go b/vendor/github.com/emicklei/proto/enum.go index 649bbd2b99..745698fedd 100644 --- a/vendor/github.com/emicklei/proto/enum.go +++ b/vendor/github.com/emicklei/proto/enum.go @@ -140,6 +140,18 @@ type EnumField struct { Parent Visitee } +// elements is part of elementContainer +func (f *EnumField) elements() []Visitee { + return f.Elements +} + +// takeLastComment is part of elementContainer +// removes and returns the last element of the list if it is a Comment. +func (f *EnumField) takeLastComment(expectedOnLine int) (last *Comment) { + last, f.Elements = takeLastCommentIfEndsOnLine(f.Elements, expectedOnLine) + return +} + // Accept dispatches the call to the visitor. func (f *EnumField) Accept(v Visitor) { v.VisitEnumField(f) diff --git a/vendor/github.com/emicklei/proto/field.go b/vendor/github.com/emicklei/proto/field.go index 50cfa051f6..11e7dd00bf 100644 --- a/vendor/github.com/emicklei/proto/field.go +++ b/vendor/github.com/emicklei/proto/field.go @@ -68,8 +68,15 @@ func (f *NormalField) Doc() *Comment { // [ "repeated" | "optional" ] type fieldName "=" fieldNumber [ "[" fieldOptions "]" ] ";" func (f *NormalField) parse(p *Parser) error { for { - _, tok, lit := p.nextTypeName() + pos, tok, lit := p.nextTypeName() switch tok { + case tCOMMENT: + c := newComment(pos, lit) + if f.InlineComment == nil { + f.InlineComment = c + } else { + f.InlineComment.Merge(c) + } case tREPEATED: f.Repeated = true return f.parse(p) @@ -90,24 +97,56 @@ done: // parseFieldAfterType expects: // fieldName "=" fieldNumber [ "[" fieldOptions "]" ] "; func parseFieldAfterType(f *Field, p *Parser, parent Visitee) error { - pos, tok, lit := p.next() - if tok != tIDENT { - if !isKeyword(tok) { - return p.unexpected(lit, "field identifier", f) + expectedToken := tIDENT + expected := "field identifier" + + for { + pos, tok, lit := p.next() + if tok == tCOMMENT { + c := newComment(pos, lit) + if f.InlineComment == nil { + f.InlineComment = c + } else { + f.InlineComment.Merge(c) + } + continue + } + if tok != expectedToken { + // allow keyword as field name + if expectedToken == tIDENT && isKeyword(tok) { + // continue as identifier + tok = tIDENT + } else { + return p.unexpected(lit, expected, f) + } + } + // found expected token + if tok == tIDENT { + f.Name = lit + expectedToken = tEQUALS + expected = "field =" + continue + } + if tok == tEQUALS { + expectedToken = tNUMBER + expected = "field sequence number" + continue + } + if tok == tNUMBER { + // put it back so we can use the generic nextInteger + p.nextPut(pos, tok, lit) + i, err := p.nextInteger() + if err != nil { + return p.unexpected(lit, expected, f) + } + f.Sequence = i + break } } - f.Name = lit - pos, tok, lit = p.next() - if tok != tEQUALS { - return p.unexpected(lit, "field =", f) - } - i, err := p.nextInteger() - if err != nil { - return p.unexpected(lit, "field sequence number", f) - } - f.Sequence = i + consumeFieldComments(f, p) + // see if there are options - pos, tok, _ = p.next() + pos, tok, lit := p.next() if tLEFTSQUARE != tok { p.nextPut(pos, tok, lit) return nil @@ -135,6 +174,37 @@ func parseFieldAfterType(f *Field, p *Parser, parent Visitee) error { return nil } +func consumeFieldComments(f *Field, p *Parser) { + pos, tok, lit := p.next() + for tok == tCOMMENT { + c := newComment(pos, lit) + if f.InlineComment == nil { + f.InlineComment = c + } else { + f.InlineComment.Merge(c) + } + pos, tok, lit = p.next() + } + // no longer a comment, put it back + p.nextPut(pos, tok, lit) +} + +// TODO copy paste +func consumeOptionComments(o *Option, p *Parser) { + pos, tok, lit := p.next() + for tok == tCOMMENT { + c := newComment(pos, lit) + if o.Comment == nil { + o.Comment = c + } else { + o.Comment.Merge(c) + } + pos, tok, lit = p.next() + } + // no longer a comment, put it back + p.nextPut(pos, tok, lit) +} + // MapField represents a map entry in a message. type MapField struct { *Field diff --git a/vendor/github.com/emicklei/proto/option.go b/vendor/github.com/emicklei/proto/option.go index 0351f01904..65897b888c 100644 --- a/vendor/github.com/emicklei/proto/option.go +++ b/vendor/github.com/emicklei/proto/option.go @@ -44,8 +44,9 @@ type Option struct { } // parse reads an Option body -// ( ident | "(" fullIdent ")" ) { "." ident } "=" constant ";" +// ( ident | //... | "(" fullIdent ")" ) { "." ident } "=" constant ";" func (o *Option) parse(p *Parser) error { + consumeOptionComments(o, p) pos, tok, lit := p.nextIdentifier() if tLEFTPAREN == tok { pos, tok, lit = p.nextIdentifier() @@ -60,15 +61,6 @@ func (o *Option) parse(p *Parser) error { } o.Name = fmt.Sprintf("(%s)", lit) } else { - if tCOMMENT == tok { - nc := newComment(pos, lit) - if o.Comment != nil { - o.Comment.Merge(nc) - } else { - o.Comment = nc - } - return o.parse(p) - } // non full ident if tIDENT != tok { if !isKeyword(tok) { @@ -111,6 +103,7 @@ func (o *Option) parse(p *Parser) error { o.Constant = *l } }) + consumeOptionComments(o, p) return err } @@ -135,6 +128,10 @@ type Literal struct { Source string IsString bool + // It not nil then the entry is actually a comment with line(s) + // modelled this way because Literal is not an elementContainer + Comment *Comment + // The rune use to delimit the string value (only valid iff IsString) QuoteRune rune @@ -191,6 +188,17 @@ func (l Literal) SourceRepresentation() string { // parse expects to read a literal constant after =. func (l *Literal) parse(p *Parser) error { pos, tok, lit := p.next() + // handle special element inside literal, a comment line + if isComment(lit) { + nc := newComment(pos, lit) + if l.Comment == nil { + l.Comment = nc + } else { + l.Comment.Merge(nc) + } + // continue with remaining entries + return l.parse(p) + } if tok == tLEFTSQUARE { // collect array elements array := []*Literal{} @@ -198,14 +206,13 @@ func (l *Literal) parse(p *Parser) error { // if it's an empty array, consume the close bracket, set the Array to // an empty array, and return r := p.peekNonWhitespace() - if ']' == r { + if r == ']' { pos, _, _ := p.next() l.Array = array l.IsString = false l.Position = pos return nil } - for { e := new(Literal) if err := e.parse(p); err != nil { @@ -324,12 +331,12 @@ func (b byPosition) Swap(i, j int) { b[i], b[j] = b[j], b[i] } func parseAggregateConstants(p *Parser, container interface{}) (list []*NamedLiteral, err error) { for { - pos, tok, lit := p.nextIdentifier() - if tRIGHTSQUARE == tok { - p.nextPut(pos, tok, lit) - // caller has checked for open square ; will consume rightsquare, rightcurly and semicolon - return - } + _, tok, lit := p.nextMessageLiteralFieldName() + // if tRIGHTSQUARE == tok { + // p.nextPut(pos, tok, lit) + // // caller has checked for open square ; will consume rightsquare, rightcurly and semicolon + // return + // } if tRIGHTCURLY == tok { return } @@ -364,7 +371,7 @@ func parseAggregateConstants(p *Parser, container interface{}) (list []*NamedLit key := lit printsColon := false // expect colon, aggregate or plain literal - pos, tok, lit = p.next() + pos, tok, lit := p.next() if tCOLON == tok { // consume it printsColon = true diff --git a/vendor/github.com/emicklei/proto/parser.go b/vendor/github.com/emicklei/proto/parser.go index 8334e6c93e..0f338ee183 100644 --- a/vendor/github.com/emicklei/proto/parser.go +++ b/vendor/github.com/emicklei/proto/parser.go @@ -190,7 +190,7 @@ func (p *Parser) nextInteger() (i int, err error) { i, err = p.nextInteger() return i * -1, err } - if tok != tIDENT { + if tok != tNUMBER { return 0, errors.New("non integer") } if strings.HasPrefix(lit, "0x") || strings.HasPrefix(lit, "0X") { @@ -213,6 +213,15 @@ func (p *Parser) nextIdentifier() (pos scanner.Position, tok token, lit string) return } +func (p *Parser) nextMessageLiteralFieldName() (pos scanner.Position, tok token, lit string) { + pos, tok, lit = p.nextIdent(true) + if tok == tLEFTSQUARE { + pos, tok, lit = p.nextIdent(true) + _, _, _ = p.next() // consume right square + } + return +} + // nextTypeName implements the Packages and Name Resolution for finding the name of the type. // Valid examples: // .google.protobuf.Empty diff --git a/vendor/github.com/emicklei/proto/token.go b/vendor/github.com/emicklei/proto/token.go index 26fe70a033..d1f59c9752 100644 --- a/vendor/github.com/emicklei/proto/token.go +++ b/vendor/github.com/emicklei/proto/token.go @@ -24,6 +24,7 @@ package proto import ( + "strconv" "strings" ) @@ -78,6 +79,9 @@ const ( tENUM tSTREAM + // numbers (pos or neg, float) + tNUMBER + // BEGIN proto2 tOPTIONAL tGROUP @@ -119,6 +123,18 @@ func isComment(lit string) bool { return strings.HasPrefix(lit, "//") || strings.HasPrefix(lit, "/*") } +func isNumber(lit string) bool { + if lit == "NaN" || lit == "nan" || lit == "Inf" || lit == "Infinity" || lit == "inf" || lit == "infinity" { + return false + } + if strings.HasPrefix(lit, "0x") || strings.HasPrefix(lit, "0X") { + _, err := strconv.ParseInt(lit, 0, 64) + return err == nil + } + _, err := strconv.ParseFloat(lit, 64) + return err == nil +} + const doubleQuoteRune = rune('"') // unQuote removes one matching leading and trailing single or double quote. @@ -220,6 +236,9 @@ func asToken(literal string) token { return tREQUIRED default: // special cases + if isNumber(literal) { + return tNUMBER + } if isComment(literal) { return tCOMMENT } diff --git a/vendor/github.com/go-jose/go-jose/v3/cryptosigner/cryptosigner.go b/vendor/github.com/go-jose/go-jose/v3/cryptosigner/cryptosigner.go deleted file mode 100644 index ddad5c96d5..0000000000 --- a/vendor/github.com/go-jose/go-jose/v3/cryptosigner/cryptosigner.go +++ /dev/null @@ -1,147 +0,0 @@ -/*- - * Copyright 2018 Square Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Package cryptosigner implements an OpaqueSigner that wraps a "crypto".Signer -// -// https://godoc.org/crypto#Signer -package cryptosigner - -import ( - "crypto" - "crypto/ecdsa" - "crypto/ed25519" - "crypto/elliptic" - "crypto/rand" - "crypto/rsa" - "encoding/asn1" - "io" - "math/big" - - "github.com/go-jose/go-jose/v3" -) - -// Opaque creates an OpaqueSigner from a "crypto".Signer -func Opaque(s crypto.Signer) jose.OpaqueSigner { - pk := &jose.JSONWebKey{ - Key: s.Public(), - } - return &cryptoSigner{signer: s, rand: rand.Reader, pk: pk} -} - -type cryptoSigner struct { - pk *jose.JSONWebKey - signer crypto.Signer - rand io.Reader -} - -func (s *cryptoSigner) Public() *jose.JSONWebKey { - return s.pk -} - -func (s *cryptoSigner) Algs() []jose.SignatureAlgorithm { - switch key := s.signer.Public().(type) { - case ed25519.PublicKey: - return []jose.SignatureAlgorithm{jose.EdDSA} - case *ecdsa.PublicKey: - switch key.Curve { - case elliptic.P256(): - return []jose.SignatureAlgorithm{jose.ES256} - case elliptic.P384(): - return []jose.SignatureAlgorithm{jose.ES384} - case elliptic.P521(): - return []jose.SignatureAlgorithm{jose.ES512} - default: - return nil - } - case *rsa.PublicKey: - return []jose.SignatureAlgorithm{jose.RS256, jose.RS384, jose.RS512, jose.PS256, jose.PS384, jose.PS512} - default: - return nil - } -} - -func (s *cryptoSigner) SignPayload(payload []byte, alg jose.SignatureAlgorithm) ([]byte, error) { - var hash crypto.Hash - switch alg { - case jose.EdDSA: - case jose.RS256, jose.PS256, jose.ES256: - hash = crypto.SHA256 - case jose.RS384, jose.PS384, jose.ES384: - hash = crypto.SHA384 - case jose.RS512, jose.PS512, jose.ES512: - hash = crypto.SHA512 - default: - return nil, jose.ErrUnsupportedAlgorithm - } - - var hashed []byte - if hash != crypto.Hash(0) { - hasher := hash.New() - if _, err := hasher.Write(payload); err != nil { - return nil, err - } - hashed = hasher.Sum(nil) - } - - var ( - out []byte - err error - ) - switch alg { - case jose.EdDSA: - out, err = s.signer.Sign(s.rand, payload, crypto.Hash(0)) - case jose.ES256, jose.ES384, jose.ES512: - var byteLen int - switch alg { - case jose.ES256: - byteLen = 32 - case jose.ES384: - byteLen = 48 - case jose.ES512: - byteLen = 66 - } - var b []byte - b, err = s.signer.Sign(s.rand, hashed, hash) - if err != nil { - return nil, err - } - - sig := struct { - R, S *big.Int - }{} - if _, err = asn1.Unmarshal(b, &sig); err != nil { - return nil, err - } - - rBytes := sig.R.Bytes() - out = make([]byte, byteLen) - copy(out[byteLen-len(rBytes):], rBytes) - - sBytes := sig.S.Bytes() - sBytesPadded := make([]byte, byteLen) - copy(sBytesPadded[byteLen-len(sBytes):], sBytes) - - out = append(out, sBytesPadded...) - case jose.RS256, jose.RS384, jose.RS512: - out, err = s.signer.Sign(s.rand, hashed, hash) - case jose.PS256, jose.PS384, jose.PS512: - out, err = s.signer.Sign(s.rand, hashed, &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - Hash: hash, - }) - } - return out, err -} diff --git a/vendor/github.com/go-piv/piv-go/third_party/rsa/LICENSE b/vendor/github.com/go-piv/piv-go/third_party/rsa/LICENSE deleted file mode 100644 index 6a66aea5ea..0000000000 --- a/vendor/github.com/go-piv/piv-go/third_party/rsa/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/go-piv/piv-go/LICENSE b/vendor/github.com/go-piv/piv-go/v2/LICENSE similarity index 100% rename from vendor/github.com/go-piv/piv-go/LICENSE rename to vendor/github.com/go-piv/piv-go/v2/LICENSE diff --git a/vendor/github.com/go-piv/piv-go/piv/doc.go b/vendor/github.com/go-piv/piv-go/v2/piv/doc.go similarity index 100% rename from vendor/github.com/go-piv/piv-go/piv/doc.go rename to vendor/github.com/go-piv/piv-go/v2/piv/doc.go diff --git a/vendor/github.com/go-piv/piv-go/piv/key.go b/vendor/github.com/go-piv/piv-go/v2/piv/key.go similarity index 80% rename from vendor/github.com/go-piv/piv-go/piv/key.go rename to vendor/github.com/go-piv/piv-go/v2/piv/key.go index 5b8bc072c5..177d6aed8c 100644 --- a/vendor/github.com/go-piv/piv-go/piv/key.go +++ b/vendor/github.com/go-piv/piv-go/v2/piv/key.go @@ -17,6 +17,7 @@ package piv import ( "bytes" "crypto" + "crypto/ecdh" "crypto/ecdsa" "crypto/ed25519" "crypto/elliptic" @@ -32,7 +33,7 @@ import ( "strconv" "strings" - rsafork "github.com/go-piv/piv-go/third_party/rsa" + rsafork "github.com/go-piv/piv-go/v2/third_party/rsa" ) // errMismatchingAlgorithms is returned when a cryptographic operation @@ -205,15 +206,26 @@ func (a *Attestation) addExt(e pkix.Extension) error { // YubiKey certificate chains up to the Yubico CA, parsing additional information // out of the slot certificate, such as the touch and PIN policies of a key. func Verify(attestationCert, slotCert *x509.Certificate) (*Attestation, error) { - var v verifier + var v Verifier return v.Verify(attestationCert, slotCert) } -type verifier struct { +// Verifier allows specifying options when verifying attestations produced by +// YubiKeys. +type Verifier struct { + // Root certificates to use to validate challenges. If nil, this defaults to Yubico's + // CA bundle. + // + // https://developers.yubico.com/PIV/Introduction/PIV_attestation.html + // https://developers.yubico.com/PIV/Introduction/piv-attestation-ca.pem + // https://developers.yubico.com/U2F/yubico-u2f-ca-certs.txt Roots *x509.CertPool } -func (v *verifier) Verify(attestationCert, slotCert *x509.Certificate) (*Attestation, error) { +// Verify proves that a key was generated on a YubiKey. +// +// As opposed to the package level [Verify], it uses any options enabled on the [Verifier]. +func (v *Verifier) Verify(attestationCert, slotCert *x509.Certificate) (*Attestation, error) { o := x509.VerifyOptions{KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny}} o.Roots = v.Roots if o.Roots == nil { @@ -404,11 +416,11 @@ var retiredKeyManagementSlots = map[uint32]Slot{ // RetiredKeyManagementSlot provides access to "retired" slots. Slots meant for old Key Management // keys that have been rotated. YubiKeys 4 and later support values between 0x82 and 0x95 (inclusive). // -// slot, ok := RetiredKeyManagementSlot(0x82) -// if !ok { -// // unrecognized slot -// } -// pub, err := yk.GenerateKey(managementKey, slot, key) +// slot, ok := RetiredKeyManagementSlot(0x82) +// if !ok { +// // unrecognized slot +// } +// pub, err := yk.GenerateKey(managementKey, slot, key) // // https://developers.yubico.com/PIV/Introduction/Certificate_slots.html#_slot_82_95_retired_key_management func RetiredKeyManagementSlot(key uint32) (Slot, bool) { @@ -428,8 +440,6 @@ type Algorithm int // Algorithms supported by this package. Note that not all cards will support // every algorithm. // -// AlgorithmEd25519 is currently only implemented by SoloKeys. -// // For algorithm discovery, see: https://github.com/ericchiang/piv-go/issues/1 const ( AlgorithmEC256 Algorithm = iota + 1 @@ -437,6 +447,9 @@ const ( AlgorithmEd25519 AlgorithmRSA1024 AlgorithmRSA2048 + AlgorithmRSA3072 + AlgorithmRSA4096 + AlgorithmX25519 ) // PINPolicy represents PIN requirements when signing or decrypting with an @@ -465,6 +478,16 @@ const ( TouchPolicyCached ) +// Origin represents whether a key was generated on the hardware, or has been +// imported into it. +type Origin int + +// Origins supported by this package. +const ( + OriginGenerated Origin = iota + 1 + OriginImported +) + const ( tagPINPolicy = 0xaa tagTouchPolicy = 0xab @@ -476,18 +499,54 @@ var pinPolicyMap = map[PINPolicy]byte{ PINPolicyAlways: 0x03, } +var pinPolicyMapInv = map[byte]PINPolicy{ + 0x01: PINPolicyNever, + 0x02: PINPolicyOnce, + 0x03: PINPolicyAlways, +} + var touchPolicyMap = map[TouchPolicy]byte{ TouchPolicyNever: 0x01, TouchPolicyAlways: 0x02, TouchPolicyCached: 0x03, } +var touchPolicyMapInv = map[byte]TouchPolicy{ + 0x01: TouchPolicyNever, + 0x02: TouchPolicyAlways, + 0x03: TouchPolicyCached, +} + +var originMap = map[Origin]byte{ + OriginGenerated: 0x01, + OriginImported: 0x02, +} + +var originMapInv = map[byte]Origin{ + 0x01: OriginGenerated, + 0x02: OriginImported, +} + var algorithmsMap = map[Algorithm]byte{ AlgorithmEC256: algECCP256, AlgorithmEC384: algECCP384, AlgorithmEd25519: algEd25519, AlgorithmRSA1024: algRSA1024, AlgorithmRSA2048: algRSA2048, + AlgorithmRSA3072: algRSA3072, + AlgorithmRSA4096: algRSA4096, + AlgorithmX25519: algX25519, +} + +var algorithmsMapInv = map[byte]Algorithm{ + algECCP256: AlgorithmEC256, + algECCP384: AlgorithmEC384, + algEd25519: AlgorithmEd25519, + algRSA1024: AlgorithmRSA1024, + algRSA2048: AlgorithmRSA2048, + algRSA3072: AlgorithmRSA3072, + algRSA4096: AlgorithmRSA4096, + algX25519: AlgorithmX25519, } // AttestationCertificate returns the YubiKey's attestation certificate, which @@ -543,6 +602,92 @@ func ykAttest(tx *scTx, slot Slot) (*x509.Certificate, error) { return cert, nil } +// KeyInfo holds unprotected metadata about a key slot. +type KeyInfo struct { + Algorithm Algorithm + PINPolicy PINPolicy + TouchPolicy TouchPolicy + Origin Origin + PublicKey crypto.PublicKey +} + +func (ki *KeyInfo) unmarshal(b []byte) error { + for len(b) > 0 { + var v asn1.RawValue + rest, err := asn1.Unmarshal(b, &v) + if err != nil { + return err + } + b = rest + if v.Class != 0 || v.IsCompound { + continue + } + var ok bool + switch v.Tag { + case 1: + if len(v.Bytes) != 1 { + return errors.New("invalid algorithm in response") + } + if ki.Algorithm, ok = algorithmsMapInv[v.Bytes[0]]; !ok { + return errors.New("unknown algorithm in response") + } + case 2: + if len(v.Bytes) != 2 { + return errors.New("invalid policy in response") + } + if ki.PINPolicy, ok = pinPolicyMapInv[v.Bytes[0]]; !ok { + return errors.New("unknown PIN policy in response") + } + if ki.TouchPolicy, ok = touchPolicyMapInv[v.Bytes[1]]; !ok { + return errors.New("unknown touch policy in response") + } + case 3: + if len(v.Bytes) != 1 { + return errors.New("invalid origin in response") + } + if ki.Origin, ok = originMapInv[v.Bytes[0]]; !ok { + return errors.New("unknown origin in response") + } + case 4: + ki.PublicKey, err = decodePublic(v.Bytes, ki.Algorithm) + if err != nil { + return fmt.Errorf("parse public key: %w", err) + } + default: + // TODO: According to the Yubico website, we get two more fields, + // if we pass 0x80 or 0x81 as slots: + // 1. Default value (for PIN/PUK and management key): Whether the + // default value is used. + // 2. Retries (for PIN/PUK): The number of retries remaining + // However, it seems the reference implementation does not expect + // these and can not parse them out: + // https://github.com/Yubico/yubico-piv-tool/blob/yubico-piv-tool-2.3.1/lib/util.c#L1529 + // For now, we just ignore them. + } + } + return nil +} + +// KeyInfo returns public information about the given key slot. It is only +// supported by YubiKeys with a version >= 5.3.0. +func (yk *YubiKey) KeyInfo(slot Slot) (KeyInfo, error) { + // https://developers.yubico.com/PIV/Introduction/Yubico_extensions.html#_get_metadata + cmd := apdu{ + instruction: insGetMetadata, + param1: 0x00, + param2: byte(slot.Key), + } + resp, err := yk.tx.Transmit(cmd) + if err != nil { + return KeyInfo{}, fmt.Errorf("command failed: %w", err) + } + var ki KeyInfo + if err := ki.unmarshal(resp); err != nil { + return KeyInfo{}, err + } + return ki, nil +} + // Certificate returns the certifiate object stored in a given slot. // // If a certificate hasn't been set in the provided slot, the returned error @@ -606,8 +751,8 @@ func marshalASN1(tag byte, data []byte) []byte { // SetCertificate stores a certificate object in the provided slot. Setting a // certificate isn't required to use the associated key for signing or // decryption. -func (yk *YubiKey) SetCertificate(key [24]byte, slot Slot, cert *x509.Certificate) error { - if err := ykAuthenticate(yk.tx, key, yk.rand); err != nil { +func (yk *YubiKey) SetCertificate(key []byte, slot Slot, cert *x509.Certificate) error { + if err := ykAuthenticate(yk.tx, key, yk.rand, yk.version); err != nil { return fmt.Errorf("authenticating with management key: %w", err) } return ykStoreCertificate(yk.tx, slot, cert) @@ -660,8 +805,8 @@ type Key struct { // GenerateKey generates an asymmetric key on the card, returning the key's // public key. -func (yk *YubiKey) GenerateKey(key [24]byte, slot Slot, opts Key) (crypto.PublicKey, error) { - if err := ykAuthenticate(yk.tx, key, yk.rand); err != nil { +func (yk *YubiKey) GenerateKey(key []byte, slot Slot, opts Key) (crypto.PublicKey, error) { + if err := ykAuthenticate(yk.tx, key, yk.rand, yk.version); err != nil { return nil, fmt.Errorf("authenticating with management key: %w", err) } return ykGenerateKey(yk.tx, slot, opts) @@ -671,7 +816,6 @@ func ykGenerateKey(tx *scTx, slot Slot, o Key) (crypto.PublicKey, error) { alg, ok := algorithmsMap[o.Algorithm] if !ok { return nil, fmt.Errorf("unsupported algorithm") - } tp, ok := touchPolicyMap[o.TouchPolicy] if !ok { @@ -698,10 +842,20 @@ func ykGenerateKey(tx *scTx, slot Slot, o Key) (crypto.PublicKey, error) { return nil, fmt.Errorf("command failed: %w", err) } + // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf#page=95 + obj, _, err := unmarshalASN1(resp, 1, 0x49) + if err != nil { + return nil, fmt.Errorf("unmarshal response: %v", err) + } + + return decodePublic(obj, o.Algorithm) +} + +func decodePublic(b []byte, alg Algorithm) (crypto.PublicKey, error) { var curve elliptic.Curve - switch o.Algorithm { - case AlgorithmRSA1024, AlgorithmRSA2048: - pub, err := decodeRSAPublic(resp) + switch alg { + case AlgorithmRSA1024, AlgorithmRSA2048, AlgorithmRSA3072, AlgorithmRSA4096: + pub, err := decodeRSAPublic(b) if err != nil { return nil, fmt.Errorf("decoding rsa public key: %v", err) } @@ -711,15 +865,21 @@ func ykGenerateKey(tx *scTx, slot Slot, o Key) (crypto.PublicKey, error) { case AlgorithmEC384: curve = elliptic.P384() case AlgorithmEd25519: - pub, err := decodeEd25519Public(resp) + pub, err := decodeEd25519Public(b) if err != nil { return nil, fmt.Errorf("decoding ed25519 public key: %v", err) } return pub, nil + case AlgorithmX25519: + pub, err := decodeX25519Public(b) + if err != nil { + return nil, fmt.Errorf("decoding X25519 public key: %v", err) + } + return pub, nil default: return nil, fmt.Errorf("unsupported algorithm") } - pub, err := decodeECPublic(resp, curve) + pub, err := decodeECPublic(b, curve) if err != nil { return nil, fmt.Errorf("decoding ec public key: %v", err) } @@ -780,6 +940,13 @@ func (k KeyAuth) do(yk *YubiKey, pp PINPolicy, f func(tx *scTx) ([]byte, error)) } func pinPolicy(yk *YubiKey, slot Slot) (PINPolicy, error) { + if supportsVersion(yk.version, 5, 3, 0) { + info, err := yk.KeyInfo(slot) + if err != nil { + return 0, fmt.Errorf("get key info: %v", err) + } + return info.PINPolicy, nil + } cert, err := yk.Attest(slot) if err != nil { var e *apduErr @@ -809,12 +976,11 @@ func pinPolicy(yk *YubiKey, slot Slot) (PINPolicy, error) { // If the public key hasn't been stored externally, it can be provided by // fetching the slot's attestation certificate: // -// cert, err := yk.Attest(slot) -// if err != nil { -// // ... -// } -// priv, err := yk.PrivateKey(slot, cert.PublicKey, auth) -// +// cert, err := yk.Attest(slot) +// if err != nil { +// // ... +// } +// priv, err := yk.PrivateKey(slot, cert.PublicKey, auth) func (yk *YubiKey) PrivateKey(slot Slot, public crypto.PublicKey, auth KeyAuth) (crypto.PrivateKey, error) { pp := PINPolicyNever if _, ok := pinPolicyMap[auth.PINPolicy]; ok { @@ -838,6 +1004,11 @@ func (yk *YubiKey) PrivateKey(slot Slot, public crypto.PublicKey, auth KeyAuth) return &keyEd25519{yk, slot, pub, auth, pp}, nil case *rsa.PublicKey: return &keyRSA{yk, slot, pub, auth, pp}, nil + case *ecdh.PublicKey: + if crv := pub.Curve(); crv != ecdh.X25519() { + return nil, fmt.Errorf("unsupported ecdh curve: %v", crv) + } + return &X25519PrivateKey{yk, slot, pub, auth, pp}, nil default: return nil, fmt.Errorf("unsupported public key type: %T", public) } @@ -853,7 +1024,7 @@ func (yk *YubiKey) PrivateKey(slot Slot, public crypto.PublicKey, auth KeyAuth) // Keys generated outside of the YubiKey should not be considered hardware-backed, // as there's no way to prove the key wasn't copied, exfiltrated, or replaced with malicious // material before being imported. -func (yk *YubiKey) SetPrivateKeyInsecure(key [24]byte, slot Slot, private crypto.PrivateKey, policy Key) error { +func (yk *YubiKey) SetPrivateKeyInsecure(key []byte, slot Slot, private crypto.PrivateKey, policy Key) error { // Reference implementation // https://github.com/Yubico/yubico-piv-tool/blob/671a5740ef09d6c5d9d33f6e5575450750b58bde/lib/ykpiv.c#L1812 @@ -872,6 +1043,12 @@ func (yk *YubiKey) SetPrivateKeyInsecure(key [24]byte, slot Slot, private crypto case 2048: policy.Algorithm = AlgorithmRSA2048 elemLen = 128 + case 3072: + policy.Algorithm = AlgorithmRSA3072 + elemLen = 192 + case 4096: + policy.Algorithm = AlgorithmRSA4096 + elemLen = 256 default: return errUnsupportedKeySize } @@ -904,8 +1081,25 @@ func (yk *YubiKey) SetPrivateKeyInsecure(key [24]byte, slot Slot, private crypto copy(privateKey[padding:], valueBytes) params = append(params, privateKey) + case ed25519.PrivateKey: + paramTag = 0x07 + elemLen = ed25519.SeedSize + + // seed + privateKey := make([]byte, elemLen) + copy(privateKey, priv[:32]) + params = append(params, privateKey) + case *ecdh.PrivateKey: + if crv := priv.Curve(); crv != ecdh.X25519() { + return fmt.Errorf("unsupported ecdh curve: %v", crv) + } + paramTag = 0x08 + elemLen = 32 + + // seed + params = append(params, priv.Bytes()) default: - return errors.New("unsupported private key type") + return fmt.Errorf("unsupported private key type: %T", private) } elemLenASN1 := marshalASN1Length(uint64(elemLen)) @@ -921,7 +1115,7 @@ func (yk *YubiKey) SetPrivateKeyInsecure(key [24]byte, slot Slot, private crypto tags = append(tags, param...) } - if err := ykAuthenticate(yk.tx, key, yk.rand); err != nil { + if err := ykAuthenticate(yk.tx, key, yk.rand, yk.version); err != nil { return fmt.Errorf("authenticating with management key: %w", err) } @@ -932,7 +1126,6 @@ func ykImportKey(tx *scTx, tags []byte, slot Slot, o Key) error { alg, ok := algorithmsMap[o.Algorithm] if !ok { return fmt.Errorf("unsupported algorithm") - } tp, ok := touchPolicyMap[o.TouchPolicy] if !ok { @@ -1000,10 +1193,31 @@ func (k *ECDSAPrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.Signer // used for the operation. Callers should use a cryptographic key // derivation function to extract the amount of bytes they need. func (k *ECDSAPrivateKey) SharedKey(peer *ecdsa.PublicKey) ([]byte, error) { - if peer.Curve.Params().BitSize != k.pub.Curve.Params().BitSize { + peerECDH, err := peer.ECDH() + if err != nil { + return nil, unsupportedCurveError{curve: peer.Params().BitSize} + } + return k.ECDH(peerECDH) +} + +// ECDH performs a Diffie-Hellman key agreement with the peer +// to produce a shared secret key. +// +// Peer's public key must use the same algorithm as the key in +// this slot, or an error will be returned. +// +// Length of the result depends on the types and sizes of the keys +// used for the operation. Callers should use a cryptographic key +// derivation function to extract the amount of bytes they need. +func (k *ECDSAPrivateKey) ECDH(peer *ecdh.PublicKey) ([]byte, error) { + ourECDH, err := k.pub.ECDH() + if err != nil { + return nil, unsupportedCurveError{curve: k.pub.Params().BitSize} + } + if peer.Curve() != ourECDH.Curve() { return nil, errMismatchingAlgorithms } - msg := elliptic.Marshal(peer.Curve, peer.X, peer.Y) + msg := peer.Bytes() return k.auth.do(k.yk, k.pp, func(tx *scTx) ([]byte, error) { var alg byte size := k.pub.Params().BitSize @@ -1042,6 +1256,33 @@ func (k *ECDSAPrivateKey) SharedKey(peer *ecdsa.PublicKey) ([]byte, error) { }) } +// X25519PrivateKey is a crypto.PrivateKey implementation for X25519 keys. It +// implements the method ECDH to perform Diffie-Hellman key agreements. +// +// Keys returned by YubiKey.PrivateKey() may be type asserted to +// *X25519PrivateKey, if the slot contains an X25519 key. +type X25519PrivateKey struct { + yk *YubiKey + slot Slot + pub *ecdh.PublicKey + auth KeyAuth + pp PINPolicy +} + +func (k *X25519PrivateKey) Public() crypto.PublicKey { + return k.pub +} + +// ECDH performs an ECDH exchange and returns the shared secret. +// +// Peer's public key must use the same algorithm as the key in this slot, or an +// error will be returned. +func (k *X25519PrivateKey) ECDH(peer *ecdh.PublicKey) ([]byte, error) { + return k.auth.do(k.yk, k.pp, func(tx *scTx) ([]byte, error) { + return ykECDHX25519(tx, k.slot, k.pub, peer) + }) +} + type keyEd25519 struct { yk *YubiKey slot Slot @@ -1054,9 +1295,9 @@ func (k *keyEd25519) Public() crypto.PublicKey { return k.pub } -func (k *keyEd25519) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) { +func (k *keyEd25519) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) ([]byte, error) { return k.auth.do(k.yk, k.pp, func(tx *scTx) ([]byte, error) { - return skSignEd25519(tx, k.slot, k.pub, digest) + return ykSignEd25519(tx, k.slot, k.pub, message, opts) }) } @@ -1127,9 +1368,46 @@ func ykSignECDSA(tx *scTx, slot Slot, pub *ecdsa.PublicKey, digest []byte) ([]by return rs, nil } -// This function only works on SoloKeys prototypes and other PIV devices that choose -// to implement Ed25519 signatures under alg 0x22. -func skSignEd25519(tx *scTx, slot Slot, pub ed25519.PublicKey, digest []byte) ([]byte, error) { +func ykECDHX25519(tx *scTx, slot Slot, pub *ecdh.PublicKey, peer *ecdh.PublicKey) ([]byte, error) { + if crv := pub.Curve(); crv != ecdh.X25519() { + return nil, fmt.Errorf("unsupported ecdh curve: %v", crv) + } + if pub.Curve() != peer.Curve() { + return nil, errMismatchingAlgorithms + } + cmd := apdu{ + instruction: insAuthenticate, + param1: algX25519, + param2: byte(slot.Key), + data: marshalASN1(0x7c, + append([]byte{0x82, 0x00}, + marshalASN1(0x85, peer.Bytes())...)), + } + resp, err := tx.Transmit(cmd) + if err != nil { + return nil, fmt.Errorf("command failed: %w", err) + } + + sig, _, err := unmarshalASN1(resp, 1, 0x1c) // 0x7c + if err != nil { + return nil, fmt.Errorf("unmarshal response: %v", err) + } + sharedSecret, _, err := unmarshalASN1(sig, 2, 0x02) // 0x82 + if err != nil { + return nil, fmt.Errorf("unmarshal response signature: %v", err) + } + + return sharedSecret, nil +} + +func ykSignEd25519(tx *scTx, slot Slot, pub ed25519.PublicKey, message []byte, opts crypto.SignerOpts) ([]byte, error) { + if opts.HashFunc() != crypto.Hash(0) { + return nil, fmt.Errorf("ed25519ph not supported") + } + if ed25519opts, ok := opts.(*ed25519.Options); ok && ed25519opts.Context != "" { + return nil, fmt.Errorf("ed25519ctx not supported") + } + // Adaptation of // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf#page=118 cmd := apdu{ @@ -1138,7 +1416,7 @@ func skSignEd25519(tx *scTx, slot Slot, pub ed25519.PublicKey, digest []byte) ([ param2: byte(slot.Key), data: marshalASN1(0x7c, append([]byte{0x82, 0x00}, - marshalASN1(0x81, digest)...)), + marshalASN1(0x81, message)...)), } resp, err := tx.Transmit(cmd) if err != nil { @@ -1169,11 +1447,7 @@ func unmarshalASN1(b []byte, class, tag int) (obj, rest []byte, err error) { func decodeECPublic(b []byte, curve elliptic.Curve) (*ecdsa.PublicKey, error) { // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf#page=95 - r, _, err := unmarshalASN1(b, 1, 0x49) - if err != nil { - return nil, fmt.Errorf("unmarshal response: %v", err) - } - p, _, err := unmarshalASN1(r, 2, 0x06) + p, _, err := unmarshalASN1(b, 2, 0x06) if err != nil { return nil, fmt.Errorf("unmarshal points: %v", err) } @@ -1199,11 +1473,7 @@ func decodeECPublic(b []byte, curve elliptic.Curve) (*ecdsa.PublicKey, error) { func decodeEd25519Public(b []byte) (ed25519.PublicKey, error) { // Adaptation of // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf#page=95 - r, _, err := unmarshalASN1(b, 1, 0x49) - if err != nil { - return nil, fmt.Errorf("unmarshal response: %v", err) - } - p, _, err := unmarshalASN1(r, 2, 0x06) + p, _, err := unmarshalASN1(b, 2, 0x06) if err != nil { return nil, fmt.Errorf("unmarshal points: %v", err) } @@ -1215,11 +1485,7 @@ func decodeEd25519Public(b []byte) (ed25519.PublicKey, error) { func decodeRSAPublic(b []byte) (*rsa.PublicKey, error) { // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf#page=95 - r, _, err := unmarshalASN1(b, 1, 0x49) - if err != nil { - return nil, fmt.Errorf("unmarshal response: %v", err) - } - mod, r, err := unmarshalASN1(r, 2, 0x01) + mod, r, err := unmarshalASN1(b, 2, 0x01) if err != nil { return nil, fmt.Errorf("unmarshal modulus: %v", err) } @@ -1236,6 +1502,16 @@ func decodeRSAPublic(b []byte) (*rsa.PublicKey, error) { return &rsa.PublicKey{N: &n, E: int(e.Int64())}, nil } +func decodeX25519Public(b []byte) (*ecdh.PublicKey, error) { + // Adaptation of + // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf#page=95 + p, _, err := unmarshalASN1(b, 2, 0x06) + if err != nil { + return nil, fmt.Errorf("unmarshal points: %v", err) + } + return ecdh.X25519().NewPublicKey(p) +} + func rsaAlg(pub *rsa.PublicKey) (byte, error) { size := pub.N.BitLen() switch size { @@ -1243,6 +1519,10 @@ func rsaAlg(pub *rsa.PublicKey) (byte, error) { return algRSA1024, nil case 2048: return algRSA2048, nil + case 3072: + return algRSA3072, nil + case 4096: + return algRSA4096, nil default: return 0, fmt.Errorf("unsupported rsa key size: %d", size) } diff --git a/vendor/github.com/go-piv/piv-go/piv/pcsc.go b/vendor/github.com/go-piv/piv-go/v2/piv/pcsc.go similarity index 100% rename from vendor/github.com/go-piv/piv-go/piv/pcsc.go rename to vendor/github.com/go-piv/piv-go/v2/piv/pcsc.go diff --git a/vendor/github.com/go-piv/piv-go/piv/pcsc_darwin.go b/vendor/github.com/go-piv/piv-go/v2/piv/pcsc_darwin.go similarity index 100% rename from vendor/github.com/go-piv/piv-go/piv/pcsc_darwin.go rename to vendor/github.com/go-piv/piv-go/v2/piv/pcsc_darwin.go diff --git a/vendor/github.com/go-piv/piv-go/piv/pcsc_errors b/vendor/github.com/go-piv/piv-go/v2/piv/pcsc_errors similarity index 100% rename from vendor/github.com/go-piv/piv-go/piv/pcsc_errors rename to vendor/github.com/go-piv/piv-go/v2/piv/pcsc_errors diff --git a/vendor/github.com/go-piv/piv-go/piv/pcsc_errors.go b/vendor/github.com/go-piv/piv-go/v2/piv/pcsc_errors.go similarity index 100% rename from vendor/github.com/go-piv/piv-go/piv/pcsc_errors.go rename to vendor/github.com/go-piv/piv-go/v2/piv/pcsc_errors.go diff --git a/vendor/github.com/go-piv/piv-go/piv/pcsc_errors.py b/vendor/github.com/go-piv/piv-go/v2/piv/pcsc_errors.py similarity index 100% rename from vendor/github.com/go-piv/piv-go/piv/pcsc_errors.py rename to vendor/github.com/go-piv/piv-go/v2/piv/pcsc_errors.py diff --git a/vendor/github.com/go-piv/piv-go/piv/pcsc_freebsd.go b/vendor/github.com/go-piv/piv-go/v2/piv/pcsc_freebsd.go similarity index 100% rename from vendor/github.com/go-piv/piv-go/piv/pcsc_freebsd.go rename to vendor/github.com/go-piv/piv-go/v2/piv/pcsc_freebsd.go diff --git a/vendor/github.com/go-piv/piv-go/piv/pcsc_linux.go b/vendor/github.com/go-piv/piv-go/v2/piv/pcsc_linux.go similarity index 100% rename from vendor/github.com/go-piv/piv-go/piv/pcsc_linux.go rename to vendor/github.com/go-piv/piv-go/v2/piv/pcsc_linux.go diff --git a/vendor/github.com/go-piv/piv-go/piv/pcsc_openbsd.go b/vendor/github.com/go-piv/piv-go/v2/piv/pcsc_openbsd.go similarity index 100% rename from vendor/github.com/go-piv/piv-go/piv/pcsc_openbsd.go rename to vendor/github.com/go-piv/piv-go/v2/piv/pcsc_openbsd.go diff --git a/vendor/github.com/go-piv/piv-go/piv/pcsc_unix.go b/vendor/github.com/go-piv/piv-go/v2/piv/pcsc_unix.go similarity index 100% rename from vendor/github.com/go-piv/piv-go/piv/pcsc_unix.go rename to vendor/github.com/go-piv/piv-go/v2/piv/pcsc_unix.go diff --git a/vendor/github.com/go-piv/piv-go/piv/pcsc_windows.go b/vendor/github.com/go-piv/piv-go/v2/piv/pcsc_windows.go similarity index 100% rename from vendor/github.com/go-piv/piv-go/piv/pcsc_windows.go rename to vendor/github.com/go-piv/piv-go/v2/piv/pcsc_windows.go diff --git a/vendor/github.com/go-piv/piv-go/piv/piv.go b/vendor/github.com/go-piv/piv-go/v2/piv/piv.go similarity index 72% rename from vendor/github.com/go-piv/piv-go/piv/piv.go rename to vendor/github.com/go-piv/piv-go/v2/piv/piv.go index fe1ac2f311..a4d884ec88 100644 --- a/vendor/github.com/go-piv/piv-go/piv/piv.go +++ b/vendor/github.com/go-piv/piv-go/v2/piv/piv.go @@ -16,6 +16,8 @@ package piv import ( "bytes" + "crypto/aes" + "crypto/cipher" "crypto/des" "crypto/rand" "encoding/asn1" @@ -36,7 +38,7 @@ var ( // DefaultManagementKey for the PIV applet. The Management Key is a Triple-DES // key required for slot actions such as generating keys, setting certificates, // and signing. - DefaultManagementKey = [24]byte{ + DefaultManagementKey = []byte{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, @@ -59,13 +61,19 @@ const ( // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-78-4.pdf#page=17 algTag = 0x80 alg3DES = 0x03 + algAES128 = 0x08 + algAES192 = 0x0a + algAES256 = 0x0c algRSA1024 = 0x06 algRSA2048 = 0x07 + algRSA3072 = 0x05 + algRSA4096 = 0x16 algECCP256 = 0x11 algECCP384 = 0x14 - // non-standard; as implemented by SoloKeys. Chosen for low probability of eventual - // clashes, if and when PIV standard adds Ed25519 support - algEd25519 = 0x22 + // non-standard; implemented by YubiKey 5.7.x. Previous versions supported + // Ed25519 on SoloKeys with the value 0x22 + algEd25519 = 0xE0 + algX25519 = 0xE1 // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-78-4.pdf#page=16 keyAuthentication = 0x9a @@ -93,6 +101,7 @@ const ( insSetPINRetries = 0xfa insAttest = 0xf9 insGetSerial = 0xf8 + insGetMetadata = 0xf7 ) // YubiKey is an exclusive open connection to a YubiKey smart card. While open, @@ -142,7 +151,7 @@ type client struct { func (c *client) Cards() ([]string, error) { ctx, err := newSCContext() if err != nil { - return nil, fmt.Errorf("connecting to pscs: %w", err) + return nil, fmt.Errorf("connecting to pcsc: %w", err) } defer ctx.Close() return ctx.ListReaders() @@ -209,7 +218,11 @@ func encodePIN(pin string) ([]byte, error) { if len(data) > 8 { return nil, fmt.Errorf("pin longer than 8 bytes") } + // apply padding + // 2.4 Security Architecture + // 2.4.3 Authentication of an Individual + // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf#page=88 for i := len(data); i < 8; i++ { data = append(data, 0xff) } @@ -236,7 +249,10 @@ func ykLogin(tx *scTx, pin string) error { return err } + // 3.2 PIV Card Application Card Commands for Authentication + // 3.2.1 VERIFY Card Command // https://csrc.nist.gov/CSRC/media/Publications/sp/800-73/4/archive/2015-05-29/documents/sp800_73-4_pt2_draft.pdf#page=20 + // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf#page=86 cmd := apdu{instruction: insVerify, param2: 0x80, data: data} if _, err := tx.Transmit(cmd); err != nil { return fmt.Errorf("verify pin: %w", err) @@ -340,8 +356,8 @@ type version struct { // certificates to slots. // // Use DefaultManagementKey if the management key hasn't been set. -func (yk *YubiKey) authManagementKey(key [24]byte) error { - return ykAuthenticate(yk.tx, key, yk.rand) +func (yk *YubiKey) authManagementKey(key []byte) error { + return ykAuthenticate(yk.tx, key, yk.rand, yk.version) } var ( @@ -356,14 +372,50 @@ var ( aidYubiKey = [...]byte{0xa0, 0x00, 0x00, 0x05, 0x27, 0x20, 0x01, 0x01} ) -func ykAuthenticate(tx *scTx, key [24]byte, rand io.Reader) error { +var managementKeyLengthMap = map[byte]int{ + alg3DES: 24, + algAES128: 16, + algAES192: 24, + algAES256: 32, +} + +func ykAuthenticate(tx *scTx, key []byte, rand io.Reader, version *version) error { // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf#page=92 // https://tsapps.nist.gov/publication/get_pdf.cfm?pub_id=918402#page=114 + var managementKeyType byte + if supportsVersion(version, 5, 3, 0) { + // if yubikey version >= 5.3.0, determine management key type using slot metadata + cmd := apdu{ + instruction: insGetMetadata, + param1: 0x00, + param2: keyCardManagement, + } + resp, err := tx.Transmit(cmd) + if err != nil { + return fmt.Errorf("determining key management type: %w", err) + } + managementKeyType = resp[2:][0] + } + + // set challengeLength based on managementKeyType + var challengeLength byte + switch managementKeyType { + case algAES128, algAES192, algAES256: + challengeLength = 16 + default: + // default fallback to 3DES + managementKeyType = alg3DES + challengeLength = 8 + } + if len(key) != managementKeyLengthMap[managementKeyType] { + return fmt.Errorf("invalid management key length: %d bytes (expected %d)", len(key), managementKeyLengthMap[managementKeyType]) + } + // request a witness cmd := apdu{ instruction: insAuthenticate, - param1: alg3DES, + param1: managementKeyType, param2: keyCardManagement, data: []byte{ 0x7c, // Dynamic Authentication Template tag @@ -381,45 +433,55 @@ func ykAuthenticate(tx *scTx, key [24]byte, rand io.Reader) error { } if !bytes.Equal(resp[:4], []byte{ 0x7c, - 0x0a, - 0x80, // 'Witness' - 0x08, // Tag length + challengeLength + 2, + 0x80, // 'Witness' + challengeLength, // Tag length }) { return fmt.Errorf("invalid authentication object header: %x", resp[:4]) } - cardChallenge := resp[4 : 4+8] - cardResponse := make([]byte, 8) - - block, err := des.NewTripleDESCipher(key[:]) - if err != nil { - return fmt.Errorf("creating triple des block cipher: %v", err) + var block cipher.Block + switch managementKeyType { + case algAES128, algAES192, algAES256: + block, err = aes.NewCipher(key[:]) + if err != nil { + return fmt.Errorf("creating aes block cipher: %v", err) + } + default: + block, err = des.NewTripleDESCipher(key[:]) + if err != nil { + return fmt.Errorf("creating des block cipher: %v", err) + } } + + cardChallenge := resp[4 : 4+challengeLength] + cardResponse := make([]byte, challengeLength) + block.Decrypt(cardResponse, cardChallenge) - challenge := make([]byte, 8) + challenge := make([]byte, challengeLength) if _, err := io.ReadFull(rand, challenge); err != nil { return fmt.Errorf("reading rand data: %v", err) } - response := make([]byte, 8) + response := make([]byte, challengeLength) block.Encrypt(response, challenge) data := []byte{ 0x7c, // Dynamic Authentication Template tag - 20, // 2+8+2+8 - 0x80, // 'Witness' - 0x08, // Tag length + (challengeLength + 2) * 2, + 0x80, // 'Witness' + challengeLength, // Tag length } data = append(data, cardResponse...) data = append(data, - 0x81, // 'Challenge' - 0x08, // Tag length + 0x81, // 'Challenge' + challengeLength, // Tag length ) data = append(data, challenge...) cmd = apdu{ instruction: insAuthenticate, - param1: alg3DES, + param1: managementKeyType, param2: keyCardManagement, data: data, } @@ -432,13 +494,13 @@ func ykAuthenticate(tx *scTx, key [24]byte, rand io.Reader) error { } if !bytes.Equal(resp[:4], []byte{ 0x7c, - 0x0a, + challengeLength + 2, 0x82, // 'Response' - 0x08, + challengeLength, }) { return fmt.Errorf("response invalid authentication object header: %x", resp[:4]) } - if !bytes.Equal(resp[4:4+8], response) { + if !bytes.Equal(resp[4:4+challengeLength], response) { return fmt.Errorf("challenge failed") } @@ -449,20 +511,21 @@ func ykAuthenticate(tx *scTx, key [24]byte, rand io.Reader) error { // are triple-des keys, however padding isn't verified. To generate a new key, // generate 24 random bytes. // -// var newKey [24]byte -// if _, err := io.ReadFull(rand.Reader, newKey[:]); err != nil { -// // ... -// } -// if err := yk.SetManagementKey(piv.DefaultManagementKey, newKey); err != nil { -// // ... -// } -// +// Note: Yubikeys also support aes128, aes192, and aes256 management keys, +// which are 16, 24, and 32 bytes, respectively. // -func (yk *YubiKey) SetManagementKey(oldKey, newKey [24]byte) error { - if err := ykAuthenticate(yk.tx, oldKey, yk.rand); err != nil { +// var newKey [24]byte +// if _, err := io.ReadFull(rand.Reader, newKey[:]); err != nil { +// // ... +// } +// if err := yk.SetManagementKey(piv.DefaultManagementKey, newKey[:]); err != nil { +// // ... +// } +func (yk *YubiKey) SetManagementKey(oldKey, newKey []byte) error { + if err := ykAuthenticate(yk.tx, oldKey, yk.rand, yk.version); err != nil { return fmt.Errorf("authenticating with old key: %w", err) } - if err := ykSetManagementKey(yk.tx, newKey, false); err != nil { + if err := ykSetManagementKey(yk.tx, newKey, false, yk.version); err != nil { return err } return nil @@ -470,13 +533,32 @@ func (yk *YubiKey) SetManagementKey(oldKey, newKey [24]byte) error { // ykSetManagementKey updates the management key to a new key. This requires // authenticating with the existing management key. -func ykSetManagementKey(tx *scTx, key [24]byte, touch bool) error { +func ykSetManagementKey(tx *scTx, key []byte, touch bool, version *version) error { + var managementKeyType byte + if supportsVersion(version, 5, 4, 0) { + // if yubikey version >= 5.4.0, set AES management key + switch len(key) { + case 16: + managementKeyType = algAES128 + case 24: + managementKeyType = algAES192 + case 32: + managementKeyType = algAES256 + default: + return fmt.Errorf("invalid new AES management key length: %d bytes (expected 16, 24, or 32)", len(key)) + } + } else if len(key) == 24 { + // if yubikey version < 5.4.0, set legacy 3DES management key + managementKeyType = alg3DES + } else { + return fmt.Errorf("invalid new 3DES management key length: %d bytes (expected 24)", len(key)) + } cmd := apdu{ instruction: insSetMGMKey, param1: 0xff, param2: 0xff, data: append([]byte{ - alg3DES, keyCardManagement, 24, + managementKeyType, keyCardManagement, byte(len(key)), }, key[:]...), } if touch { @@ -493,17 +575,16 @@ func ykSetManagementKey(tx *scTx, key [24]byte, touch bool) error { // // To generate a new PIN, use the crypto/rand package. // -// // Generate a 6 character PIN. -// newPINInt, err := rand.Int(rand.Reader, bit.NewInt(1_000_000)) -// if err != nil { -// // ... -// } -// // Format with leading zeros. -// newPIN := fmt.Sprintf("%06d", newPINInt) -// if err := yk.SetPIN(piv.DefaultPIN, newPIN); err != nil { -// // ... -// } -// +// // Generate a 6 character PIN. +// newPINInt, err := rand.Int(rand.Reader, bit.NewInt(1_000_000)) +// if err != nil { +// // ... +// } +// // Format with leading zeros. +// newPIN := fmt.Sprintf("%06d", newPINInt) +// if err := yk.SetPIN(piv.DefaultPIN, newPIN); err != nil { +// // ... +// } func (yk *YubiKey) SetPIN(oldPIN, newPIN string) error { return ykChangePIN(yk.tx, oldPIN, newPIN) } @@ -554,17 +635,16 @@ func ykUnblockPIN(tx *scTx, puk, newPIN string) error { // // To generate a new PUK, use the crypto/rand package. // -// // Generate a 8 character PUK. -// newPUKInt, err := rand.Int(rand.Reader, bit.NewInt(100_000_000)) -// if err != nil { -// // ... -// } -// // Format with leading zeros. -// newPUK := fmt.Sprintf("%08d", newPUKInt) -// if err := yk.SetPIN(piv.DefaultPUK, newPUK); err != nil { -// // ... -// } -// +// // Generate a 8 character PUK. +// newPUKInt, err := rand.Int(rand.Reader, big.NewInt(100_000_000)) +// if err != nil { +// // ... +// } +// // Format with leading zeros. +// newPUK := fmt.Sprintf("%08d", newPUKInt) +// if err := yk.SetPUK(piv.DefaultPUK, newPUK); err != nil { +// // ... +// } func (yk *YubiKey) SetPUK(oldPUK, newPUK string) error { return ykChangePUK(yk.tx, oldPUK, newPUK) } @@ -587,6 +667,47 @@ func ykChangePUK(tx *scTx, oldPUK, newPUK string) error { return err } +// SetRetries sets the allowed retry count for the PIN and the PUK. +// +// Yubikeys allows one byte for storing each, allowed values are 1-255. In instances of greater +// than 15 retries remaining, the remaining count will show 15 as Yubikeys only have 4 bits in +// the response for remaining retries. +// +// IMPORTANT NOTE: Changing the retries on Yubikeys RESETS THE PIN AND PUK TO THEIR DEFAULTS! +// If you use SetRetries, it is *highly* recommended that you follow it with SetPIN and SetPUK. +// https://docs.yubico.com/yesdk/users-manual/application-piv/commands.html#set-pin-retries +// +// if err := yk.SetRetries(piv.DefaultManagementKey, piv.DefaultPIN, 5, 4); err != nil { +// // ... +// } +func (yk *YubiKey) SetRetries(managementKey []byte, pin string, pinRetries int, pukRetries int) error { + return ykSetRetries(yk.tx, managementKey, pin, pinRetries, pukRetries, yk.rand, yk.version) +} + +func ykSetRetries(tx *scTx, managementKey []byte, pin string, pinRetries int, pukRetries int, rand io.Reader, version *version) error { + if pinRetries < 1 || pukRetries < 1 || pinRetries > 255 || pukRetries > 255 { + return fmt.Errorf("pinRetries and pukRetries must both be in range 1 - 255") + } + + // NOTE: this action requires the management key AND PIN to be authenticated on + // the same transaction. It doesn't work otherwise. + if err := ykAuthenticate(tx, managementKey, rand, version); err != nil { + return fmt.Errorf("authenticating with management key: %w", err) + } + if err := ykLogin(tx, pin); err != nil { + return fmt.Errorf("authenticating with pin: %w", err) + } + cmd := apdu{ + instruction: insSetPINRetries, + param1: byte(pinRetries), + param2: byte(pukRetries), + } + if _, err := tx.Transmit(cmd); err != nil { + return fmt.Errorf("command failed: %w", err) + } + return nil +} + func ykSelectApplication(tx *scTx, id []byte) error { cmd := apdu{ instruction: insSelectApplication, @@ -650,8 +771,8 @@ func (yk *YubiKey) Metadata(pin string) (*Metadata, error) { // SetMetadata sets PIN protected metadata on the key. This is primarily to // store the management key on the smart card instead of managing the PIN and // management key seperately. -func (yk *YubiKey) SetMetadata(key [24]byte, m *Metadata) error { - return ykSetProtectedMetadata(yk.tx, key, m) +func (yk *YubiKey) SetMetadata(key []byte, m *Metadata) error { + return ykSetProtectedMetadata(yk.tx, key, m, yk.rand, yk.version) } // Metadata holds protected metadata. This is primarily used by YubiKey manager @@ -659,7 +780,7 @@ func (yk *YubiKey) SetMetadata(key [24]byte, m *Metadata) error { // guarded by the PIN. type Metadata struct { // ManagementKey is the management key stored directly on the YubiKey. - ManagementKey *[24]byte + ManagementKey *[]byte // raw, if not nil, is the full bytes raw []byte @@ -675,7 +796,7 @@ func (m *Metadata) marshal() ([]byte, error) { 26, 0x89, 24, - }, m.ManagementKey[:]...), nil + }, *m.ManagementKey...), nil } if m.ManagementKey == nil { @@ -710,7 +831,7 @@ func (m *Metadata) marshal() ([]byte, error) { metadata.Bytes = append(metadata.Bytes, v.FullBytes...) } metadata.Bytes = append(metadata.Bytes, 0x89, 24) - metadata.Bytes = append(metadata.Bytes, m.ManagementKey[:]...) + metadata.Bytes = append(metadata.Bytes, *m.ManagementKey...) return asn1.Marshal(metadata) } @@ -737,12 +858,12 @@ func (m *Metadata) unmarshal(b []byte) error { continue } // 0x89 indicates key - if len(v.Bytes) != 24 { + switch len(v.Bytes) { + case 16, 24, 32: + default: return fmt.Errorf("invalid management key length: %d", len(v.Bytes)) } - var key [24]byte - copy(key[:], v.Bytes) - m.ManagementKey = &key + m.ManagementKey = &v.Bytes } return nil } @@ -780,7 +901,7 @@ func ykGetProtectedMetadata(tx *scTx, pin string) (*Metadata, error) { return &m, nil } -func ykSetProtectedMetadata(tx *scTx, key [24]byte, m *Metadata) error { +func ykSetProtectedMetadata(tx *scTx, key []byte, m *Metadata, rand io.Reader, version *version) error { data, err := m.marshal() if err != nil { return fmt.Errorf("encoding metadata: %v", err) @@ -792,19 +913,29 @@ func ykSetProtectedMetadata(tx *scTx, key [24]byte, m *Metadata) error { 0xc1, 0x09, }, marshalASN1(0x53, data)...) + // NOTE: for some reason this action requires the management key authenticated + // on the same transaction. It doesn't work otherwise. + if err := ykAuthenticate(tx, key, rand, version); err != nil { + return fmt.Errorf("authenticating with key: %w", err) + } cmd := apdu{ instruction: insPutData, param1: 0x3f, param2: 0xff, data: data, } - // NOTE: for some reason this action requires the management key authenticated - // on the same transaction. It doesn't work otherwise. - if err := ykAuthenticate(tx, key, rand.Reader); err != nil { - return fmt.Errorf("authenticating with key: %w", err) - } if _, err := tx.Transmit(cmd); err != nil { return fmt.Errorf("command failed: %w", err) } return nil } + +func supportsVersion(v *version, major, minor, patch byte) bool { + if v.major != major { + return v.major > major + } + if v.minor != minor { + return v.minor > minor + } + return v.patch >= patch +} diff --git a/vendor/filippo.io/edwards25519/LICENSE b/vendor/github.com/go-piv/piv-go/v2/third_party/rsa/LICENSE similarity index 100% rename from vendor/filippo.io/edwards25519/LICENSE rename to vendor/github.com/go-piv/piv-go/v2/third_party/rsa/LICENSE diff --git a/vendor/github.com/go-piv/piv-go/third_party/rsa/README b/vendor/github.com/go-piv/piv-go/v2/third_party/rsa/README similarity index 100% rename from vendor/github.com/go-piv/piv-go/third_party/rsa/README rename to vendor/github.com/go-piv/piv-go/v2/third_party/rsa/README diff --git a/vendor/github.com/go-piv/piv-go/third_party/rsa/pss.go b/vendor/github.com/go-piv/piv-go/v2/third_party/rsa/pss.go similarity index 100% rename from vendor/github.com/go-piv/piv-go/third_party/rsa/pss.go rename to vendor/github.com/go-piv/piv-go/v2/third_party/rsa/pss.go diff --git a/vendor/github.com/google/certificate-transparency-go/AUTHORS b/vendor/github.com/google/certificate-transparency-go/AUTHORS index 3ec5370574..ad514665ef 100644 --- a/vendor/github.com/google/certificate-transparency-go/AUTHORS +++ b/vendor/github.com/google/certificate-transparency-go/AUTHORS @@ -9,7 +9,6 @@ # Please keep the list sorted. Alex Cohn -Comodo CA Limited Ed Maste Elisha Silas Fiaz Hossain @@ -24,6 +23,7 @@ Nicholas Galbreath Oliver Weidner PrimeKey Solutions AB Ruslan Kovalov +Sectigo Limited Venafi, Inc. Vladimir Rutsky Ximin Luo diff --git a/vendor/github.com/google/certificate-transparency-go/CHANGELOG.md b/vendor/github.com/google/certificate-transparency-go/CHANGELOG.md index ad59927495..5cb7b7d433 100644 --- a/vendor/github.com/google/certificate-transparency-go/CHANGELOG.md +++ b/vendor/github.com/google/certificate-transparency-go/CHANGELOG.md @@ -2,6 +2,180 @@ ## HEAD +## v1.3.1 + +* Add AllLogListSignatureURL by @AlexLaroche in https://github.com/google/certificate-transparency-go/pull/1634 +* Add TiledLogs to log list JSON by @mcpherrinm in https://github.com/google/certificate-transparency-go/pull/1635 +* chore: relax go directive to permit 1.22.x by @dnwe in https://github.com/google/certificate-transparency-go/pull/1640 + +### Dependency Update + +* Bump github.com/fullstorydev/grpcurl from 1.9.1 to 1.9.2 in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1627 +* Bump the all-deps group with 3 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1628 +* Bump the docker-deps group across 5 directories with 3 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1630 +* Bump github/codeql-action from 3.27.5 to 3.27.6 in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1629 +* Bump golang.org/x/crypto from 0.30.0 to 0.31.0 in the go_modules group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1631 +* Bump the all-deps group with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1633 +* Bump the all-deps group with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1632 +* Bump the docker-deps group across 4 directories with 1 update by @dependabot in https://github.com/google/certificate-transparency-go/pull/1638 +* Bump the all-deps group with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1637 +* Bump the all-deps group across 1 directory with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1641 +* Bump the all-deps group with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1643 +* Bump google.golang.org/grpc from 1.69.2 to 1.69.4 in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1642 + +## v1.3.0 + +### CTFE Storage Saving: Extra Data Issuance Chain Deduplication + +This feature now supports PostgreSQL, in addition to the support for MySQL/MariaDB that was added in [v1.2.0](#v1.2.0). + +Log operators can choose to enable this feature for new PostgreSQL-based CT logs by adding new CTFE configs in the [LogMultiConfig](trillian/ctfe/configpb/config.proto) and importing the [database schema](trillian/ctfe/storage/postgresql/schema.sql). The other available options are documented in the [v1.2.0](#v1.2.0) changelog entry. + +This change is tested in Cloud Build tests using the `postgres:17` Docker image as of the time of writing. + +* Add IssuanceChainStorage PostgreSQL implementation by @robstradling in https://github.com/google/certificate-transparency-go/pull/1618 + +### Misc + +* [Dependabot] Update all docker images in one PR by @mhutchinson in https://github.com/google/certificate-transparency-go/pull/1614 +* Explicitly include version tag by @mhutchinson in https://github.com/google/certificate-transparency-go/pull/1617 +* Add empty cloudbuild_postgresql.yaml by @roger2hk in https://github.com/google/certificate-transparency-go/pull/1623 + +### Dependency update + +* Bump the all-deps group with 4 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1609 +* Bump golang from 1.23.2-bookworm to 1.23.3-bookworm in /internal/witness/cmd/feeder in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1611 +* Bump github/codeql-action from 3.27.0 to 3.27.1 in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1610 +* Bump golang from 1.23.2-bookworm to 1.23.3-bookworm in /trillian/examples/deployment/docker/ctfe in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1612 +* Bump github.com/golang-jwt/jwt/v4 from 4.5.0 to 4.5.1 in the go_modules group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1613 +* Bump the docker-deps group across 3 directories with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1616 +* Bump github/codeql-action from 3.27.1 to 3.27.2 in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1615 +* Bump the docker-deps group across 4 directories with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1622 +* Bump github/codeql-action from 3.27.2 to 3.27.4 in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1620 +* Bump the all-deps group with 4 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1621 +* Bump github.com/google/trillian from 1.6.1 to 1.7.0 in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1624 +* Bump github/codeql-action from 3.27.4 to 3.27.5 in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1625 + +## v1.2.2 + +* Recommended Go version for development: 1.22 + * Using a different version can lead to presubmits failing due to unexpected diffs. + +### Add TLS Support + +Add TLS support for Trillian: By using `--trillian_tls_ca_cert_file` flag, users can provide a CA certificate, that is used to establish a secure communication with Trillian log server. + +Add TLS support for ct_server: By using `--tls_certificate` and `--tls_key` flags, users can provide a service certificate and key, that enables the server to handle HTTPS requests. + +* Add TLS support for CTLog server by @fghanmi in https://github.com/google/certificate-transparency-go/pull/1523 +* Add TLS support for migrillian by @fghanmi in https://github.com/google/certificate-transparency-go/pull/1525 +* fix TLS configuration for ct_server by @fghanmi in https://github.com/google/certificate-transparency-go/pull/1542 +* Add Trillian TLS support for ct_server by @fghanmi in https://github.com/google/certificate-transparency-go/pull/1551 + +### HTTP Idle Connection Timeout Flag + +A new flag `http_idle_timeout` is added to set the HTTP server's idle timeout value in the ct_server binary. This controls the maximum amount of time to wait for the next request when keep-alives are enabled. + +* add flag for HTTP idle connection timeout value by @bobcallaway in https://github.com/google/certificate-transparency-go/pull/1597 + +### Misc + +* Refactor issuance chain service by @mhutchinson in https://github.com/google/certificate-transparency-go/pull/1512 +* Use the version in the go.mod file for vuln checks by @mhutchinson in https://github.com/google/certificate-transparency-go/pull/1528 + +### Fixes + +* Fix failed tests on 32-bit OS by @roger2hk in https://github.com/google/certificate-transparency-go/pull/1540 + +### Dependency update + +* Bump go.etcd.io/etcd/v3 from 3.5.13 to 3.5.14 by @dependabot in https://github.com/google/certificate-transparency-go/pull/1500 +* Bump github/codeql-action from 3.25.6 to 3.25.7 by @dependabot in https://github.com/google/certificate-transparency-go/pull/1501 +* Bump golang.org/x/net from 0.25.0 to 0.26.0 by @dependabot in https://github.com/google/certificate-transparency-go/pull/1503 +* Group dependabot updates as much as possible by @mhutchinson in https://github.com/google/certificate-transparency-go/pull/1506 +* Bump golang from 1.22.3-bookworm to 1.22.4-bookworm in /internal/witness/cmd/witness in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1507 +* Bump the all-deps group with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1511 +* Bump golang from 1.22.3-bookworm to 1.22.4-bookworm in /trillian/examples/deployment/docker/ctfe in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1510 +* Bump golang from 1.22.3-bookworm to 1.22.4-bookworm in /integration in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1509 +* Bump golang from 1.22.3-bookworm to 1.22.4-bookworm in /internal/witness/cmd/feeder in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1508 +* Bump the all-deps group with 3 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1516 +* Bump golang from `aec4784` to `9678844` in /internal/witness/cmd/witness in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1518 +* Bump alpine from 3.19 to 3.20 in /trillian/examples/deployment/docker/envsubst by @dependabot in https://github.com/google/certificate-transparency-go/pull/1492 +* Bump golang from `aec4784` to `9678844` in /internal/witness/cmd/feeder in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1517 +* Bump golang from `aec4784` to `9678844` in /trillian/examples/deployment/docker/ctfe in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1513 +* Bump the all-deps group with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1515 +* Bump golang from `aec4784` to `9678844` in /integration in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1514 +* Bump alpine from `77726ef` to `b89d9c9` in /trillian/examples/deployment/docker/envsubst in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1519 +* Bump k8s.io/klog/v2 from 2.130.0 to 2.130.1 in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1521 +* Bump alpine from `77726ef` to `b89d9c9` in /internal/witness/cmd/feeder in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1520 +* Bump github/codeql-action from 3.25.10 to 3.25.11 in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1526 +* Bump version of go used by the vuln checker by @mhutchinson in https://github.com/google/certificate-transparency-go/pull/1527 +* Bump the all-deps group with 3 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1530 +* Bump golang from 1.22.4-bookworm to 1.22.5-bookworm in /internal/witness/cmd/feeder in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1531 +* Bump golang from 1.22.4-bookworm to 1.22.5-bookworm in /internal/witness/cmd/witness in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1532 +* Bump the all-deps group in /trillian/examples/deployment/docker/ctfe with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1533 +* Bump actions/upload-artifact from 4.3.3 to 4.3.4 in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1534 +* Bump golang from 1.22.4-bookworm to 1.22.5-bookworm in /integration in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1535 +* Bump the all-deps group with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1536 +* Bump github/codeql-action from 3.25.12 to 3.25.13 in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1538 +* Bump the all-deps group with 3 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1537 +* Bump the all-deps group with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1543 +* Bump golang from `6c27802` to `af9b40f` in /trillian/examples/deployment/docker/ctfe in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1544 +* Bump golang from `6c27802` to `af9b40f` in /internal/witness/cmd/witness in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1548 +* Bump golang from `6c27802` to `af9b40f` in /integration in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1547 +* Bump alpine from `b89d9c9` to `0a4eaa0` in /trillian/examples/deployment/docker/envsubst in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1546 +* Bump the all-deps group in /internal/witness/cmd/feeder with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1545 +* Bump the all-deps group with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1549 +* Bump golang.org/x/time from 0.5.0 to 0.6.0 in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1550 +* Bump golang from 1.22.5-bookworm to 1.22.6-bookworm in /internal/witness/cmd/feeder in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1552 +* Bump golang from 1.22.5-bookworm to 1.22.6-bookworm in /trillian/examples/deployment/docker/ctfe in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1553 +* Bump golang from 1.22.5-bookworm to 1.22.6-bookworm in /integration in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1554 +* Bump the all-deps group with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1555 +* Bump the all-deps group with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1556 +* Bump golang from 1.22.5-bookworm to 1.22.6-bookworm in /internal/witness/cmd/witness in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1557 +* Bump github.com/prometheus/client_golang from 1.19.1 to 1.20.0 in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1559 +* Bump github/codeql-action from 3.26.0 to 3.26.3 in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1561 +* Bump golang from 1.22.6-bookworm to 1.23.0-bookworm in /internal/witness/cmd/witness in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1558 +* Bump golang from 1.22.6-bookworm to 1.23.0-bookworm in /internal/witness/cmd/feeder in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1563 +* Bump golang from 1.22.6-bookworm to 1.23.0-bookworm in /trillian/examples/deployment/docker/ctfe in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1560 +* Bump golang from 1.22.6-bookworm to 1.23.0-bookworm in /integration in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1562 +* Bump go version to 1.22.6 by @roger2hk in https://github.com/google/certificate-transparency-go/pull/1564 +* Bump github.com/prometheus/client_golang from 1.20.0 to 1.20.2 in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1565 +* Bump github/codeql-action from 3.26.3 to 3.26.5 in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1566 +* Bump the all-deps group with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1568 +* Bump the all-deps group with 3 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1569 +* Bump go from 1.22.6 to 1.22.7 by @roger2hk in https://github.com/google/certificate-transparency-go/pull/1574 +* Bump alpine from `0a4eaa0` to `beefdbd` in /trillian/examples/deployment/docker/envsubst in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1571 +* Bump the all-deps group across 1 directory with 5 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1577 +* Bump golang from 1.23.0-bookworm to 1.23.1-bookworm in /internal/witness/cmd/witness in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1575 +* Bump golang from 1.23.0-bookworm to 1.23.1-bookworm in /integration in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1576 +* Bump the all-deps group in /trillian/examples/deployment/docker/ctfe with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1572 +* Bump the all-deps group in /internal/witness/cmd/feeder with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1573 +* Bump the all-deps group with 4 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1578 +* Bump github/codeql-action from 3.26.6 to 3.26.7 in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1579 +* Bump the all-deps group with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1580 +* Bump github/codeql-action from 3.26.7 to 3.26.8 in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1581 +* Bump distroless/base-debian12 from `c925d12` to `88e0a2a` in /trillian/examples/deployment/docker/ctfe in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1582 +* Bump the all-deps group in /trillian/examples/deployment/docker/ctfe with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1585 +* Bump the all-deps group with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1583 +* Bump golang from `1a5326b` to `dba79eb` in /integration in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1584 +* Bump golang from `1a5326b` to `dba79eb` in /internal/witness/cmd/feeder in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1587 +* Bump golang from `1a5326b` to `dba79eb` in /internal/witness/cmd/witness in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1586 +* Bump the all-deps group with 5 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1588 +* Bump the all-deps group with 6 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1589 +* Bump golang from 1.23.1-bookworm to 1.23.2-bookworm in /trillian/examples/deployment/docker/ctfe in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1593 +* Bump golang from 1.23.1-bookworm to 1.23.2-bookworm in /integration in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1592 +* Bump golang from 1.23.1-bookworm to 1.23.2-bookworm in /internal/witness/cmd/witness in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1591 +* Bump golang from 1.23.1-bookworm to 1.23.2-bookworm in /internal/witness/cmd/feeder in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1590 +* Bump the all-deps group with 2 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1595 +* Bump github.com/prometheus/client_golang from 1.20.4 to 1.20.5 in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1598 +* Bump golang from `18d2f94` to `2341ddf` in /integration in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1602 +* Bump golang from `18d2f94` to `2341ddf` in /internal/witness/cmd/witness in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1599 +* Bump golang from `18d2f94` to `2341ddf` in /trillian/examples/deployment/docker/ctfe in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1600 +* Bump golang from `18d2f94` to `2341ddf` in /internal/witness/cmd/feeder in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1601 +* Bump the all-deps group with 3 updates by @dependabot in https://github.com/google/certificate-transparency-go/pull/1603 +* Bump distroless/base-debian12 from `6ae5fe6` to `8fe31fb` in /trillian/examples/deployment/docker/ctfe in the all-deps group by @dependabot in https://github.com/google/certificate-transparency-go/pull/1604 + ## v1.2.1 ### Fixes diff --git a/vendor/github.com/google/certificate-transparency-go/CONTRIBUTORS b/vendor/github.com/google/certificate-transparency-go/CONTRIBUTORS index fd7550fcef..3a98a7e1ef 100644 --- a/vendor/github.com/google/certificate-transparency-go/CONTRIBUTORS +++ b/vendor/github.com/google/certificate-transparency-go/CONTRIBUTORS @@ -52,7 +52,7 @@ Paul Lietar Pavel Kalinnikov Pierre Phaneuf Rob Percival -Rob Stradling +Rob Stradling Roger Ng Roland Shoemaker Ruslan Kovalov diff --git a/vendor/github.com/google/certificate-transparency-go/README.md b/vendor/github.com/google/certificate-transparency-go/README.md index ac71ebc118..b528c55755 100644 --- a/vendor/github.com/google/certificate-transparency-go/README.md +++ b/vendor/github.com/google/certificate-transparency-go/README.md @@ -6,7 +6,7 @@ This repository holds Go code related to [Certificate Transparency](https://www.certificate-transparency.org/) (CT). The -repository requires Go version 1.21. +repository requires Go version 1.22. - [Repository Structure](#repository-structure) - [Trillian CT Personality](#trillian-ct-personality) diff --git a/vendor/github.com/google/certificate-transparency-go/cloudbuild_postgresql.yaml b/vendor/github.com/google/certificate-transparency-go/cloudbuild_postgresql.yaml new file mode 100644 index 0000000000..37faca72ac --- /dev/null +++ b/vendor/github.com/google/certificate-transparency-go/cloudbuild_postgresql.yaml @@ -0,0 +1,161 @@ +############################################################################# +## This file is based on cloudbuild.yaml, but targets PostgreSQL instead of +## MySQL. +############################################################################# + +timeout: 1200s +options: + machineType: N1_HIGHCPU_32 + volumes: + - name: go-modules + path: /go + env: + - GOPROXY=https://proxy.golang.org + - PROJECT_ROOT=github.com/google/certificate-transparency-go + - GOPATH=/go + +substitutions: + _CLUSTER_NAME: trillian-opensource-ci + _MASTER_ZONE: us-central1-a + +# Cloud Build logs sent to GCS bucket +logsBucket: 'gs://trillian-cloudbuild-logs' + +steps: +# First build a "ct_testbase" docker image which contains most of the tools we need for the later steps: +- name: 'gcr.io/cloud-builders/docker' + entrypoint: 'bash' + args: ['-c', 'docker pull gcr.io/$PROJECT_ID/ct_testbase:latest || exit 0'] +- name: 'gcr.io/cloud-builders/docker' + args: [ + 'build', + '-t', 'gcr.io/$PROJECT_ID/ct_testbase:latest', + '--cache-from', 'gcr.io/$PROJECT_ID/ct_testbase:latest', + '-f', './integration/Dockerfile', + '.' + ] + +# prepare spins up an ephemeral trillian instance for testing use. +- name: gcr.io/$PROJECT_ID/ct_testbase + entrypoint: 'bash' + id: 'prepare' + args: + - '-exc' + - | + # Use latest versions of Trillian docker images built by the Trillian CI cloudbuilders. + docker pull gcr.io/$PROJECT_ID/log_server:latest + docker tag gcr.io/$PROJECT_ID/log_server:latest postgresql_trillian-log-server + docker pull gcr.io/$PROJECT_ID/log_signer:latest + docker tag gcr.io/$PROJECT_ID/log_signer:latest postgresql_trillian-log-signer + + # Bring up an ephemeral trillian instance using the docker-compose config in the Trillian repo: + export TRILLIAN_LOCATION="$$(go list -f '{{.Dir}}' github.com/google/trillian)" + + # We need to fix up Trillian's docker-compose to connect to the CloudBuild network to that tests can use it: + echo -e "networks:\n default:\n external:\n name: cloudbuild" >> $${TRILLIAN_LOCATION}/examples/deployment/postgresql/docker-compose.yml + + docker-compose -f $${TRILLIAN_LOCATION}/examples/deployment/postgresql/docker-compose.yml pull postgresql trillian-log-server trillian-log-signer + docker-compose -f $${TRILLIAN_LOCATION}/examples/deployment/postgresql/docker-compose.yml up -d postgresql trillian-log-server trillian-log-signer + +# Install proto related bits and block on Trillian being ready +- name: gcr.io/$PROJECT_ID/ct_testbase + id: 'ci-ready' + entrypoint: 'bash' + args: + - '-ec' + - | + go install \ + github.com/golang/protobuf/proto \ + github.com/golang/protobuf/protoc-gen-go \ + github.com/golang/mock/mockgen \ + go.etcd.io/etcd/v3 go.etcd.io/etcd/etcdctl/v3 \ + github.com/fullstorydev/grpcurl/cmd/grpcurl + + # Generate all protoc and mockgen files + go generate -run="protoc" ./... + go generate -run="mockgen" ./... + + # Cache all the modules we'll need too + go mod download + go test ./... + + # Wait for trillian logserver to be up + until nc -z postgresql_trillian-log-server_1 8090; do echo .; sleep 5; done + + # Reset the CT test database + export CT_GO_PATH="$$(go list -f '{{.Dir}}' github.com/google/certificate-transparency-go)" + export POSTGRESQL_HOST="postgresql" + yes | bash "$${CT_GO_PATH}/scripts/resetpgctdb.sh" --verbose + waitFor: ['prepare'] + +# Run the presubmit tests +- name: gcr.io/$PROJECT_ID/ct_testbase + id: 'default_test' + env: + - 'GOFLAGS=' + - 'PRESUBMIT_OPTS=--no-linters --no-generate' + - 'TRILLIAN_LOG_SERVERS=postgresql_trillian-log-server_1:8090' + - 'TRILLIAN_LOG_SERVER_1=postgresql_trillian-log-server_1:8090' + - 'CONFIG_SUBDIR=/postgresql' + waitFor: ['ci-ready'] + +- name: gcr.io/$PROJECT_ID/ct_testbase + id: 'race_detection' + env: + - 'GOFLAGS=-race' + - 'PRESUBMIT_OPTS=--no-linters --no-generate' + - 'TRILLIAN_LOG_SERVERS=postgresql_trillian-log-server_1:8090' + - 'TRILLIAN_LOG_SERVER_1=postgresql_trillian-log-server_1:8090' + - 'CONFIG_SUBDIR=/postgresql' + waitFor: ['ci-ready'] + +- name: gcr.io/$PROJECT_ID/ct_testbase + id: 'etcd_with_coverage' + env: + - 'GOFLAGS=' + - 'PRESUBMIT_OPTS=--no-linters --no-generate --coverage' + - 'WITH_ETCD=true' + - 'TRILLIAN_LOG_SERVERS=postgresql_trillian-log-server_1:8090' + - 'TRILLIAN_LOG_SERVER_1=postgresql_trillian-log-server_1:8090' + - 'CONFIG_SUBDIR=/postgresql' + waitFor: ['ci-ready'] + +- name: gcr.io/$PROJECT_ID/ct_testbase + id: 'etcd_with_race' + env: + - 'GOFLAGS=-race' + - 'PRESUBMIT_OPTS=--no-linters --no-generate' + - 'WITH_ETCD=true' + - 'TRILLIAN_LOG_SERVERS=postgresql_trillian-log-server_1:8090' + - 'TRILLIAN_LOG_SERVER_1=postgresql_trillian-log-server_1:8090' + - 'CONFIG_SUBDIR=/postgresql' + waitFor: ['ci-ready'] + +- name: gcr.io/$PROJECT_ID/ct_testbase + id: 'with_pkcs11_and_race' + env: + - 'GOFLAGS=-race --tags=pkcs11' + - 'PRESUBMIT_OPTS=--no-linters --no-generate' + - 'WITH_PKCS11=true' + - 'TRILLIAN_LOG_SERVERS=postgresql_trillian-log-server_1:8090' + - 'TRILLIAN_LOG_SERVER_1=postgresql_trillian-log-server_1:8090' + - 'CONFIG_SUBDIR=/postgresql' + waitFor: ['ci-ready'] + +# Collect and submit codecoverage reports +- name: 'gcr.io/cloud-builders/curl' + id: 'codecov.io' + entrypoint: bash + args: ['-c', 'bash <(curl -s https://codecov.io/bash)'] + env: + - 'VCS_COMMIT_ID=$COMMIT_SHA' + - 'VCS_BRANCH_NAME=$BRANCH_NAME' + - 'VCS_PULL_REQUEST=$_PR_NUMBER' + - 'CI_BUILD_ID=$BUILD_ID' + - 'CODECOV_TOKEN=$_CODECOV_TOKEN' # _CODECOV_TOKEN is specified in the cloud build trigger + waitFor: ['etcd_with_coverage'] + +- name: gcr.io/$PROJECT_ID/ct_testbase + id: 'ci_complete' + entrypoint: /bin/true + waitFor: ['codecov.io', 'default_test', 'race_detection', 'etcd_with_coverage', 'etcd_with_race', 'with_pkcs11_and_race'] diff --git a/vendor/github.com/google/certificate-transparency-go/loglist3/loglist3.go b/vendor/github.com/google/certificate-transparency-go/loglist3/loglist3.go index c81726515c..c5e94f1874 100644 --- a/vendor/github.com/google/certificate-transparency-go/loglist3/loglist3.go +++ b/vendor/github.com/google/certificate-transparency-go/loglist3/loglist3.go @@ -39,8 +39,10 @@ const ( LogListURL = "https://www.gstatic.com/ct/log_list/v3/log_list.json" // LogListSignatureURL has the URL for the signature over Google Chrome's log list. LogListSignatureURL = "https://www.gstatic.com/ct/log_list/v3/log_list.sig" - // AllLogListURL has the URL for the list of all known logs (which isn't signed). + // AllLogListURL has the URL for the list of all known logs. AllLogListURL = "https://www.gstatic.com/ct/log_list/v3/all_logs_list.json" + // AllLogListSignatureURL has the URL for the signature over the list of all known logs. + AllLogListSignatureURL = "https://www.gstatic.com/ct/log_list/v3/all_logs_list.sig" ) // Manually mapped from https://www.gstatic.com/ct/log_list/v3/log_list_schema.json @@ -66,11 +68,14 @@ type Operator struct { // Email lists the email addresses that can be used to contact this log // operator. Email []string `json:"email"` - // Logs is a list of CT logs run by this operator. + // Logs is a list of RFC 6962 CT logs run by this operator. Logs []*Log `json:"logs"` + // TiledLogs is a list of Static CT API CT logs run by this operator. + TiledLogs []*TiledLog `json:"tiled_logs"` } -// Log describes a single CT log. +// Log describes a single RFC 6962 CT log. It is nearly the same as the TiledLog struct, +// but has a single URL field instead of SubmissionURL and MonitoringURL fields. type Log struct { // Description is a human-readable string that describes the log. Description string `json:"description,omitempty"` @@ -98,6 +103,37 @@ type Log struct { Type string `json:"log_type,omitempty"` } +// TiledLog describes a Static CT API log. It is nearly the same as the Log struct, +// but has both SubmissionURL and MonitoringURL fields instead of a single URL field. +type TiledLog struct { + // Description is a human-readable string that describes the log. + Description string `json:"description,omitempty"` + // LogID is the SHA-256 hash of the log's public key. + LogID []byte `json:"log_id"` + // Key is the public key with which signatures can be verified. + Key []byte `json:"key"` + // SubmissionURL + SubmissionURL string `json:"submission_url"` + // MonitoringURL + MonitoringURL string `json:"monitoring_url"` + // DNS is the address of the DNS API. + DNS string `json:"dns,omitempty"` + // MMD is the Maximum Merge Delay, in seconds. All submitted + // certificates must be incorporated into the log within this time. + MMD int32 `json:"mmd"` + // PreviousOperators is a list of previous operators and the timestamp + // of when they stopped running the log. + PreviousOperators []*PreviousOperator `json:"previous_operators,omitempty"` + // State is the current state of the log, from the perspective of the + // log list distributor. + State *LogStates `json:"state,omitempty"` + // TemporalInterval, if set, indicates that this log only accepts + // certificates with a NotAfter date in this time range. + TemporalInterval *TemporalInterval `json:"temporal_interval,omitempty"` + // Type indicates the purpose of this log, e.g. "test" or "prod". + Type string `json:"log_type,omitempty"` +} + // PreviousOperator holds information about a log operator and the time at which // they stopped running a log. type PreviousOperator struct { diff --git a/vendor/github.com/google/s2a-go/internal/proto/v2/s2a_go_proto/s2a.pb.go b/vendor/github.com/google/s2a-go/internal/proto/v2/s2a_go_proto/s2a.pb.go index 548f31da2d..f47c77a2ba 100644 --- a/vendor/github.com/google/s2a-go/internal/proto/v2/s2a_go_proto/s2a.pb.go +++ b/vendor/github.com/google/s2a-go/internal/proto/v2/s2a_go_proto/s2a.pb.go @@ -297,6 +297,8 @@ const ( ValidatePeerCertificateChainReq_RESERVED_CUSTOM_VERIFICATION_MODE_4 ValidatePeerCertificateChainReq_VerificationMode = 4 // Internal use only. ValidatePeerCertificateChainReq_RESERVED_CUSTOM_VERIFICATION_MODE_5 ValidatePeerCertificateChainReq_VerificationMode = 5 + // Internal use only. + ValidatePeerCertificateChainReq_RESERVED_CUSTOM_VERIFICATION_MODE_6 ValidatePeerCertificateChainReq_VerificationMode = 6 ) // Enum value maps for ValidatePeerCertificateChainReq_VerificationMode. @@ -308,6 +310,7 @@ var ( 3: "RESERVED_CUSTOM_VERIFICATION_MODE_3", 4: "RESERVED_CUSTOM_VERIFICATION_MODE_4", 5: "RESERVED_CUSTOM_VERIFICATION_MODE_5", + 6: "RESERVED_CUSTOM_VERIFICATION_MODE_6", } ValidatePeerCertificateChainReq_VerificationMode_value = map[string]int32{ "UNSPECIFIED": 0, @@ -316,6 +319,7 @@ var ( "RESERVED_CUSTOM_VERIFICATION_MODE_3": 3, "RESERVED_CUSTOM_VERIFICATION_MODE_4": 4, "RESERVED_CUSTOM_VERIFICATION_MODE_5": 5, + "RESERVED_CUSTOM_VERIFICATION_MODE_6": 6, } ) @@ -1978,8 +1982,8 @@ var file_internal_proto_v2_s2a_s2a_proto_rawDesc = []byte{ 0x4f, 0x66, 0x66, 0x6c, 0x6f, 0x61, 0x64, 0x52, 0x65, 0x73, 0x75, 0x6d, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x4b, 0x65, 0x79, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x12, 0x1b, 0x0a, 0x09, 0x6f, 0x75, 0x74, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x6f, 0x75, 0x74, 0x42, 0x79, 0x74, 0x65, 0x73, 0x22, 0xf4, - 0x05, 0x0a, 0x1f, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x50, 0x65, 0x65, 0x72, 0x43, + 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x6f, 0x75, 0x74, 0x42, 0x79, 0x74, 0x65, 0x73, 0x22, 0x9d, + 0x06, 0x0a, 0x1f, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x50, 0x65, 0x65, 0x72, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x52, 0x65, 0x71, 0x12, 0x52, 0x0a, 0x04, 0x6d, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x3e, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, @@ -2013,7 +2017,7 @@ var file_internal_proto_v2_s2a_s2a_proto_rawDesc = []byte{ 0x6e, 0x74, 0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x22, 0x73, 0x65, 0x72, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x64, 0x55, 0x6e, 0x72, 0x65, 0x73, 0x74, 0x72, 0x69, 0x63, 0x74, 0x65, 0x64, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x50, 0x6f, 0x6c, - 0x69, 0x63, 0x79, 0x22, 0xc1, 0x01, 0x0a, 0x10, 0x56, 0x65, 0x72, 0x69, 0x66, 0x69, 0x63, 0x61, + 0x69, 0x63, 0x79, 0x22, 0xea, 0x01, 0x0a, 0x10, 0x56, 0x65, 0x72, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4d, 0x6f, 0x64, 0x65, 0x12, 0x0f, 0x0a, 0x0b, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x53, 0x50, 0x49, 0x46, 0x46, 0x45, 0x10, 0x01, 0x12, 0x15, 0x0a, 0x11, 0x43, 0x4f, 0x4e, 0x4e, 0x45, 0x43, 0x54, @@ -2025,141 +2029,143 @@ var file_internal_proto_v2_s2a_s2a_proto_rawDesc = []byte{ 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x4d, 0x4f, 0x44, 0x45, 0x5f, 0x34, 0x10, 0x04, 0x12, 0x27, 0x0a, 0x23, 0x52, 0x45, 0x53, 0x45, 0x52, 0x56, 0x45, 0x44, 0x5f, 0x43, 0x55, 0x53, 0x54, 0x4f, 0x4d, 0x5f, 0x56, 0x45, 0x52, 0x49, 0x46, 0x49, 0x43, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x4d, - 0x4f, 0x44, 0x45, 0x5f, 0x35, 0x10, 0x05, 0x42, 0x0c, 0x0a, 0x0a, 0x70, 0x65, 0x65, 0x72, 0x5f, - 0x6f, 0x6e, 0x65, 0x6f, 0x66, 0x22, 0xb2, 0x02, 0x0a, 0x20, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, - 0x74, 0x65, 0x50, 0x65, 0x65, 0x72, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, - 0x65, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x12, 0x6c, 0x0a, 0x11, 0x76, 0x61, - 0x6c, 0x69, 0x64, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x3f, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x50, 0x65, 0x65, - 0x72, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x43, 0x68, 0x61, 0x69, - 0x6e, 0x52, 0x65, 0x73, 0x70, 0x2e, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x69, 0x6f, 0x6e, - 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x52, 0x10, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x2d, 0x0a, 0x12, 0x76, 0x61, 0x6c, 0x69, - 0x64, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x64, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x18, 0x02, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x11, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x69, 0x6f, 0x6e, - 0x44, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x12, 0x32, 0x0a, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, - 0x78, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x53, 0x32, 0x41, 0x43, 0x6f, 0x6e, 0x74, 0x65, - 0x78, 0x74, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x22, 0x3d, 0x0a, 0x10, 0x56, - 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, - 0x0f, 0x0a, 0x0b, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, - 0x12, 0x0b, 0x0a, 0x07, 0x53, 0x55, 0x43, 0x43, 0x45, 0x53, 0x53, 0x10, 0x01, 0x12, 0x0b, 0x0a, - 0x07, 0x46, 0x41, 0x49, 0x4c, 0x55, 0x52, 0x45, 0x10, 0x02, 0x22, 0xa0, 0x05, 0x0a, 0x0a, 0x53, - 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x12, 0x3d, 0x0a, 0x0e, 0x6c, 0x6f, 0x63, - 0x61, 0x6c, 0x5f, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x18, 0x07, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x16, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, - 0x2e, 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x52, 0x0d, 0x6c, 0x6f, 0x63, 0x61, 0x6c, - 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x12, 0x62, 0x0a, 0x19, 0x61, 0x75, 0x74, 0x68, - 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6d, 0x65, 0x63, 0x68, 0x61, - 0x6e, 0x69, 0x73, 0x6d, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x25, 0x2e, 0x73, 0x32, - 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x41, 0x75, 0x74, 0x68, 0x65, - 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4d, 0x65, 0x63, 0x68, 0x61, 0x6e, 0x69, - 0x73, 0x6d, 0x52, 0x18, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x4d, 0x65, 0x63, 0x68, 0x61, 0x6e, 0x69, 0x73, 0x6d, 0x73, 0x12, 0x61, 0x0a, 0x19, - 0x67, 0x65, 0x74, 0x5f, 0x74, 0x6c, 0x73, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, - 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x71, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, - 0x24, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x47, - 0x65, 0x74, 0x54, 0x6c, 0x73, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x48, 0x00, 0x52, 0x16, 0x67, 0x65, 0x74, 0x54, 0x6c, 0x73, 0x43, - 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x12, - 0x77, 0x0a, 0x21, 0x6f, 0x66, 0x66, 0x6c, 0x6f, 0x61, 0x64, 0x5f, 0x70, 0x72, 0x69, 0x76, 0x61, - 0x74, 0x65, 0x5f, 0x6b, 0x65, 0x79, 0x5f, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, - 0x5f, 0x72, 0x65, 0x71, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x73, 0x32, 0x61, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x4f, 0x66, 0x66, 0x6c, 0x6f, 0x61, - 0x64, 0x50, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x4b, 0x65, 0x79, 0x4f, 0x70, 0x65, 0x72, 0x61, - 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x48, 0x00, 0x52, 0x1d, 0x6f, 0x66, 0x66, 0x6c, 0x6f, - 0x61, 0x64, 0x50, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x4b, 0x65, 0x79, 0x4f, 0x70, 0x65, 0x72, - 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x12, 0x80, 0x01, 0x0a, 0x24, 0x6f, 0x66, 0x66, - 0x6c, 0x6f, 0x61, 0x64, 0x5f, 0x72, 0x65, 0x73, 0x75, 0x6d, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x5f, - 0x6b, 0x65, 0x79, 0x5f, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, - 0x71, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2e, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x4f, 0x66, 0x66, 0x6c, 0x6f, 0x61, 0x64, 0x52, 0x65, - 0x73, 0x75, 0x6d, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x4b, 0x65, 0x79, 0x4f, 0x70, 0x65, 0x72, 0x61, - 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x48, 0x00, 0x52, 0x20, 0x6f, 0x66, 0x66, 0x6c, 0x6f, + 0x4f, 0x44, 0x45, 0x5f, 0x35, 0x10, 0x05, 0x12, 0x27, 0x0a, 0x23, 0x52, 0x45, 0x53, 0x45, 0x52, + 0x56, 0x45, 0x44, 0x5f, 0x43, 0x55, 0x53, 0x54, 0x4f, 0x4d, 0x5f, 0x56, 0x45, 0x52, 0x49, 0x46, + 0x49, 0x43, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x4d, 0x4f, 0x44, 0x45, 0x5f, 0x36, 0x10, 0x06, + 0x42, 0x0c, 0x0a, 0x0a, 0x70, 0x65, 0x65, 0x72, 0x5f, 0x6f, 0x6e, 0x65, 0x6f, 0x66, 0x22, 0xb2, + 0x02, 0x0a, 0x20, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x50, 0x65, 0x65, 0x72, 0x43, + 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x52, + 0x65, 0x73, 0x70, 0x12, 0x6c, 0x0a, 0x11, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x5f, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x3f, + 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x56, 0x61, + 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x50, 0x65, 0x65, 0x72, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, + 0x69, 0x63, 0x61, 0x74, 0x65, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x2e, 0x56, + 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x52, + 0x10, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, + 0x74, 0x12, 0x2d, 0x0a, 0x12, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, + 0x64, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x11, 0x76, + 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x44, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, + 0x12, 0x32, 0x0a, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x18, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, + 0x2e, 0x53, 0x32, 0x41, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x52, 0x07, 0x63, 0x6f, 0x6e, + 0x74, 0x65, 0x78, 0x74, 0x22, 0x3d, 0x0a, 0x10, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x0f, 0x0a, 0x0b, 0x55, 0x4e, 0x53, 0x50, + 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0b, 0x0a, 0x07, 0x53, 0x55, 0x43, + 0x43, 0x45, 0x53, 0x53, 0x10, 0x01, 0x12, 0x0b, 0x0a, 0x07, 0x46, 0x41, 0x49, 0x4c, 0x55, 0x52, + 0x45, 0x10, 0x02, 0x22, 0xa0, 0x05, 0x0a, 0x0a, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x52, + 0x65, 0x71, 0x12, 0x3d, 0x0a, 0x0e, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x5f, 0x69, 0x64, 0x65, 0x6e, + 0x74, 0x69, 0x74, 0x79, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x73, 0x32, 0x61, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, + 0x74, 0x79, 0x52, 0x0d, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, + 0x79, 0x12, 0x62, 0x0a, 0x19, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x5f, 0x6d, 0x65, 0x63, 0x68, 0x61, 0x6e, 0x69, 0x73, 0x6d, 0x73, 0x18, 0x02, + 0x20, 0x03, 0x28, 0x0b, 0x32, 0x25, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x2e, 0x76, 0x32, 0x2e, 0x41, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x4d, 0x65, 0x63, 0x68, 0x61, 0x6e, 0x69, 0x73, 0x6d, 0x52, 0x18, 0x61, 0x75, 0x74, + 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4d, 0x65, 0x63, 0x68, 0x61, + 0x6e, 0x69, 0x73, 0x6d, 0x73, 0x12, 0x61, 0x0a, 0x19, 0x67, 0x65, 0x74, 0x5f, 0x74, 0x6c, 0x73, + 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, + 0x65, 0x71, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x47, 0x65, 0x74, 0x54, 0x6c, 0x73, 0x43, 0x6f, + 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x48, 0x00, + 0x52, 0x16, 0x67, 0x65, 0x74, 0x54, 0x6c, 0x73, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x12, 0x77, 0x0a, 0x21, 0x6f, 0x66, 0x66, 0x6c, + 0x6f, 0x61, 0x64, 0x5f, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x5f, 0x6b, 0x65, 0x79, 0x5f, + 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x71, 0x18, 0x04, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, + 0x76, 0x32, 0x2e, 0x4f, 0x66, 0x66, 0x6c, 0x6f, 0x61, 0x64, 0x50, 0x72, 0x69, 0x76, 0x61, 0x74, + 0x65, 0x4b, 0x65, 0x79, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, + 0x48, 0x00, 0x52, 0x1d, 0x6f, 0x66, 0x66, 0x6c, 0x6f, 0x61, 0x64, 0x50, 0x72, 0x69, 0x76, 0x61, + 0x74, 0x65, 0x4b, 0x65, 0x79, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, + 0x71, 0x12, 0x80, 0x01, 0x0a, 0x24, 0x6f, 0x66, 0x66, 0x6c, 0x6f, 0x61, 0x64, 0x5f, 0x72, 0x65, + 0x73, 0x75, 0x6d, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6b, 0x65, 0x79, 0x5f, 0x6f, 0x70, 0x65, + 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x71, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x2e, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, + 0x4f, 0x66, 0x66, 0x6c, 0x6f, 0x61, 0x64, 0x52, 0x65, 0x73, 0x75, 0x6d, 0x70, 0x74, 0x69, 0x6f, + 0x6e, 0x4b, 0x65, 0x79, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, + 0x48, 0x00, 0x52, 0x20, 0x6f, 0x66, 0x66, 0x6c, 0x6f, 0x61, 0x64, 0x52, 0x65, 0x73, 0x75, 0x6d, + 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x4b, 0x65, 0x79, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x52, 0x65, 0x71, 0x12, 0x7d, 0x0a, 0x23, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, + 0x5f, 0x70, 0x65, 0x65, 0x72, 0x5f, 0x63, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, + 0x65, 0x5f, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x72, 0x65, 0x71, 0x18, 0x06, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x2d, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, + 0x2e, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x50, 0x65, 0x65, 0x72, 0x43, 0x65, 0x72, + 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x52, 0x65, 0x71, + 0x48, 0x00, 0x52, 0x1f, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x50, 0x65, 0x65, 0x72, + 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x43, 0x68, 0x61, 0x69, 0x6e, + 0x52, 0x65, 0x71, 0x42, 0x0b, 0x0a, 0x09, 0x72, 0x65, 0x71, 0x5f, 0x6f, 0x6e, 0x65, 0x6f, 0x66, + 0x4a, 0x04, 0x08, 0x01, 0x10, 0x02, 0x22, 0xb4, 0x04, 0x0a, 0x0b, 0x53, 0x65, 0x73, 0x73, 0x69, + 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x12, 0x2c, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, + 0x61, 0x74, 0x75, 0x73, 0x12, 0x64, 0x0a, 0x1a, 0x67, 0x65, 0x74, 0x5f, 0x74, 0x6c, 0x73, 0x5f, + 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, + 0x73, 0x70, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x25, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x47, 0x65, 0x74, 0x54, 0x6c, 0x73, 0x43, 0x6f, + 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x48, + 0x00, 0x52, 0x17, 0x67, 0x65, 0x74, 0x54, 0x6c, 0x73, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, + 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x12, 0x7a, 0x0a, 0x22, 0x6f, 0x66, + 0x66, 0x6c, 0x6f, 0x61, 0x64, 0x5f, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x5f, 0x6b, 0x65, + 0x79, 0x5f, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x73, 0x70, + 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2c, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x4f, 0x66, 0x66, 0x6c, 0x6f, 0x61, 0x64, 0x50, 0x72, 0x69, + 0x76, 0x61, 0x74, 0x65, 0x4b, 0x65, 0x79, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x52, 0x65, 0x73, 0x70, 0x48, 0x00, 0x52, 0x1e, 0x6f, 0x66, 0x66, 0x6c, 0x6f, 0x61, 0x64, 0x50, + 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x4b, 0x65, 0x79, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x12, 0x83, 0x01, 0x0a, 0x25, 0x6f, 0x66, 0x66, 0x6c, 0x6f, + 0x61, 0x64, 0x5f, 0x72, 0x65, 0x73, 0x75, 0x6d, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6b, 0x65, + 0x79, 0x5f, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x73, 0x70, + 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x4f, 0x66, 0x66, 0x6c, 0x6f, 0x61, 0x64, 0x52, 0x65, 0x73, + 0x75, 0x6d, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x4b, 0x65, 0x79, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x48, 0x00, 0x52, 0x21, 0x6f, 0x66, 0x66, 0x6c, 0x6f, 0x61, 0x64, 0x52, 0x65, 0x73, 0x75, 0x6d, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x4b, 0x65, 0x79, 0x4f, - 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x12, 0x7d, 0x0a, 0x23, 0x76, - 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x5f, 0x63, 0x65, 0x72, - 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x5f, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x72, - 0x65, 0x71, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, - 0x50, 0x65, 0x65, 0x72, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x43, - 0x68, 0x61, 0x69, 0x6e, 0x52, 0x65, 0x71, 0x48, 0x00, 0x52, 0x1f, 0x76, 0x61, 0x6c, 0x69, 0x64, + 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x12, 0x80, 0x01, 0x0a, + 0x24, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x5f, 0x63, + 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x5f, 0x63, 0x68, 0x61, 0x69, 0x6e, + 0x5f, 0x72, 0x65, 0x73, 0x70, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2e, 0x2e, 0x73, 0x32, + 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x50, 0x65, 0x65, 0x72, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, - 0x74, 0x65, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x52, 0x65, 0x71, 0x42, 0x0b, 0x0a, 0x09, 0x72, 0x65, - 0x71, 0x5f, 0x6f, 0x6e, 0x65, 0x6f, 0x66, 0x4a, 0x04, 0x08, 0x01, 0x10, 0x02, 0x22, 0xb4, 0x04, - 0x0a, 0x0b, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x12, 0x2c, 0x0a, - 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, - 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x53, 0x74, 0x61, - 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x64, 0x0a, 0x1a, 0x67, - 0x65, 0x74, 0x5f, 0x74, 0x6c, 0x73, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x61, - 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x73, 0x70, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, - 0x25, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x47, - 0x65, 0x74, 0x54, 0x6c, 0x73, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x48, 0x00, 0x52, 0x17, 0x67, 0x65, 0x74, 0x54, 0x6c, 0x73, - 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, - 0x70, 0x12, 0x7a, 0x0a, 0x22, 0x6f, 0x66, 0x66, 0x6c, 0x6f, 0x61, 0x64, 0x5f, 0x70, 0x72, 0x69, - 0x76, 0x61, 0x74, 0x65, 0x5f, 0x6b, 0x65, 0x79, 0x5f, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x73, 0x70, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2c, 0x2e, - 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x4f, 0x66, 0x66, - 0x6c, 0x6f, 0x61, 0x64, 0x50, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x4b, 0x65, 0x79, 0x4f, 0x70, - 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x48, 0x00, 0x52, 0x1e, 0x6f, - 0x66, 0x66, 0x6c, 0x6f, 0x61, 0x64, 0x50, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x4b, 0x65, 0x79, - 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x12, 0x83, 0x01, - 0x0a, 0x25, 0x6f, 0x66, 0x66, 0x6c, 0x6f, 0x61, 0x64, 0x5f, 0x72, 0x65, 0x73, 0x75, 0x6d, 0x70, - 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6b, 0x65, 0x79, 0x5f, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x73, 0x70, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2f, 0x2e, - 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x4f, 0x66, 0x66, - 0x6c, 0x6f, 0x61, 0x64, 0x52, 0x65, 0x73, 0x75, 0x6d, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x4b, 0x65, - 0x79, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x48, 0x00, - 0x52, 0x21, 0x6f, 0x66, 0x66, 0x6c, 0x6f, 0x61, 0x64, 0x52, 0x65, 0x73, 0x75, 0x6d, 0x70, 0x74, - 0x69, 0x6f, 0x6e, 0x4b, 0x65, 0x79, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, - 0x65, 0x73, 0x70, 0x12, 0x80, 0x01, 0x0a, 0x24, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, - 0x5f, 0x70, 0x65, 0x65, 0x72, 0x5f, 0x63, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, - 0x65, 0x5f, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x72, 0x65, 0x73, 0x70, 0x18, 0x05, 0x20, 0x01, - 0x28, 0x0b, 0x32, 0x2e, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, - 0x32, 0x2e, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x50, 0x65, 0x65, 0x72, 0x43, 0x65, - 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x52, 0x65, - 0x73, 0x70, 0x48, 0x00, 0x52, 0x20, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x50, 0x65, - 0x65, 0x72, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x43, 0x68, 0x61, - 0x69, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x42, 0x0c, 0x0a, 0x0a, 0x72, 0x65, 0x73, 0x70, 0x5f, 0x6f, - 0x6e, 0x65, 0x6f, 0x66, 0x2a, 0xa2, 0x03, 0x0a, 0x12, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, - 0x72, 0x65, 0x41, 0x6c, 0x67, 0x6f, 0x72, 0x69, 0x74, 0x68, 0x6d, 0x12, 0x1c, 0x0a, 0x18, 0x53, - 0x32, 0x41, 0x5f, 0x53, 0x53, 0x4c, 0x5f, 0x53, 0x49, 0x47, 0x4e, 0x5f, 0x55, 0x4e, 0x53, 0x50, - 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x21, 0x0a, 0x1d, 0x53, 0x32, 0x41, - 0x5f, 0x53, 0x53, 0x4c, 0x5f, 0x53, 0x49, 0x47, 0x4e, 0x5f, 0x52, 0x53, 0x41, 0x5f, 0x50, 0x4b, - 0x43, 0x53, 0x31, 0x5f, 0x53, 0x48, 0x41, 0x32, 0x35, 0x36, 0x10, 0x01, 0x12, 0x21, 0x0a, 0x1d, - 0x53, 0x32, 0x41, 0x5f, 0x53, 0x53, 0x4c, 0x5f, 0x53, 0x49, 0x47, 0x4e, 0x5f, 0x52, 0x53, 0x41, - 0x5f, 0x50, 0x4b, 0x43, 0x53, 0x31, 0x5f, 0x53, 0x48, 0x41, 0x33, 0x38, 0x34, 0x10, 0x02, 0x12, - 0x21, 0x0a, 0x1d, 0x53, 0x32, 0x41, 0x5f, 0x53, 0x53, 0x4c, 0x5f, 0x53, 0x49, 0x47, 0x4e, 0x5f, - 0x52, 0x53, 0x41, 0x5f, 0x50, 0x4b, 0x43, 0x53, 0x31, 0x5f, 0x53, 0x48, 0x41, 0x35, 0x31, 0x32, - 0x10, 0x03, 0x12, 0x27, 0x0a, 0x23, 0x53, 0x32, 0x41, 0x5f, 0x53, 0x53, 0x4c, 0x5f, 0x53, 0x49, - 0x47, 0x4e, 0x5f, 0x45, 0x43, 0x44, 0x53, 0x41, 0x5f, 0x53, 0x45, 0x43, 0x50, 0x32, 0x35, 0x36, - 0x52, 0x31, 0x5f, 0x53, 0x48, 0x41, 0x32, 0x35, 0x36, 0x10, 0x04, 0x12, 0x27, 0x0a, 0x23, 0x53, + 0x74, 0x65, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x48, 0x00, 0x52, 0x20, 0x76, + 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x50, 0x65, 0x65, 0x72, 0x43, 0x65, 0x72, 0x74, 0x69, + 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x42, + 0x0c, 0x0a, 0x0a, 0x72, 0x65, 0x73, 0x70, 0x5f, 0x6f, 0x6e, 0x65, 0x6f, 0x66, 0x2a, 0xa2, 0x03, + 0x0a, 0x12, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x41, 0x6c, 0x67, 0x6f, 0x72, + 0x69, 0x74, 0x68, 0x6d, 0x12, 0x1c, 0x0a, 0x18, 0x53, 0x32, 0x41, 0x5f, 0x53, 0x53, 0x4c, 0x5f, + 0x53, 0x49, 0x47, 0x4e, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, + 0x10, 0x00, 0x12, 0x21, 0x0a, 0x1d, 0x53, 0x32, 0x41, 0x5f, 0x53, 0x53, 0x4c, 0x5f, 0x53, 0x49, + 0x47, 0x4e, 0x5f, 0x52, 0x53, 0x41, 0x5f, 0x50, 0x4b, 0x43, 0x53, 0x31, 0x5f, 0x53, 0x48, 0x41, + 0x32, 0x35, 0x36, 0x10, 0x01, 0x12, 0x21, 0x0a, 0x1d, 0x53, 0x32, 0x41, 0x5f, 0x53, 0x53, 0x4c, + 0x5f, 0x53, 0x49, 0x47, 0x4e, 0x5f, 0x52, 0x53, 0x41, 0x5f, 0x50, 0x4b, 0x43, 0x53, 0x31, 0x5f, + 0x53, 0x48, 0x41, 0x33, 0x38, 0x34, 0x10, 0x02, 0x12, 0x21, 0x0a, 0x1d, 0x53, 0x32, 0x41, 0x5f, + 0x53, 0x53, 0x4c, 0x5f, 0x53, 0x49, 0x47, 0x4e, 0x5f, 0x52, 0x53, 0x41, 0x5f, 0x50, 0x4b, 0x43, + 0x53, 0x31, 0x5f, 0x53, 0x48, 0x41, 0x35, 0x31, 0x32, 0x10, 0x03, 0x12, 0x27, 0x0a, 0x23, 0x53, 0x32, 0x41, 0x5f, 0x53, 0x53, 0x4c, 0x5f, 0x53, 0x49, 0x47, 0x4e, 0x5f, 0x45, 0x43, 0x44, 0x53, - 0x41, 0x5f, 0x53, 0x45, 0x43, 0x50, 0x33, 0x38, 0x34, 0x52, 0x31, 0x5f, 0x53, 0x48, 0x41, 0x33, - 0x38, 0x34, 0x10, 0x05, 0x12, 0x27, 0x0a, 0x23, 0x53, 0x32, 0x41, 0x5f, 0x53, 0x53, 0x4c, 0x5f, - 0x53, 0x49, 0x47, 0x4e, 0x5f, 0x45, 0x43, 0x44, 0x53, 0x41, 0x5f, 0x53, 0x45, 0x43, 0x50, 0x35, - 0x32, 0x31, 0x52, 0x31, 0x5f, 0x53, 0x48, 0x41, 0x35, 0x31, 0x32, 0x10, 0x06, 0x12, 0x24, 0x0a, - 0x20, 0x53, 0x32, 0x41, 0x5f, 0x53, 0x53, 0x4c, 0x5f, 0x53, 0x49, 0x47, 0x4e, 0x5f, 0x52, 0x53, - 0x41, 0x5f, 0x50, 0x53, 0x53, 0x5f, 0x52, 0x53, 0x41, 0x45, 0x5f, 0x53, 0x48, 0x41, 0x32, 0x35, - 0x36, 0x10, 0x07, 0x12, 0x24, 0x0a, 0x20, 0x53, 0x32, 0x41, 0x5f, 0x53, 0x53, 0x4c, 0x5f, 0x53, - 0x49, 0x47, 0x4e, 0x5f, 0x52, 0x53, 0x41, 0x5f, 0x50, 0x53, 0x53, 0x5f, 0x52, 0x53, 0x41, 0x45, - 0x5f, 0x53, 0x48, 0x41, 0x33, 0x38, 0x34, 0x10, 0x08, 0x12, 0x24, 0x0a, 0x20, 0x53, 0x32, 0x41, - 0x5f, 0x53, 0x53, 0x4c, 0x5f, 0x53, 0x49, 0x47, 0x4e, 0x5f, 0x52, 0x53, 0x41, 0x5f, 0x50, 0x53, - 0x53, 0x5f, 0x52, 0x53, 0x41, 0x45, 0x5f, 0x53, 0x48, 0x41, 0x35, 0x31, 0x32, 0x10, 0x09, 0x12, - 0x18, 0x0a, 0x14, 0x53, 0x32, 0x41, 0x5f, 0x53, 0x53, 0x4c, 0x5f, 0x53, 0x49, 0x47, 0x4e, 0x5f, - 0x45, 0x44, 0x32, 0x35, 0x35, 0x31, 0x39, 0x10, 0x0a, 0x32, 0x57, 0x0a, 0x0a, 0x53, 0x32, 0x41, - 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x49, 0x0a, 0x0c, 0x53, 0x65, 0x74, 0x55, 0x70, - 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x18, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, - 0x71, 0x1a, 0x19, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, - 0x2e, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, 0x28, 0x01, - 0x30, 0x01, 0x42, 0x36, 0x5a, 0x34, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, - 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x73, 0x32, 0x61, 0x2f, 0x69, 0x6e, 0x74, 0x65, - 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x76, 0x32, 0x2f, 0x73, 0x32, - 0x61, 0x5f, 0x67, 0x6f, 0x5f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x33, + 0x41, 0x5f, 0x53, 0x45, 0x43, 0x50, 0x32, 0x35, 0x36, 0x52, 0x31, 0x5f, 0x53, 0x48, 0x41, 0x32, + 0x35, 0x36, 0x10, 0x04, 0x12, 0x27, 0x0a, 0x23, 0x53, 0x32, 0x41, 0x5f, 0x53, 0x53, 0x4c, 0x5f, + 0x53, 0x49, 0x47, 0x4e, 0x5f, 0x45, 0x43, 0x44, 0x53, 0x41, 0x5f, 0x53, 0x45, 0x43, 0x50, 0x33, + 0x38, 0x34, 0x52, 0x31, 0x5f, 0x53, 0x48, 0x41, 0x33, 0x38, 0x34, 0x10, 0x05, 0x12, 0x27, 0x0a, + 0x23, 0x53, 0x32, 0x41, 0x5f, 0x53, 0x53, 0x4c, 0x5f, 0x53, 0x49, 0x47, 0x4e, 0x5f, 0x45, 0x43, + 0x44, 0x53, 0x41, 0x5f, 0x53, 0x45, 0x43, 0x50, 0x35, 0x32, 0x31, 0x52, 0x31, 0x5f, 0x53, 0x48, + 0x41, 0x35, 0x31, 0x32, 0x10, 0x06, 0x12, 0x24, 0x0a, 0x20, 0x53, 0x32, 0x41, 0x5f, 0x53, 0x53, + 0x4c, 0x5f, 0x53, 0x49, 0x47, 0x4e, 0x5f, 0x52, 0x53, 0x41, 0x5f, 0x50, 0x53, 0x53, 0x5f, 0x52, + 0x53, 0x41, 0x45, 0x5f, 0x53, 0x48, 0x41, 0x32, 0x35, 0x36, 0x10, 0x07, 0x12, 0x24, 0x0a, 0x20, + 0x53, 0x32, 0x41, 0x5f, 0x53, 0x53, 0x4c, 0x5f, 0x53, 0x49, 0x47, 0x4e, 0x5f, 0x52, 0x53, 0x41, + 0x5f, 0x50, 0x53, 0x53, 0x5f, 0x52, 0x53, 0x41, 0x45, 0x5f, 0x53, 0x48, 0x41, 0x33, 0x38, 0x34, + 0x10, 0x08, 0x12, 0x24, 0x0a, 0x20, 0x53, 0x32, 0x41, 0x5f, 0x53, 0x53, 0x4c, 0x5f, 0x53, 0x49, + 0x47, 0x4e, 0x5f, 0x52, 0x53, 0x41, 0x5f, 0x50, 0x53, 0x53, 0x5f, 0x52, 0x53, 0x41, 0x45, 0x5f, + 0x53, 0x48, 0x41, 0x35, 0x31, 0x32, 0x10, 0x09, 0x12, 0x18, 0x0a, 0x14, 0x53, 0x32, 0x41, 0x5f, + 0x53, 0x53, 0x4c, 0x5f, 0x53, 0x49, 0x47, 0x4e, 0x5f, 0x45, 0x44, 0x32, 0x35, 0x35, 0x31, 0x39, + 0x10, 0x0a, 0x32, 0x57, 0x0a, 0x0a, 0x53, 0x32, 0x41, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, + 0x12, 0x49, 0x0a, 0x0c, 0x53, 0x65, 0x74, 0x55, 0x70, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, + 0x12, 0x18, 0x2e, 0x73, 0x32, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, + 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x1a, 0x19, 0x2e, 0x73, 0x32, 0x61, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, + 0x6e, 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, 0x28, 0x01, 0x30, 0x01, 0x42, 0x36, 0x5a, 0x34, 0x67, + 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2f, 0x73, 0x32, 0x61, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x2f, 0x76, 0x32, 0x2f, 0x73, 0x32, 0x61, 0x5f, 0x67, 0x6f, 0x5f, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/google/s2a-go/internal/v2/s2av2.go b/vendor/github.com/google/s2a-go/internal/v2/s2av2.go index a6402ee48c..0cc78547e9 100644 --- a/vendor/github.com/google/s2a-go/internal/v2/s2av2.go +++ b/vendor/github.com/google/s2a-go/internal/v2/s2av2.go @@ -64,13 +64,13 @@ type s2av2TransportCreds struct { localIdentities []*commonpb.Identity verificationMode s2av2pb.ValidatePeerCertificateChainReq_VerificationMode fallbackClientHandshake fallback.ClientHandshake - getS2AStream func(ctx context.Context, s2av2Address string) (stream.S2AStream, error) + getS2AStream stream.GetS2AStream serverAuthorizationPolicy []byte } // NewClientCreds returns a client-side transport credentials object that uses // the S2Av2 to establish a secure connection with a server. -func NewClientCreds(s2av2Address string, transportCreds credentials.TransportCredentials, localIdentity *commonpb.Identity, verificationMode s2av2pb.ValidatePeerCertificateChainReq_VerificationMode, fallbackClientHandshakeFunc fallback.ClientHandshake, getS2AStream func(ctx context.Context, s2av2Address string) (stream.S2AStream, error), serverAuthorizationPolicy []byte) (credentials.TransportCredentials, error) { +func NewClientCreds(s2av2Address string, transportCreds credentials.TransportCredentials, localIdentity *commonpb.Identity, verificationMode s2av2pb.ValidatePeerCertificateChainReq_VerificationMode, fallbackClientHandshakeFunc fallback.ClientHandshake, getS2AStream stream.GetS2AStream, serverAuthorizationPolicy []byte) (credentials.TransportCredentials, error) { // Create an AccessTokenManager instance to use to authenticate to S2Av2. accessTokenManager, err := tokenmanager.NewSingleTokenAccessTokenManager() @@ -101,7 +101,7 @@ func NewClientCreds(s2av2Address string, transportCreds credentials.TransportCre // NewServerCreds returns a server-side transport credentials object that uses // the S2Av2 to establish a secure connection with a client. -func NewServerCreds(s2av2Address string, transportCreds credentials.TransportCredentials, localIdentities []*commonpb.Identity, verificationMode s2av2pb.ValidatePeerCertificateChainReq_VerificationMode, getS2AStream func(ctx context.Context, s2av2Address string) (stream.S2AStream, error)) (credentials.TransportCredentials, error) { +func NewServerCreds(s2av2Address string, transportCreds credentials.TransportCredentials, localIdentities []*commonpb.Identity, verificationMode s2av2pb.ValidatePeerCertificateChainReq_VerificationMode, getS2AStream stream.GetS2AStream) (credentials.TransportCredentials, error) { // Create an AccessTokenManager instance to use to authenticate to S2Av2. accessTokenManager, err := tokenmanager.NewSingleTokenAccessTokenManager() creds := &s2av2TransportCreds{ @@ -306,8 +306,9 @@ func NewClientTLSConfig( tokenManager tokenmanager.AccessTokenManager, verificationMode s2av2pb.ValidatePeerCertificateChainReq_VerificationMode, serverName string, - serverAuthorizationPolicy []byte) (*tls.Config, error) { - s2AStream, err := createStream(ctx, s2av2Address, transportCreds, nil) + serverAuthorizationPolicy []byte, + getStream stream.GetS2AStream) (*tls.Config, error) { + s2AStream, err := createStream(ctx, s2av2Address, transportCreds, getStream) if err != nil { grpclog.Infof("Failed to connect to S2Av2: %v", err) return nil, err @@ -350,7 +351,7 @@ func (x s2AGrpcStream) CloseSend() error { return x.stream.CloseSend() } -func createStream(ctx context.Context, s2av2Address string, transportCreds credentials.TransportCredentials, getS2AStream func(ctx context.Context, s2av2Address string) (stream.S2AStream, error)) (stream.S2AStream, error) { +func createStream(ctx context.Context, s2av2Address string, transportCreds credentials.TransportCredentials, getS2AStream stream.GetS2AStream) (stream.S2AStream, error) { if getS2AStream != nil { return getS2AStream(ctx, s2av2Address) } diff --git a/vendor/github.com/google/s2a-go/internal/v2/tlsconfigstore/tlsconfigstore.go b/vendor/github.com/google/s2a-go/internal/v2/tlsconfigstore/tlsconfigstore.go index fa0002e36b..6ca75f5608 100644 --- a/vendor/github.com/google/s2a-go/internal/v2/tlsconfigstore/tlsconfigstore.go +++ b/vendor/github.com/google/s2a-go/internal/v2/tlsconfigstore/tlsconfigstore.go @@ -75,7 +75,7 @@ func GetTLSConfigurationForClient(serverHostname string, s2AStream stream.S2AStr return nil, fmt.Errorf("failed to get TLS configuration from S2A: %d, %v", resp.GetStatus().Code, resp.GetStatus().Details) } - // Extract TLS configiguration from SessionResp. + // Extract TLS configuration from SessionResp. tlsConfig := resp.GetGetTlsConfigurationResp().GetClientTlsConfiguration() var cert tls.Certificate diff --git a/vendor/github.com/google/s2a-go/s2a.go b/vendor/github.com/google/s2a-go/s2a.go index cc79bd09a6..c52fccddf8 100644 --- a/vendor/github.com/google/s2a-go/s2a.go +++ b/vendor/github.com/google/s2a-go/s2a.go @@ -35,6 +35,7 @@ import ( "github.com/google/s2a-go/internal/tokenmanager" "github.com/google/s2a-go/internal/v2" "github.com/google/s2a-go/retry" + "github.com/google/s2a-go/stream" "google.golang.org/grpc/credentials" "google.golang.org/grpc/grpclog" "google.golang.org/protobuf/proto" @@ -330,6 +331,7 @@ func NewTLSClientConfigFactory(opts *ClientOptions) (TLSClientConfigFactory, err tokenManager: nil, verificationMode: getVerificationMode(opts.VerificationMode), serverAuthorizationPolicy: opts.serverAuthorizationPolicy, + getStream: opts.getS2AStream, }, nil } return &s2aTLSClientConfigFactory{ @@ -338,6 +340,7 @@ func NewTLSClientConfigFactory(opts *ClientOptions) (TLSClientConfigFactory, err tokenManager: tokenManager, verificationMode: getVerificationMode(opts.VerificationMode), serverAuthorizationPolicy: opts.serverAuthorizationPolicy, + getStream: opts.getS2AStream, }, nil } @@ -347,6 +350,7 @@ type s2aTLSClientConfigFactory struct { tokenManager tokenmanager.AccessTokenManager verificationMode s2av2pb.ValidatePeerCertificateChainReq_VerificationMode serverAuthorizationPolicy []byte + getStream stream.GetS2AStream } func (f *s2aTLSClientConfigFactory) Build( @@ -355,7 +359,7 @@ func (f *s2aTLSClientConfigFactory) Build( if opts != nil && opts.ServerName != "" { serverName = opts.ServerName } - return v2.NewClientTLSConfig(ctx, f.s2av2Address, f.transportCreds, f.tokenManager, f.verificationMode, serverName, f.serverAuthorizationPolicy) + return v2.NewClientTLSConfig(ctx, f.s2av2Address, f.transportCreds, f.tokenManager, f.verificationMode, serverName, f.serverAuthorizationPolicy, f.getStream) } func getVerificationMode(verificationMode VerificationModeType) s2av2pb.ValidatePeerCertificateChainReq_VerificationMode { @@ -370,6 +374,8 @@ func getVerificationMode(verificationMode VerificationModeType) s2av2pb.Validate return s2av2pb.ValidatePeerCertificateChainReq_RESERVED_CUSTOM_VERIFICATION_MODE_4 case ReservedCustomVerificationMode5: return s2av2pb.ValidatePeerCertificateChainReq_RESERVED_CUSTOM_VERIFICATION_MODE_5 + case ReservedCustomVerificationMode6: + return s2av2pb.ValidatePeerCertificateChainReq_RESERVED_CUSTOM_VERIFICATION_MODE_6 default: return s2av2pb.ValidatePeerCertificateChainReq_UNSPECIFIED } diff --git a/vendor/github.com/google/s2a-go/s2a_options.go b/vendor/github.com/google/s2a-go/s2a_options.go index 5bbf31bf41..b7a277f9e3 100644 --- a/vendor/github.com/google/s2a-go/s2a_options.go +++ b/vendor/github.com/google/s2a-go/s2a_options.go @@ -19,7 +19,6 @@ package s2a import ( - "context" "crypto/tls" "errors" "sync" @@ -28,7 +27,7 @@ import ( "github.com/google/s2a-go/stream" "google.golang.org/grpc/credentials" - s2apbv1 "github.com/google/s2a-go/internal/proto/common_go_proto" + s2av1pb "github.com/google/s2a-go/internal/proto/common_go_proto" s2apb "github.com/google/s2a-go/internal/proto/v2/common_go_proto" ) @@ -36,6 +35,17 @@ import ( type Identity interface { // Name returns the name of the identity. Name() string + Attributes() map[string]string +} + +type UnspecifiedID struct { + Attr map[string]string +} + +func (u *UnspecifiedID) Name() string { return "" } + +func (u *UnspecifiedID) Attributes() map[string]string { + return u.Attr } type spiffeID struct { @@ -44,10 +54,10 @@ type spiffeID struct { func (s *spiffeID) Name() string { return s.spiffeID } +func (spiffeID) Attributes() map[string]string { return nil } + // NewSpiffeID creates a SPIFFE ID from id. -func NewSpiffeID(id string) Identity { - return &spiffeID{spiffeID: id} -} +func NewSpiffeID(id string) Identity { return &spiffeID{spiffeID: id} } type hostname struct { hostname string @@ -55,10 +65,10 @@ type hostname struct { func (h *hostname) Name() string { return h.hostname } +func (hostname) Attributes() map[string]string { return nil } + // NewHostname creates a hostname from name. -func NewHostname(name string) Identity { - return &hostname{hostname: name} -} +func NewHostname(name string) Identity { return &hostname{hostname: name} } type uid struct { uid string @@ -66,10 +76,10 @@ type uid struct { func (h *uid) Name() string { return h.uid } +func (uid) Attributes() map[string]string { return nil } + // NewUID creates a UID from name. -func NewUID(name string) Identity { - return &uid{uid: name} -} +func NewUID(name string) Identity { return &uid{uid: name} } // VerificationModeType specifies the mode that S2A must use to verify the peer // certificate chain. @@ -83,6 +93,7 @@ const ( ReservedCustomVerificationMode3 ReservedCustomVerificationMode4 ReservedCustomVerificationMode5 + ReservedCustomVerificationMode6 ) // ClientOptions contains the client-side options used to establish a secure @@ -137,7 +148,7 @@ type ClientOptions struct { FallbackOpts *FallbackOptions // Generates an S2AStream interface for talking to the S2A server. - getS2AStream func(ctx context.Context, s2av2Address string) (stream.S2AStream, error) + getS2AStream stream.GetS2AStream // Serialized user specified policy for server authorization. serverAuthorizationPolicy []byte @@ -191,7 +202,7 @@ type ServerOptions struct { VerificationMode VerificationModeType // Generates an S2AStream interface for talking to the S2A server. - getS2AStream func(ctx context.Context, s2av2Address string) (stream.S2AStream, error) + getS2AStream stream.GetS2AStream } // DefaultServerOptions returns the default server options. @@ -202,17 +213,30 @@ func DefaultServerOptions(s2aAddress string) *ServerOptions { } } -func toProtoIdentity(identity Identity) (*s2apbv1.Identity, error) { +func toProtoIdentity(identity Identity) (*s2av1pb.Identity, error) { if identity == nil { return nil, nil } switch id := identity.(type) { case *spiffeID: - return &s2apbv1.Identity{IdentityOneof: &s2apbv1.Identity_SpiffeId{SpiffeId: id.Name()}}, nil + return &s2av1pb.Identity{ + IdentityOneof: &s2av1pb.Identity_SpiffeId{SpiffeId: id.Name()}, + Attributes: id.Attributes(), + }, nil case *hostname: - return &s2apbv1.Identity{IdentityOneof: &s2apbv1.Identity_Hostname{Hostname: id.Name()}}, nil + return &s2av1pb.Identity{ + IdentityOneof: &s2av1pb.Identity_Hostname{Hostname: id.Name()}, + Attributes: id.Attributes(), + }, nil case *uid: - return &s2apbv1.Identity{IdentityOneof: &s2apbv1.Identity_Uid{Uid: id.Name()}}, nil + return &s2av1pb.Identity{ + IdentityOneof: &s2av1pb.Identity_Uid{Uid: id.Name()}, + Attributes: id.Attributes(), + }, nil + case *UnspecifiedID: + return &s2av1pb.Identity{ + Attributes: id.Attributes(), + }, nil default: return nil, errors.New("unrecognized identity type") } @@ -224,11 +248,24 @@ func toV2ProtoIdentity(identity Identity) (*s2apb.Identity, error) { } switch id := identity.(type) { case *spiffeID: - return &s2apb.Identity{IdentityOneof: &s2apb.Identity_SpiffeId{SpiffeId: id.Name()}}, nil + return &s2apb.Identity{ + IdentityOneof: &s2apb.Identity_SpiffeId{SpiffeId: id.Name()}, + Attributes: id.Attributes(), + }, nil case *hostname: - return &s2apb.Identity{IdentityOneof: &s2apb.Identity_Hostname{Hostname: id.Name()}}, nil + return &s2apb.Identity{ + IdentityOneof: &s2apb.Identity_Hostname{Hostname: id.Name()}, + Attributes: id.Attributes(), + }, nil case *uid: - return &s2apb.Identity{IdentityOneof: &s2apb.Identity_Uid{Uid: id.Name()}}, nil + return &s2apb.Identity{ + IdentityOneof: &s2apb.Identity_Uid{Uid: id.Name()}, + Attributes: id.Attributes(), + }, nil + case *UnspecifiedID: + return &s2apb.Identity{ + Attributes: id.Attributes(), + }, nil default: return nil, errors.New("unrecognized identity type") } diff --git a/vendor/github.com/google/s2a-go/stream/s2a_stream.go b/vendor/github.com/google/s2a-go/stream/s2a_stream.go index 584bf32b1c..ae2d5eb4c1 100644 --- a/vendor/github.com/google/s2a-go/stream/s2a_stream.go +++ b/vendor/github.com/google/s2a-go/stream/s2a_stream.go @@ -20,6 +20,8 @@ package stream import ( + "context" + s2av2pb "github.com/google/s2a-go/internal/proto/v2/s2a_go_proto" ) @@ -32,3 +34,6 @@ type S2AStream interface { // Closes the channel to the S2A server. CloseSend() error } + +// GetS2AStream type is for generating an S2AStream interface for talking to the S2A server. +type GetS2AStream func(ctx context.Context, s2av2Address string, opts ...string) (S2AStream, error) diff --git a/vendor/github.com/jmespath/go-jmespath/.gitignore b/vendor/github.com/jmespath/go-jmespath/.gitignore deleted file mode 100644 index 5091fb0736..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -/jpgo -jmespath-fuzz.zip -cpu.out -go-jmespath.test diff --git a/vendor/github.com/jmespath/go-jmespath/.golangci.yml b/vendor/github.com/jmespath/go-jmespath/.golangci.yml deleted file mode 100644 index 6a2d4f8770..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/.golangci.yml +++ /dev/null @@ -1,3 +0,0 @@ -linters: - disable: - - structcheck diff --git a/vendor/github.com/jmespath/go-jmespath/LICENSE b/vendor/github.com/jmespath/go-jmespath/LICENSE deleted file mode 100644 index d645695673..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/jmespath/go-jmespath/Makefile b/vendor/github.com/jmespath/go-jmespath/Makefile deleted file mode 100644 index 97081e417e..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/Makefile +++ /dev/null @@ -1,48 +0,0 @@ - -CMD = jpgo - -SRC_PKGS=./ ./cmd/... ./fuzz/... - -help: - @echo "Please use \`make ' where is one of" - @echo " test to run all the tests" - @echo " build to build the library and jp executable" - @echo " generate to run codegen" - - -generate: - go generate ${SRC_PKGS} - -build: - rm -f $(CMD) - go build ${SRC_PKGS} - rm -f cmd/$(CMD)/$(CMD) && cd cmd/$(CMD)/ && go build ./... - mv cmd/$(CMD)/$(CMD) . - -test: build - go test -v ${SRC_PKGS} - -check: - go vet ${SRC_PKGS} - golint ${SRC_PKGS} - golangci-lint run - -htmlc: - go test -coverprofile="/tmp/jpcov" && go tool cover -html="/tmp/jpcov" && unlink /tmp/jpcov - -buildfuzz: - go-fuzz-build github.com/jmespath/go-jmespath/fuzz - -fuzz: buildfuzz - go-fuzz -bin=./jmespath-fuzz.zip -workdir=fuzz/testdata - -bench: - go test -bench . -cpuprofile cpu.out - -pprof-cpu: - go tool pprof ./go-jmespath.test ./cpu.out - -install-dev-cmds: - go install golang.org/x/lint/golint@latest - go install golang.org/x/tools/cmd/stringer@latest - command -v golangci-lint || { curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $$(go env GOPATH)/bin v1.46.2; } diff --git a/vendor/github.com/jmespath/go-jmespath/NOTICE b/vendor/github.com/jmespath/go-jmespath/NOTICE deleted file mode 100644 index c00cc539b0..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/NOTICE +++ /dev/null @@ -1,2 +0,0 @@ -go-jmespath -Copyright 2015 James Saryerwinnie diff --git a/vendor/github.com/jmespath/go-jmespath/README.md b/vendor/github.com/jmespath/go-jmespath/README.md deleted file mode 100644 index 110ad79997..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/README.md +++ /dev/null @@ -1,87 +0,0 @@ -# go-jmespath - A JMESPath implementation in Go - -[![Build Status](https://img.shields.io/travis/jmespath/go-jmespath.svg)](https://travis-ci.org/jmespath/go-jmespath) - - - -go-jmespath is a GO implementation of JMESPath, -which is a query language for JSON. It will take a JSON -document and transform it into another JSON document -through a JMESPath expression. - -Using go-jmespath is really easy. There's a single function -you use, `jmespath.search`: - - -```go -> import "github.com/jmespath/go-jmespath" -> -> var jsondata = []byte(`{"foo": {"bar": {"baz": [0, 1, 2, 3, 4]}}}`) // your data -> var data interface{} -> err := json.Unmarshal(jsondata, &data) -> result, err := jmespath.Search("foo.bar.baz[2]", data) -result = 2 -``` - -In the example we gave the ``search`` function input data of -`{"foo": {"bar": {"baz": [0, 1, 2, 3, 4]}}}` as well as the JMESPath -expression `foo.bar.baz[2]`, and the `search` function evaluated -the expression against the input data to produce the result ``2``. - -The JMESPath language can do a lot more than select an element -from a list. Here are a few more examples: - -```go -> var jsondata = []byte(`{"foo": {"bar": {"baz": [0, 1, 2, 3, 4]}}}`) // your data -> var data interface{} -> err := json.Unmarshal(jsondata, &data) -> result, err := jmespath.search("foo.bar", data) -result = { "baz": [ 0, 1, 2, 3, 4 ] } - - -> var jsondata = []byte(`{"foo": [{"first": "a", "last": "b"}, - {"first": "c", "last": "d"}]}`) // your data -> var data interface{} -> err := json.Unmarshal(jsondata, &data) -> result, err := jmespath.search({"foo[*].first", data) -result [ 'a', 'c' ] - - -> var jsondata = []byte(`{"foo": [{"age": 20}, {"age": 25}, - {"age": 30}, {"age": 35}, - {"age": 40}]}`) // your data -> var data interface{} -> err := json.Unmarshal(jsondata, &data) -> result, err := jmespath.search("foo[?age > `30`]") -result = [ { age: 35 }, { age: 40 } ] -``` - -You can also pre-compile your query. This is usefull if -you are going to run multiple searches with it: - -```go - > var jsondata = []byte(`{"foo": "bar"}`) - > var data interface{} - > err := json.Unmarshal(jsondata, &data) - > precompiled, err := Compile("foo") - > if err != nil{ - > // ... handle the error - > } - > result, err := precompiled.Search(data) - result = "bar" -``` - -## More Resources - -The example above only show a small amount of what -a JMESPath expression can do. If you want to take a -tour of the language, the *best* place to go is the -[JMESPath Tutorial](http://jmespath.org/tutorial.html). - -One of the best things about JMESPath is that it is -implemented in many different programming languages including -python, ruby, php, lua, etc. To see a complete list of libraries, -check out the [JMESPath libraries page](http://jmespath.org/libraries.html). - -And finally, the full JMESPath specification can be found -on the [JMESPath site](http://jmespath.org/specification.html). diff --git a/vendor/github.com/jmespath/go-jmespath/api.go b/vendor/github.com/jmespath/go-jmespath/api.go deleted file mode 100644 index 010efe9bfb..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/api.go +++ /dev/null @@ -1,49 +0,0 @@ -package jmespath - -import "strconv" - -// JMESPath is the representation of a compiled JMES path query. A JMESPath is -// safe for concurrent use by multiple goroutines. -type JMESPath struct { - ast ASTNode - intr *treeInterpreter -} - -// Compile parses a JMESPath expression and returns, if successful, a JMESPath -// object that can be used to match against data. -func Compile(expression string) (*JMESPath, error) { - parser := NewParser() - ast, err := parser.Parse(expression) - if err != nil { - return nil, err - } - jmespath := &JMESPath{ast: ast, intr: newInterpreter()} - return jmespath, nil -} - -// MustCompile is like Compile but panics if the expression cannot be parsed. -// It simplifies safe initialization of global variables holding compiled -// JMESPaths. -func MustCompile(expression string) *JMESPath { - jmespath, err := Compile(expression) - if err != nil { - panic(`jmespath: Compile(` + strconv.Quote(expression) + `): ` + err.Error()) - } - return jmespath -} - -// Search evaluates a JMESPath expression against input data and returns the result. -func (jp *JMESPath) Search(data interface{}) (interface{}, error) { - return jp.intr.Execute(jp.ast, data) -} - -// Search evaluates a JMESPath expression against input data and returns the result. -func Search(expression string, data interface{}) (interface{}, error) { - intr := newInterpreter() - parser := NewParser() - ast, err := parser.Parse(expression) - if err != nil { - return nil, err - } - return intr.Execute(ast, data) -} diff --git a/vendor/github.com/jmespath/go-jmespath/astnodetype_string.go b/vendor/github.com/jmespath/go-jmespath/astnodetype_string.go deleted file mode 100644 index 9a41dadb9e..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/astnodetype_string.go +++ /dev/null @@ -1,45 +0,0 @@ -// Code generated by "stringer -type astNodeType"; DO NOT EDIT. - -package jmespath - -import "strconv" - -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[ASTEmpty-0] - _ = x[ASTComparator-1] - _ = x[ASTCurrentNode-2] - _ = x[ASTExpRef-3] - _ = x[ASTFunctionExpression-4] - _ = x[ASTField-5] - _ = x[ASTFilterProjection-6] - _ = x[ASTFlatten-7] - _ = x[ASTIdentity-8] - _ = x[ASTIndex-9] - _ = x[ASTIndexExpression-10] - _ = x[ASTKeyValPair-11] - _ = x[ASTLiteral-12] - _ = x[ASTMultiSelectHash-13] - _ = x[ASTMultiSelectList-14] - _ = x[ASTOrExpression-15] - _ = x[ASTAndExpression-16] - _ = x[ASTNotExpression-17] - _ = x[ASTPipe-18] - _ = x[ASTProjection-19] - _ = x[ASTSubexpression-20] - _ = x[ASTSlice-21] - _ = x[ASTValueProjection-22] -} - -const _astNodeType_name = "ASTEmptyASTComparatorASTCurrentNodeASTExpRefASTFunctionExpressionASTFieldASTFilterProjectionASTFlattenASTIdentityASTIndexASTIndexExpressionASTKeyValPairASTLiteralASTMultiSelectHashASTMultiSelectListASTOrExpressionASTAndExpressionASTNotExpressionASTPipeASTProjectionASTSubexpressionASTSliceASTValueProjection" - -var _astNodeType_index = [...]uint16{0, 8, 21, 35, 44, 65, 73, 92, 102, 113, 121, 139, 152, 162, 180, 198, 213, 229, 245, 252, 265, 281, 289, 307} - -func (i astNodeType) String() string { - if i < 0 || i >= astNodeType(len(_astNodeType_index)-1) { - return "astNodeType(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _astNodeType_name[_astNodeType_index[i]:_astNodeType_index[i+1]] -} diff --git a/vendor/github.com/jmespath/go-jmespath/functions.go b/vendor/github.com/jmespath/go-jmespath/functions.go deleted file mode 100644 index e9770e84ac..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/functions.go +++ /dev/null @@ -1,841 +0,0 @@ -package jmespath - -import ( - "encoding/json" - "errors" - "fmt" - "math" - "reflect" - "sort" - "strconv" - "strings" - "unicode/utf8" -) - -type jpFunction func(arguments []interface{}) (interface{}, error) - -type jpType string - -const ( - jpNumber jpType = "number" - jpString jpType = "string" - jpArray jpType = "array" - jpObject jpType = "object" - jpArrayNumber jpType = "array[number]" - jpArrayString jpType = "array[string]" - jpExpref jpType = "expref" - jpAny jpType = "any" -) - -type functionEntry struct { - name string - arguments []argSpec - handler jpFunction - hasExpRef bool -} - -type argSpec struct { - types []jpType - variadic bool -} - -type byExprString struct { - intr *treeInterpreter - node ASTNode - items []interface{} - hasError bool -} - -func (a *byExprString) Len() int { - return len(a.items) -} -func (a *byExprString) Swap(i, j int) { - a.items[i], a.items[j] = a.items[j], a.items[i] -} -func (a *byExprString) Less(i, j int) bool { - first, err := a.intr.Execute(a.node, a.items[i]) - if err != nil { - a.hasError = true - // Return a dummy value. - return true - } - ith, ok := first.(string) - if !ok { - a.hasError = true - return true - } - second, err := a.intr.Execute(a.node, a.items[j]) - if err != nil { - a.hasError = true - // Return a dummy value. - return true - } - jth, ok := second.(string) - if !ok { - a.hasError = true - return true - } - return ith < jth -} - -type byExprFloat struct { - intr *treeInterpreter - node ASTNode - items []interface{} - hasError bool -} - -func (a *byExprFloat) Len() int { - return len(a.items) -} -func (a *byExprFloat) Swap(i, j int) { - a.items[i], a.items[j] = a.items[j], a.items[i] -} -func (a *byExprFloat) Less(i, j int) bool { - first, err := a.intr.Execute(a.node, a.items[i]) - if err != nil { - a.hasError = true - // Return a dummy value. - return true - } - ith, ok := first.(float64) - if !ok { - a.hasError = true - return true - } - second, err := a.intr.Execute(a.node, a.items[j]) - if err != nil { - a.hasError = true - // Return a dummy value. - return true - } - jth, ok := second.(float64) - if !ok { - a.hasError = true - return true - } - return ith < jth -} - -type functionCaller struct { - functionTable map[string]functionEntry -} - -func newFunctionCaller() *functionCaller { - caller := &functionCaller{} - caller.functionTable = map[string]functionEntry{ - "length": { - name: "length", - arguments: []argSpec{ - {types: []jpType{jpString, jpArray, jpObject}}, - }, - handler: jpfLength, - }, - "starts_with": { - name: "starts_with", - arguments: []argSpec{ - {types: []jpType{jpString}}, - {types: []jpType{jpString}}, - }, - handler: jpfStartsWith, - }, - "abs": { - name: "abs", - arguments: []argSpec{ - {types: []jpType{jpNumber}}, - }, - handler: jpfAbs, - }, - "avg": { - name: "avg", - arguments: []argSpec{ - {types: []jpType{jpArrayNumber}}, - }, - handler: jpfAvg, - }, - "ceil": { - name: "ceil", - arguments: []argSpec{ - {types: []jpType{jpNumber}}, - }, - handler: jpfCeil, - }, - "contains": { - name: "contains", - arguments: []argSpec{ - {types: []jpType{jpArray, jpString}}, - {types: []jpType{jpAny}}, - }, - handler: jpfContains, - }, - "ends_with": { - name: "ends_with", - arguments: []argSpec{ - {types: []jpType{jpString}}, - {types: []jpType{jpString}}, - }, - handler: jpfEndsWith, - }, - "floor": { - name: "floor", - arguments: []argSpec{ - {types: []jpType{jpNumber}}, - }, - handler: jpfFloor, - }, - "map": { - name: "amp", - arguments: []argSpec{ - {types: []jpType{jpExpref}}, - {types: []jpType{jpArray}}, - }, - handler: jpfMap, - hasExpRef: true, - }, - "max": { - name: "max", - arguments: []argSpec{ - {types: []jpType{jpArrayNumber, jpArrayString}}, - }, - handler: jpfMax, - }, - "merge": { - name: "merge", - arguments: []argSpec{ - {types: []jpType{jpObject}, variadic: true}, - }, - handler: jpfMerge, - }, - "max_by": { - name: "max_by", - arguments: []argSpec{ - {types: []jpType{jpArray}}, - {types: []jpType{jpExpref}}, - }, - handler: jpfMaxBy, - hasExpRef: true, - }, - "sum": { - name: "sum", - arguments: []argSpec{ - {types: []jpType{jpArrayNumber}}, - }, - handler: jpfSum, - }, - "min": { - name: "min", - arguments: []argSpec{ - {types: []jpType{jpArrayNumber, jpArrayString}}, - }, - handler: jpfMin, - }, - "min_by": { - name: "min_by", - arguments: []argSpec{ - {types: []jpType{jpArray}}, - {types: []jpType{jpExpref}}, - }, - handler: jpfMinBy, - hasExpRef: true, - }, - "type": { - name: "type", - arguments: []argSpec{ - {types: []jpType{jpAny}}, - }, - handler: jpfType, - }, - "keys": { - name: "keys", - arguments: []argSpec{ - {types: []jpType{jpObject}}, - }, - handler: jpfKeys, - }, - "values": { - name: "values", - arguments: []argSpec{ - {types: []jpType{jpObject}}, - }, - handler: jpfValues, - }, - "sort": { - name: "sort", - arguments: []argSpec{ - {types: []jpType{jpArrayString, jpArrayNumber}}, - }, - handler: jpfSort, - }, - "sort_by": { - name: "sort_by", - arguments: []argSpec{ - {types: []jpType{jpArray}}, - {types: []jpType{jpExpref}}, - }, - handler: jpfSortBy, - hasExpRef: true, - }, - "join": { - name: "join", - arguments: []argSpec{ - {types: []jpType{jpString}}, - {types: []jpType{jpArrayString}}, - }, - handler: jpfJoin, - }, - "reverse": { - name: "reverse", - arguments: []argSpec{ - {types: []jpType{jpArray, jpString}}, - }, - handler: jpfReverse, - }, - "to_array": { - name: "to_array", - arguments: []argSpec{ - {types: []jpType{jpAny}}, - }, - handler: jpfToArray, - }, - "to_string": { - name: "to_string", - arguments: []argSpec{ - {types: []jpType{jpAny}}, - }, - handler: jpfToString, - }, - "to_number": { - name: "to_number", - arguments: []argSpec{ - {types: []jpType{jpAny}}, - }, - handler: jpfToNumber, - }, - "not_null": { - name: "not_null", - arguments: []argSpec{ - {types: []jpType{jpAny}, variadic: true}, - }, - handler: jpfNotNull, - }, - } - return caller -} - -func (e *functionEntry) resolveArgs(arguments []interface{}) ([]interface{}, error) { - if len(e.arguments) == 0 { - return arguments, nil - } - if !e.arguments[len(e.arguments)-1].variadic { - if len(e.arguments) != len(arguments) { - return nil, errors.New("incorrect number of args") - } - for i, spec := range e.arguments { - userArg := arguments[i] - err := spec.typeCheck(userArg) - if err != nil { - return nil, err - } - } - return arguments, nil - } - if len(arguments) < len(e.arguments) { - return nil, errors.New("invalid arity") - } - return arguments, nil -} - -func (a *argSpec) typeCheck(arg interface{}) error { - for _, t := range a.types { - switch t { - case jpNumber: - if _, ok := arg.(float64); ok { - return nil - } - case jpString: - if _, ok := arg.(string); ok { - return nil - } - case jpArray: - if isSliceType(arg) { - return nil - } - case jpObject: - if _, ok := arg.(map[string]interface{}); ok { - return nil - } - case jpArrayNumber: - if _, ok := toArrayNum(arg); ok { - return nil - } - case jpArrayString: - if _, ok := toArrayStr(arg); ok { - return nil - } - case jpAny: - return nil - case jpExpref: - if _, ok := arg.(expRef); ok { - return nil - } - } - } - return fmt.Errorf("Invalid type for: %v, expected: %#v", arg, a.types) -} - -func (f *functionCaller) CallFunction(name string, arguments []interface{}, intr *treeInterpreter) (interface{}, error) { - entry, ok := f.functionTable[name] - if !ok { - return nil, errors.New("unknown function: " + name) - } - resolvedArgs, err := entry.resolveArgs(arguments) - if err != nil { - return nil, err - } - if entry.hasExpRef { - var extra []interface{} - extra = append(extra, intr) - resolvedArgs = append(extra, resolvedArgs...) - } - return entry.handler(resolvedArgs) -} - -func jpfAbs(arguments []interface{}) (interface{}, error) { - num := arguments[0].(float64) - return math.Abs(num), nil -} - -func jpfLength(arguments []interface{}) (interface{}, error) { - arg := arguments[0] - if c, ok := arg.(string); ok { - return float64(utf8.RuneCountInString(c)), nil - } else if isSliceType(arg) { - v := reflect.ValueOf(arg) - return float64(v.Len()), nil - } else if c, ok := arg.(map[string]interface{}); ok { - return float64(len(c)), nil - } - return nil, errors.New("could not compute length()") -} - -func jpfStartsWith(arguments []interface{}) (interface{}, error) { - search := arguments[0].(string) - prefix := arguments[1].(string) - return strings.HasPrefix(search, prefix), nil -} - -func jpfAvg(arguments []interface{}) (interface{}, error) { - // We've already type checked the value so we can safely use - // type assertions. - args := arguments[0].([]interface{}) - length := float64(len(args)) - numerator := 0.0 - for _, n := range args { - numerator += n.(float64) - } - return numerator / length, nil -} -func jpfCeil(arguments []interface{}) (interface{}, error) { - val := arguments[0].(float64) - return math.Ceil(val), nil -} -func jpfContains(arguments []interface{}) (interface{}, error) { - search := arguments[0] - el := arguments[1] - if searchStr, ok := search.(string); ok { - if elStr, ok := el.(string); ok { - return strings.Contains(searchStr, elStr), nil - } - return false, nil - } - // Otherwise this is a generic contains for []interface{} - general := search.([]interface{}) - for _, item := range general { - if item == el { - return true, nil - } - } - return false, nil -} -func jpfEndsWith(arguments []interface{}) (interface{}, error) { - search := arguments[0].(string) - suffix := arguments[1].(string) - return strings.HasSuffix(search, suffix), nil -} -func jpfFloor(arguments []interface{}) (interface{}, error) { - val := arguments[0].(float64) - return math.Floor(val), nil -} -func jpfMap(arguments []interface{}) (interface{}, error) { - intr := arguments[0].(*treeInterpreter) - exp := arguments[1].(expRef) - node := exp.ref - arr := arguments[2].([]interface{}) - mapped := make([]interface{}, 0, len(arr)) - for _, value := range arr { - current, err := intr.Execute(node, value) - if err != nil { - return nil, err - } - mapped = append(mapped, current) - } - return mapped, nil -} -func jpfMax(arguments []interface{}) (interface{}, error) { - if items, ok := toArrayNum(arguments[0]); ok { - if len(items) == 0 { - return nil, nil - } - if len(items) == 1 { - return items[0], nil - } - best := items[0] - for _, item := range items[1:] { - if item > best { - best = item - } - } - return best, nil - } - // Otherwise we're dealing with a max() of strings. - items, _ := toArrayStr(arguments[0]) - if len(items) == 0 { - return nil, nil - } - if len(items) == 1 { - return items[0], nil - } - best := items[0] - for _, item := range items[1:] { - if item > best { - best = item - } - } - return best, nil -} -func jpfMerge(arguments []interface{}) (interface{}, error) { - final := make(map[string]interface{}) - for _, m := range arguments { - mapped := m.(map[string]interface{}) - for key, value := range mapped { - final[key] = value - } - } - return final, nil -} -func jpfMaxBy(arguments []interface{}) (interface{}, error) { - intr := arguments[0].(*treeInterpreter) - arr := arguments[1].([]interface{}) - exp := arguments[2].(expRef) - node := exp.ref - if len(arr) == 0 { - return nil, nil - } else if len(arr) == 1 { - return arr[0], nil - } - start, err := intr.Execute(node, arr[0]) - if err != nil { - return nil, err - } - switch t := start.(type) { - case float64: - bestVal := t - bestItem := arr[0] - for _, item := range arr[1:] { - result, err := intr.Execute(node, item) - if err != nil { - return nil, err - } - current, ok := result.(float64) - if !ok { - return nil, errors.New("invalid type, must be number") - } - if current > bestVal { - bestVal = current - bestItem = item - } - } - return bestItem, nil - case string: - bestVal := t - bestItem := arr[0] - for _, item := range arr[1:] { - result, err := intr.Execute(node, item) - if err != nil { - return nil, err - } - current, ok := result.(string) - if !ok { - return nil, errors.New("invalid type, must be string") - } - if current > bestVal { - bestVal = current - bestItem = item - } - } - return bestItem, nil - default: - return nil, errors.New("invalid type, must be number of string") - } -} -func jpfSum(arguments []interface{}) (interface{}, error) { - items, _ := toArrayNum(arguments[0]) - sum := 0.0 - for _, item := range items { - sum += item - } - return sum, nil -} - -func jpfMin(arguments []interface{}) (interface{}, error) { - if items, ok := toArrayNum(arguments[0]); ok { - if len(items) == 0 { - return nil, nil - } - if len(items) == 1 { - return items[0], nil - } - best := items[0] - for _, item := range items[1:] { - if item < best { - best = item - } - } - return best, nil - } - items, _ := toArrayStr(arguments[0]) - if len(items) == 0 { - return nil, nil - } - if len(items) == 1 { - return items[0], nil - } - best := items[0] - for _, item := range items[1:] { - if item < best { - best = item - } - } - return best, nil -} - -func jpfMinBy(arguments []interface{}) (interface{}, error) { - intr := arguments[0].(*treeInterpreter) - arr := arguments[1].([]interface{}) - exp := arguments[2].(expRef) - node := exp.ref - if len(arr) == 0 { - return nil, nil - } else if len(arr) == 1 { - return arr[0], nil - } - start, err := intr.Execute(node, arr[0]) - if err != nil { - return nil, err - } - if t, ok := start.(float64); ok { - bestVal := t - bestItem := arr[0] - for _, item := range arr[1:] { - result, err := intr.Execute(node, item) - if err != nil { - return nil, err - } - current, ok := result.(float64) - if !ok { - return nil, errors.New("invalid type, must be number") - } - if current < bestVal { - bestVal = current - bestItem = item - } - } - return bestItem, nil - } else if t, ok := start.(string); ok { - bestVal := t - bestItem := arr[0] - for _, item := range arr[1:] { - result, err := intr.Execute(node, item) - if err != nil { - return nil, err - } - current, ok := result.(string) - if !ok { - return nil, errors.New("invalid type, must be string") - } - if current < bestVal { - bestVal = current - bestItem = item - } - } - return bestItem, nil - } else { - return nil, errors.New("invalid type, must be number of string") - } -} -func jpfType(arguments []interface{}) (interface{}, error) { - arg := arguments[0] - if _, ok := arg.(float64); ok { - return "number", nil - } - if _, ok := arg.(string); ok { - return "string", nil - } - if _, ok := arg.([]interface{}); ok { - return "array", nil - } - if _, ok := arg.(map[string]interface{}); ok { - return "object", nil - } - if arg == nil { - return "null", nil - } - if arg == true || arg == false { - return "boolean", nil - } - return nil, errors.New("unknown type") -} -func jpfKeys(arguments []interface{}) (interface{}, error) { - arg := arguments[0].(map[string]interface{}) - collected := make([]interface{}, 0, len(arg)) - for key := range arg { - collected = append(collected, key) - } - return collected, nil -} -func jpfValues(arguments []interface{}) (interface{}, error) { - arg := arguments[0].(map[string]interface{}) - collected := make([]interface{}, 0, len(arg)) - for _, value := range arg { - collected = append(collected, value) - } - return collected, nil -} -func jpfSort(arguments []interface{}) (interface{}, error) { - if items, ok := toArrayNum(arguments[0]); ok { - d := sort.Float64Slice(items) - sort.Stable(d) - final := make([]interface{}, len(d)) - for i, val := range d { - final[i] = val - } - return final, nil - } - // Otherwise we're dealing with sort()'ing strings. - items, _ := toArrayStr(arguments[0]) - d := sort.StringSlice(items) - sort.Stable(d) - final := make([]interface{}, len(d)) - for i, val := range d { - final[i] = val - } - return final, nil -} -func jpfSortBy(arguments []interface{}) (interface{}, error) { - intr := arguments[0].(*treeInterpreter) - arr := arguments[1].([]interface{}) - exp := arguments[2].(expRef) - node := exp.ref - if len(arr) == 0 { - return arr, nil - } else if len(arr) == 1 { - return arr, nil - } - start, err := intr.Execute(node, arr[0]) - if err != nil { - return nil, err - } - if _, ok := start.(float64); ok { - sortable := &byExprFloat{intr, node, arr, false} - sort.Stable(sortable) - if sortable.hasError { - return nil, errors.New("error in sort_by comparison") - } - return arr, nil - } else if _, ok := start.(string); ok { - sortable := &byExprString{intr, node, arr, false} - sort.Stable(sortable) - if sortable.hasError { - return nil, errors.New("error in sort_by comparison") - } - return arr, nil - } else { - return nil, errors.New("invalid type, must be number of string") - } -} -func jpfJoin(arguments []interface{}) (interface{}, error) { - sep := arguments[0].(string) - // We can't just do arguments[1].([]string), we have to - // manually convert each item to a string. - arrayStr := []string{} - for _, item := range arguments[1].([]interface{}) { - arrayStr = append(arrayStr, item.(string)) - } - return strings.Join(arrayStr, sep), nil -} -func jpfReverse(arguments []interface{}) (interface{}, error) { - if s, ok := arguments[0].(string); ok { - r := []rune(s) - for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { - r[i], r[j] = r[j], r[i] - } - return string(r), nil - } - items := arguments[0].([]interface{}) - length := len(items) - reversed := make([]interface{}, length) - for i, item := range items { - reversed[length-(i+1)] = item - } - return reversed, nil -} -func jpfToArray(arguments []interface{}) (interface{}, error) { - if _, ok := arguments[0].([]interface{}); ok { - return arguments[0], nil - } - return arguments[:1:1], nil -} -func jpfToString(arguments []interface{}) (interface{}, error) { - if v, ok := arguments[0].(string); ok { - return v, nil - } - result, err := json.Marshal(arguments[0]) - if err != nil { - return nil, err - } - return string(result), nil -} -func jpfToNumber(arguments []interface{}) (interface{}, error) { - arg := arguments[0] - if v, ok := arg.(float64); ok { - return v, nil - } - if v, ok := arg.(string); ok { - conv, err := strconv.ParseFloat(v, 64) - if err != nil { - return nil, nil - } - return conv, nil - } - if _, ok := arg.([]interface{}); ok { - return nil, nil - } - if _, ok := arg.(map[string]interface{}); ok { - return nil, nil - } - if arg == nil { - return nil, nil - } - if arg == true || arg == false { - return nil, nil - } - return nil, errors.New("unknown type") -} -func jpfNotNull(arguments []interface{}) (interface{}, error) { - for _, arg := range arguments { - if arg != nil { - return arg, nil - } - } - return nil, nil -} diff --git a/vendor/github.com/jmespath/go-jmespath/interpreter.go b/vendor/github.com/jmespath/go-jmespath/interpreter.go deleted file mode 100644 index 13c74604c2..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/interpreter.go +++ /dev/null @@ -1,418 +0,0 @@ -package jmespath - -import ( - "errors" - "reflect" - "unicode" - "unicode/utf8" -) - -/* This is a tree based interpreter. It walks the AST and directly - interprets the AST to search through a JSON document. -*/ - -type treeInterpreter struct { - fCall *functionCaller -} - -func newInterpreter() *treeInterpreter { - interpreter := treeInterpreter{} - interpreter.fCall = newFunctionCaller() - return &interpreter -} - -type expRef struct { - ref ASTNode -} - -// Execute takes an ASTNode and input data and interprets the AST directly. -// It will produce the result of applying the JMESPath expression associated -// with the ASTNode to the input data "value". -func (intr *treeInterpreter) Execute(node ASTNode, value interface{}) (interface{}, error) { - switch node.nodeType { - case ASTComparator: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - right, err := intr.Execute(node.children[1], value) - if err != nil { - return nil, err - } - switch node.value { - case tEQ: - return objsEqual(left, right), nil - case tNE: - return !objsEqual(left, right), nil - } - leftNum, ok := left.(float64) - if !ok { - return nil, nil - } - rightNum, ok := right.(float64) - if !ok { - return nil, nil - } - switch node.value { - case tGT: - return leftNum > rightNum, nil - case tGTE: - return leftNum >= rightNum, nil - case tLT: - return leftNum < rightNum, nil - case tLTE: - return leftNum <= rightNum, nil - } - case ASTExpRef: - return expRef{ref: node.children[0]}, nil - case ASTFunctionExpression: - resolvedArgs := []interface{}{} - for _, arg := range node.children { - current, err := intr.Execute(arg, value) - if err != nil { - return nil, err - } - resolvedArgs = append(resolvedArgs, current) - } - return intr.fCall.CallFunction(node.value.(string), resolvedArgs, intr) - case ASTField: - if m, ok := value.(map[string]interface{}); ok { - key := node.value.(string) - return m[key], nil - } - return intr.fieldFromStruct(node.value.(string), value) - case ASTFilterProjection: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, nil - } - sliceType, ok := left.([]interface{}) - if !ok { - if isSliceType(left) { - return intr.filterProjectionWithReflection(node, left) - } - return nil, nil - } - compareNode := node.children[2] - collected := []interface{}{} - for _, element := range sliceType { - result, err := intr.Execute(compareNode, element) - if err != nil { - return nil, err - } - if !isFalse(result) { - current, err := intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if current != nil { - collected = append(collected, current) - } - } - } - return collected, nil - case ASTFlatten: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, nil - } - sliceType, ok := left.([]interface{}) - if !ok { - // If we can't type convert to []interface{}, there's - // a chance this could still work via reflection if we're - // dealing with user provided types. - if isSliceType(left) { - return intr.flattenWithReflection(left) - } - return nil, nil - } - flattened := []interface{}{} - for _, element := range sliceType { - if elementSlice, ok := element.([]interface{}); ok { - flattened = append(flattened, elementSlice...) - } else if isSliceType(element) { - reflectFlat := []interface{}{} - v := reflect.ValueOf(element) - for i := 0; i < v.Len(); i++ { - reflectFlat = append(reflectFlat, v.Index(i).Interface()) - } - flattened = append(flattened, reflectFlat...) - } else { - flattened = append(flattened, element) - } - } - return flattened, nil - case ASTIdentity, ASTCurrentNode: - return value, nil - case ASTIndex: - if sliceType, ok := value.([]interface{}); ok { - index := node.value.(int) - if index < 0 { - index += len(sliceType) - } - if index < len(sliceType) && index >= 0 { - return sliceType[index], nil - } - return nil, nil - } - // Otherwise try via reflection. - rv := reflect.ValueOf(value) - if rv.Kind() == reflect.Slice { - index := node.value.(int) - if index < 0 { - index += rv.Len() - } - if index < rv.Len() && index >= 0 { - v := rv.Index(index) - return v.Interface(), nil - } - } - return nil, nil - case ASTKeyValPair: - return intr.Execute(node.children[0], value) - case ASTLiteral: - return node.value, nil - case ASTMultiSelectHash: - if value == nil { - return nil, nil - } - collected := make(map[string]interface{}) - for _, child := range node.children { - current, err := intr.Execute(child, value) - if err != nil { - return nil, err - } - key := child.value.(string) - collected[key] = current - } - return collected, nil - case ASTMultiSelectList: - if value == nil { - return nil, nil - } - collected := []interface{}{} - for _, child := range node.children { - current, err := intr.Execute(child, value) - if err != nil { - return nil, err - } - collected = append(collected, current) - } - return collected, nil - case ASTOrExpression: - matched, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - if isFalse(matched) { - matched, err = intr.Execute(node.children[1], value) - if err != nil { - return nil, err - } - } - return matched, nil - case ASTAndExpression: - matched, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - if isFalse(matched) { - return matched, nil - } - return intr.Execute(node.children[1], value) - case ASTNotExpression: - matched, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - if isFalse(matched) { - return true, nil - } - return false, nil - case ASTPipe: - result := value - var err error - for _, child := range node.children { - result, err = intr.Execute(child, result) - if err != nil { - return nil, err - } - } - return result, nil - case ASTProjection: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - sliceType, ok := left.([]interface{}) - if !ok { - if isSliceType(left) { - return intr.projectWithReflection(node, left) - } - return nil, nil - } - collected := []interface{}{} - var current interface{} - for _, element := range sliceType { - current, err = intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if current != nil { - collected = append(collected, current) - } - } - return collected, nil - case ASTSubexpression, ASTIndexExpression: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - return intr.Execute(node.children[1], left) - case ASTSlice: - sliceType, ok := value.([]interface{}) - if !ok { - if isSliceType(value) { - return intr.sliceWithReflection(node, value) - } - return nil, nil - } - parts := node.value.([]*int) - sliceParams := make([]sliceParam, 3) - for i, part := range parts { - if part != nil { - sliceParams[i].Specified = true - sliceParams[i].N = *part - } - } - return slice(sliceType, sliceParams) - case ASTValueProjection: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, nil - } - mapType, ok := left.(map[string]interface{}) - if !ok { - return nil, nil - } - values := make([]interface{}, len(mapType)) - for _, value := range mapType { - values = append(values, value) - } - collected := []interface{}{} - for _, element := range values { - current, err := intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if current != nil { - collected = append(collected, current) - } - } - return collected, nil - } - return nil, errors.New("Unknown AST node: " + node.nodeType.String()) -} - -func (intr *treeInterpreter) fieldFromStruct(key string, value interface{}) (interface{}, error) { - rv := reflect.ValueOf(value) - first, n := utf8.DecodeRuneInString(key) - fieldName := string(unicode.ToUpper(first)) + key[n:] - if rv.Kind() == reflect.Struct { - v := rv.FieldByName(fieldName) - if !v.IsValid() { - return nil, nil - } - return v.Interface(), nil - } else if rv.Kind() == reflect.Ptr { - // Handle multiple levels of indirection? - if rv.IsNil() { - return nil, nil - } - rv = rv.Elem() - v := rv.FieldByName(fieldName) - if !v.IsValid() { - return nil, nil - } - return v.Interface(), nil - } - return nil, nil -} - -func (intr *treeInterpreter) flattenWithReflection(value interface{}) (interface{}, error) { - v := reflect.ValueOf(value) - flattened := []interface{}{} - for i := 0; i < v.Len(); i++ { - element := v.Index(i).Interface() - if reflect.TypeOf(element).Kind() == reflect.Slice { - // Then insert the contents of the element - // slice into the flattened slice, - // i.e flattened = append(flattened, mySlice...) - elementV := reflect.ValueOf(element) - for j := 0; j < elementV.Len(); j++ { - flattened = append( - flattened, elementV.Index(j).Interface()) - } - } else { - flattened = append(flattened, element) - } - } - return flattened, nil -} - -func (intr *treeInterpreter) sliceWithReflection(node ASTNode, value interface{}) (interface{}, error) { - v := reflect.ValueOf(value) - parts := node.value.([]*int) - sliceParams := make([]sliceParam, 3) - for i, part := range parts { - if part != nil { - sliceParams[i].Specified = true - sliceParams[i].N = *part - } - } - final := []interface{}{} - for i := 0; i < v.Len(); i++ { - element := v.Index(i).Interface() - final = append(final, element) - } - return slice(final, sliceParams) -} - -func (intr *treeInterpreter) filterProjectionWithReflection(node ASTNode, value interface{}) (interface{}, error) { - compareNode := node.children[2] - collected := []interface{}{} - v := reflect.ValueOf(value) - for i := 0; i < v.Len(); i++ { - element := v.Index(i).Interface() - result, err := intr.Execute(compareNode, element) - if err != nil { - return nil, err - } - if !isFalse(result) { - current, err := intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if current != nil { - collected = append(collected, current) - } - } - } - return collected, nil -} - -func (intr *treeInterpreter) projectWithReflection(node ASTNode, value interface{}) (interface{}, error) { - collected := []interface{}{} - v := reflect.ValueOf(value) - for i := 0; i < v.Len(); i++ { - element := v.Index(i).Interface() - result, err := intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if result != nil { - collected = append(collected, result) - } - } - return collected, nil -} diff --git a/vendor/github.com/jmespath/go-jmespath/lexer.go b/vendor/github.com/jmespath/go-jmespath/lexer.go deleted file mode 100644 index 817900c8f5..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/lexer.go +++ /dev/null @@ -1,420 +0,0 @@ -package jmespath - -import ( - "bytes" - "encoding/json" - "fmt" - "strconv" - "strings" - "unicode/utf8" -) - -type token struct { - tokenType tokType - value string - position int - length int -} - -type tokType int - -const eof = -1 - -// Lexer contains information about the expression being tokenized. -type Lexer struct { - expression string // The expression provided by the user. - currentPos int // The current position in the string. - lastWidth int // The width of the current rune. This - buf bytes.Buffer // Internal buffer used for building up values. -} - -// SyntaxError is the main error used whenever a lexing or parsing error occurs. -type SyntaxError struct { - msg string // Error message displayed to user - Expression string // Expression that generated a SyntaxError - Offset int // The location in the string where the error occurred -} - -func (e SyntaxError) Error() string { - // In the future, it would be good to underline the specific - // location where the error occurred. - return "SyntaxError: " + e.msg -} - -// HighlightLocation will show where the syntax error occurred. -// It will place a "^" character on a line below the expression -// at the point where the syntax error occurred. -func (e SyntaxError) HighlightLocation() string { - return e.Expression + "\n" + strings.Repeat(" ", e.Offset) + "^" -} - -//go:generate stringer -type=tokType -const ( - tUnknown tokType = iota - tStar - tDot - tFilter - tFlatten - tLparen - tRparen - tLbracket - tRbracket - tLbrace - tRbrace - tOr - tPipe - tNumber - tUnquotedIdentifier - tQuotedIdentifier - tComma - tColon - tLT - tLTE - tGT - tGTE - tEQ - tNE - tJSONLiteral - tStringLiteral - tCurrent - tExpref - tAnd - tNot - tEOF -) - -var basicTokens = map[rune]tokType{ - '.': tDot, - '*': tStar, - ',': tComma, - ':': tColon, - '{': tLbrace, - '}': tRbrace, - ']': tRbracket, // tLbracket not included because it could be "[]" - '(': tLparen, - ')': tRparen, - '@': tCurrent, -} - -// Bit mask for [a-zA-Z_] shifted down 64 bits to fit in a single uint64. -// When using this bitmask just be sure to shift the rune down 64 bits -// before checking against identifierStartBits. -const identifierStartBits uint64 = 576460745995190270 - -// Bit mask for [a-zA-Z0-9], 128 bits -> 2 uint64s. -var identifierTrailingBits = [2]uint64{287948901175001088, 576460745995190270} - -var whiteSpace = map[rune]bool{ - ' ': true, '\t': true, '\n': true, '\r': true, -} - -func (t token) String() string { - return fmt.Sprintf("Token{%+v, %s, %d, %d}", - t.tokenType, t.value, t.position, t.length) -} - -// NewLexer creates a new JMESPath lexer. -func NewLexer() *Lexer { - lexer := Lexer{} - return &lexer -} - -func (lexer *Lexer) next() rune { - if lexer.currentPos >= len(lexer.expression) { - lexer.lastWidth = 0 - return eof - } - r, w := utf8.DecodeRuneInString(lexer.expression[lexer.currentPos:]) - lexer.lastWidth = w - lexer.currentPos += w - return r -} - -func (lexer *Lexer) back() { - lexer.currentPos -= lexer.lastWidth -} - -func (lexer *Lexer) peek() rune { - t := lexer.next() - lexer.back() - return t -} - -// tokenize takes an expression and returns corresponding tokens. -func (lexer *Lexer) tokenize(expression string) ([]token, error) { - var tokens []token - lexer.expression = expression - lexer.currentPos = 0 - lexer.lastWidth = 0 -loop: - for { - r := lexer.next() - if identifierStartBits&(1<<(uint64(r)-64)) > 0 { - t := lexer.consumeUnquotedIdentifier() - tokens = append(tokens, t) - } else if val, ok := basicTokens[r]; ok { - // Basic single char token. - t := token{ - tokenType: val, - value: string(r), - position: lexer.currentPos - lexer.lastWidth, - length: 1, - } - tokens = append(tokens, t) - } else if r == '-' || (r >= '0' && r <= '9') { - t := lexer.consumeNumber() - tokens = append(tokens, t) - } else if r == '[' { - t := lexer.consumeLBracket() - tokens = append(tokens, t) - } else if r == '"' { - t, err := lexer.consumeQuotedIdentifier() - if err != nil { - return tokens, err - } - tokens = append(tokens, t) - } else if r == '\'' { - t, err := lexer.consumeRawStringLiteral() - if err != nil { - return tokens, err - } - tokens = append(tokens, t) - } else if r == '`' { - t, err := lexer.consumeLiteral() - if err != nil { - return tokens, err - } - tokens = append(tokens, t) - } else if r == '|' { - t := lexer.matchOrElse(r, '|', tOr, tPipe) - tokens = append(tokens, t) - } else if r == '<' { - t := lexer.matchOrElse(r, '=', tLTE, tLT) - tokens = append(tokens, t) - } else if r == '>' { - t := lexer.matchOrElse(r, '=', tGTE, tGT) - tokens = append(tokens, t) - } else if r == '!' { - t := lexer.matchOrElse(r, '=', tNE, tNot) - tokens = append(tokens, t) - } else if r == '=' { - t := lexer.matchOrElse(r, '=', tEQ, tUnknown) - tokens = append(tokens, t) - } else if r == '&' { - t := lexer.matchOrElse(r, '&', tAnd, tExpref) - tokens = append(tokens, t) - } else if r == eof { - break loop - } else if _, ok := whiteSpace[r]; ok { - // Ignore whitespace - } else { - return tokens, lexer.syntaxError(fmt.Sprintf("Unknown char: %s", strconv.QuoteRuneToASCII(r))) - } - } - tokens = append(tokens, token{tEOF, "", len(lexer.expression), 0}) - return tokens, nil -} - -// Consume characters until the ending rune "r" is reached. -// If the end of the expression is reached before seeing the -// terminating rune "r", then an error is returned. -// If no error occurs then the matching substring is returned. -// The returned string will not include the ending rune. -func (lexer *Lexer) consumeUntil(end rune) (string, error) { - start := lexer.currentPos - current := lexer.next() - for current != end && current != eof { - if current == '\\' && lexer.peek() != eof { - lexer.next() - } - current = lexer.next() - } - if lexer.lastWidth == 0 { - // Then we hit an EOF so we never reached the closing - // delimiter. - return "", SyntaxError{ - msg: "Unclosed delimiter: " + string(end), - Expression: lexer.expression, - Offset: len(lexer.expression), - } - } - return lexer.expression[start : lexer.currentPos-lexer.lastWidth], nil -} - -func (lexer *Lexer) consumeLiteral() (token, error) { - start := lexer.currentPos - value, err := lexer.consumeUntil('`') - if err != nil { - return token{}, err - } - value = strings.Replace(value, "\\`", "`", -1) - return token{ - tokenType: tJSONLiteral, - value: value, - position: start, - length: len(value), - }, nil -} - -func (lexer *Lexer) consumeRawStringLiteral() (token, error) { - start := lexer.currentPos - currentIndex := start - current := lexer.next() - for current != '\'' && lexer.peek() != eof { - if current == '\\' && lexer.peek() == '\'' { - chunk := lexer.expression[currentIndex : lexer.currentPos-1] - lexer.buf.WriteString(chunk) - lexer.buf.WriteString("'") - lexer.next() - currentIndex = lexer.currentPos - } - current = lexer.next() - } - if lexer.lastWidth == 0 { - // Then we hit an EOF so we never reached the closing - // delimiter. - return token{}, SyntaxError{ - msg: "Unclosed delimiter: '", - Expression: lexer.expression, - Offset: len(lexer.expression), - } - } - if currentIndex < lexer.currentPos { - lexer.buf.WriteString(lexer.expression[currentIndex : lexer.currentPos-1]) - } - value := lexer.buf.String() - // Reset the buffer so it can reused again. - lexer.buf.Reset() - return token{ - tokenType: tStringLiteral, - value: value, - position: start, - length: len(value), - }, nil -} - -func (lexer *Lexer) syntaxError(msg string) SyntaxError { - return SyntaxError{ - msg: msg, - Expression: lexer.expression, - Offset: lexer.currentPos - 1, - } -} - -// Checks for a two char token, otherwise matches a single character -// token. This is used whenever a two char token overlaps a single -// char token, e.g. "||" -> tPipe, "|" -> tOr. -func (lexer *Lexer) matchOrElse(first rune, second rune, matchedType tokType, singleCharType tokType) token { - start := lexer.currentPos - lexer.lastWidth - nextRune := lexer.next() - var t token - if nextRune == second { - t = token{ - tokenType: matchedType, - value: string(first) + string(second), - position: start, - length: 2, - } - } else { - lexer.back() - t = token{ - tokenType: singleCharType, - value: string(first), - position: start, - length: 1, - } - } - return t -} - -func (lexer *Lexer) consumeLBracket() token { - // There's three options here: - // 1. A filter expression "[?" - // 2. A flatten operator "[]" - // 3. A bare rbracket "[" - start := lexer.currentPos - lexer.lastWidth - nextRune := lexer.next() - var t token - if nextRune == '?' { - t = token{ - tokenType: tFilter, - value: "[?", - position: start, - length: 2, - } - } else if nextRune == ']' { - t = token{ - tokenType: tFlatten, - value: "[]", - position: start, - length: 2, - } - } else { - t = token{ - tokenType: tLbracket, - value: "[", - position: start, - length: 1, - } - lexer.back() - } - return t -} - -func (lexer *Lexer) consumeQuotedIdentifier() (token, error) { - start := lexer.currentPos - value, err := lexer.consumeUntil('"') - if err != nil { - return token{}, err - } - var decoded string - asJSON := []byte("\"" + value + "\"") - if err := json.Unmarshal([]byte(asJSON), &decoded); err != nil { - return token{}, err - } - return token{ - tokenType: tQuotedIdentifier, - value: decoded, - position: start - 1, - length: len(decoded), - }, nil -} - -func (lexer *Lexer) consumeUnquotedIdentifier() token { - // Consume runes until we reach the end of an unquoted - // identifier. - start := lexer.currentPos - lexer.lastWidth - for { - r := lexer.next() - if r < 0 || r > 128 || identifierTrailingBits[uint64(r)/64]&(1<<(uint64(r)%64)) == 0 { - lexer.back() - break - } - } - value := lexer.expression[start:lexer.currentPos] - return token{ - tokenType: tUnquotedIdentifier, - value: value, - position: start, - length: lexer.currentPos - start, - } -} - -func (lexer *Lexer) consumeNumber() token { - // Consume runes until we reach something that's not a number. - start := lexer.currentPos - lexer.lastWidth - for { - r := lexer.next() - if r < '0' || r > '9' { - lexer.back() - break - } - } - value := lexer.expression[start:lexer.currentPos] - return token{ - tokenType: tNumber, - value: value, - position: start, - length: lexer.currentPos - start, - } -} diff --git a/vendor/github.com/jmespath/go-jmespath/parser.go b/vendor/github.com/jmespath/go-jmespath/parser.go deleted file mode 100644 index 4abc303ab4..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/parser.go +++ /dev/null @@ -1,603 +0,0 @@ -package jmespath - -import ( - "encoding/json" - "fmt" - "strconv" - "strings" -) - -type astNodeType int - -//go:generate stringer -type astNodeType -const ( - ASTEmpty astNodeType = iota - ASTComparator - ASTCurrentNode - ASTExpRef - ASTFunctionExpression - ASTField - ASTFilterProjection - ASTFlatten - ASTIdentity - ASTIndex - ASTIndexExpression - ASTKeyValPair - ASTLiteral - ASTMultiSelectHash - ASTMultiSelectList - ASTOrExpression - ASTAndExpression - ASTNotExpression - ASTPipe - ASTProjection - ASTSubexpression - ASTSlice - ASTValueProjection -) - -// ASTNode represents the abstract syntax tree of a JMESPath expression. -type ASTNode struct { - nodeType astNodeType - value interface{} - children []ASTNode -} - -func (node ASTNode) String() string { - return node.PrettyPrint(0) -} - -// PrettyPrint will pretty print the parsed AST. -// The AST is an implementation detail and this pretty print -// function is provided as a convenience method to help with -// debugging. You should not rely on its output as the internal -// structure of the AST may change at any time. -func (node ASTNode) PrettyPrint(indent int) string { - spaces := strings.Repeat(" ", indent) - output := fmt.Sprintf("%s%s {\n", spaces, node.nodeType) - nextIndent := indent + 2 - if node.value != nil { - if converted, ok := node.value.(fmt.Stringer); ok { - // Account for things like comparator nodes - // that are enums with a String() method. - output += fmt.Sprintf("%svalue: %s\n", strings.Repeat(" ", nextIndent), converted.String()) - } else { - output += fmt.Sprintf("%svalue: %#v\n", strings.Repeat(" ", nextIndent), node.value) - } - } - lastIndex := len(node.children) - if lastIndex > 0 { - output += fmt.Sprintf("%schildren: {\n", strings.Repeat(" ", nextIndent)) - childIndent := nextIndent + 2 - for _, elem := range node.children { - output += elem.PrettyPrint(childIndent) - } - } - output += fmt.Sprintf("%s}\n", spaces) - return output -} - -var bindingPowers = map[tokType]int{ - tEOF: 0, - tUnquotedIdentifier: 0, - tQuotedIdentifier: 0, - tRbracket: 0, - tRparen: 0, - tComma: 0, - tRbrace: 0, - tNumber: 0, - tCurrent: 0, - tExpref: 0, - tColon: 0, - tPipe: 1, - tOr: 2, - tAnd: 3, - tEQ: 5, - tLT: 5, - tLTE: 5, - tGT: 5, - tGTE: 5, - tNE: 5, - tFlatten: 9, - tStar: 20, - tFilter: 21, - tDot: 40, - tNot: 45, - tLbrace: 50, - tLbracket: 55, - tLparen: 60, -} - -// Parser holds state about the current expression being parsed. -type Parser struct { - expression string - tokens []token - index int -} - -// NewParser creates a new JMESPath parser. -func NewParser() *Parser { - p := Parser{} - return &p -} - -// Parse will compile a JMESPath expression. -func (p *Parser) Parse(expression string) (ASTNode, error) { - lexer := NewLexer() - p.expression = expression - p.index = 0 - tokens, err := lexer.tokenize(expression) - if err != nil { - return ASTNode{}, err - } - p.tokens = tokens - parsed, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - if p.current() != tEOF { - return ASTNode{}, p.syntaxError(fmt.Sprintf( - "Unexpected token at the end of the expression: %s", p.current())) - } - return parsed, nil -} - -func (p *Parser) parseExpression(bindingPower int) (ASTNode, error) { - var err error - leftToken := p.lookaheadToken(0) - p.advance() - leftNode, err := p.nud(leftToken) - if err != nil { - return ASTNode{}, err - } - currentToken := p.current() - for bindingPower < bindingPowers[currentToken] { - p.advance() - leftNode, err = p.led(currentToken, leftNode) - if err != nil { - return ASTNode{}, err - } - currentToken = p.current() - } - return leftNode, nil -} - -func (p *Parser) parseIndexExpression() (ASTNode, error) { - if p.lookahead(0) == tColon || p.lookahead(1) == tColon { - return p.parseSliceExpression() - } - indexStr := p.lookaheadToken(0).value - parsedInt, err := strconv.Atoi(indexStr) - if err != nil { - return ASTNode{}, err - } - indexNode := ASTNode{nodeType: ASTIndex, value: parsedInt} - p.advance() - if err := p.match(tRbracket); err != nil { - return ASTNode{}, err - } - return indexNode, nil -} - -func (p *Parser) parseSliceExpression() (ASTNode, error) { - parts := []*int{nil, nil, nil} - index := 0 - current := p.current() - for current != tRbracket && index < 3 { - if current == tColon { - index++ - p.advance() - } else if current == tNumber { - parsedInt, err := strconv.Atoi(p.lookaheadToken(0).value) - if err != nil { - return ASTNode{}, err - } - parts[index] = &parsedInt - p.advance() - } else { - return ASTNode{}, p.syntaxError( - "Expected tColon or tNumber" + ", received: " + p.current().String()) - } - current = p.current() - } - if err := p.match(tRbracket); err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTSlice, - value: parts, - }, nil -} - -func (p *Parser) match(tokenType tokType) error { - if p.current() == tokenType { - p.advance() - return nil - } - return p.syntaxError("Expected " + tokenType.String() + ", received: " + p.current().String()) -} - -func (p *Parser) led(tokenType tokType, node ASTNode) (ASTNode, error) { - switch tokenType { - case tDot: - if p.current() != tStar { - right, err := p.parseDotRHS(bindingPowers[tDot]) - return ASTNode{ - nodeType: ASTSubexpression, - children: []ASTNode{node, right}, - }, err - } - p.advance() - right, err := p.parseProjectionRHS(bindingPowers[tDot]) - return ASTNode{ - nodeType: ASTValueProjection, - children: []ASTNode{node, right}, - }, err - case tPipe: - right, err := p.parseExpression(bindingPowers[tPipe]) - return ASTNode{nodeType: ASTPipe, children: []ASTNode{node, right}}, err - case tOr: - right, err := p.parseExpression(bindingPowers[tOr]) - return ASTNode{nodeType: ASTOrExpression, children: []ASTNode{node, right}}, err - case tAnd: - right, err := p.parseExpression(bindingPowers[tAnd]) - return ASTNode{nodeType: ASTAndExpression, children: []ASTNode{node, right}}, err - case tLparen: - name := node.value - var args []ASTNode - for p.current() != tRparen { - expression, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - if p.current() == tComma { - if err := p.match(tComma); err != nil { - return ASTNode{}, err - } - } - args = append(args, expression) - } - if err := p.match(tRparen); err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTFunctionExpression, - value: name, - children: args, - }, nil - case tFilter: - return p.parseFilter(node) - case tFlatten: - left := ASTNode{nodeType: ASTFlatten, children: []ASTNode{node}} - right, err := p.parseProjectionRHS(bindingPowers[tFlatten]) - return ASTNode{ - nodeType: ASTProjection, - children: []ASTNode{left, right}, - }, err - case tEQ, tNE, tGT, tGTE, tLT, tLTE: - right, err := p.parseExpression(bindingPowers[tokenType]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTComparator, - value: tokenType, - children: []ASTNode{node, right}, - }, nil - case tLbracket: - tokenType := p.current() - var right ASTNode - var err error - if tokenType == tNumber || tokenType == tColon { - right, err = p.parseIndexExpression() - if err != nil { - return ASTNode{}, err - } - return p.projectIfSlice(node, right) - } - // Otherwise this is a projection. - if err := p.match(tStar); err != nil { - return ASTNode{}, err - } - if err := p.match(tRbracket); err != nil { - return ASTNode{}, err - } - right, err = p.parseProjectionRHS(bindingPowers[tStar]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTProjection, - children: []ASTNode{node, right}, - }, nil - } - return ASTNode{}, p.syntaxError("Unexpected token: " + tokenType.String()) -} - -func (p *Parser) nud(token token) (ASTNode, error) { - switch token.tokenType { - case tJSONLiteral: - var parsed interface{} - err := json.Unmarshal([]byte(token.value), &parsed) - if err != nil { - return ASTNode{}, err - } - return ASTNode{nodeType: ASTLiteral, value: parsed}, nil - case tStringLiteral: - return ASTNode{nodeType: ASTLiteral, value: token.value}, nil - case tUnquotedIdentifier: - return ASTNode{ - nodeType: ASTField, - value: token.value, - }, nil - case tQuotedIdentifier: - node := ASTNode{nodeType: ASTField, value: token.value} - if p.current() == tLparen { - return ASTNode{}, p.syntaxErrorToken("Can't have quoted identifier as function name.", token) - } - return node, nil - case tStar: - left := ASTNode{nodeType: ASTIdentity} - var right ASTNode - var err error - if p.current() == tRbracket { - right = ASTNode{nodeType: ASTIdentity} - } else { - right, err = p.parseProjectionRHS(bindingPowers[tStar]) - } - return ASTNode{nodeType: ASTValueProjection, children: []ASTNode{left, right}}, err - case tFilter: - return p.parseFilter(ASTNode{nodeType: ASTIdentity}) - case tLbrace: - return p.parseMultiSelectHash() - case tFlatten: - left := ASTNode{ - nodeType: ASTFlatten, - children: []ASTNode{{nodeType: ASTIdentity}}, - } - right, err := p.parseProjectionRHS(bindingPowers[tFlatten]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{nodeType: ASTProjection, children: []ASTNode{left, right}}, nil - case tLbracket: - tokenType := p.current() - //var right ASTNode - if tokenType == tNumber || tokenType == tColon { - right, err := p.parseIndexExpression() - if err != nil { - return ASTNode{}, nil - } - return p.projectIfSlice(ASTNode{nodeType: ASTIdentity}, right) - } else if tokenType == tStar && p.lookahead(1) == tRbracket { - p.advance() - p.advance() - right, err := p.parseProjectionRHS(bindingPowers[tStar]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTProjection, - children: []ASTNode{{nodeType: ASTIdentity}, right}, - }, nil - } else { - return p.parseMultiSelectList() - } - case tCurrent: - return ASTNode{nodeType: ASTCurrentNode}, nil - case tExpref: - expression, err := p.parseExpression(bindingPowers[tExpref]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{nodeType: ASTExpRef, children: []ASTNode{expression}}, nil - case tNot: - expression, err := p.parseExpression(bindingPowers[tNot]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{nodeType: ASTNotExpression, children: []ASTNode{expression}}, nil - case tLparen: - expression, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - if err := p.match(tRparen); err != nil { - return ASTNode{}, err - } - return expression, nil - case tEOF: - return ASTNode{}, p.syntaxErrorToken("Incomplete expression", token) - } - - return ASTNode{}, p.syntaxErrorToken("Invalid token: "+token.tokenType.String(), token) -} - -func (p *Parser) parseMultiSelectList() (ASTNode, error) { - var expressions []ASTNode - for { - expression, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - expressions = append(expressions, expression) - if p.current() == tRbracket { - break - } - err = p.match(tComma) - if err != nil { - return ASTNode{}, err - } - } - err := p.match(tRbracket) - if err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTMultiSelectList, - children: expressions, - }, nil -} - -func (p *Parser) parseMultiSelectHash() (ASTNode, error) { - var children []ASTNode - for { - keyToken := p.lookaheadToken(0) - if err := p.match(tUnquotedIdentifier); err != nil { - if err := p.match(tQuotedIdentifier); err != nil { - return ASTNode{}, p.syntaxError("Expected tQuotedIdentifier or tUnquotedIdentifier") - } - } - keyName := keyToken.value - err := p.match(tColon) - if err != nil { - return ASTNode{}, err - } - value, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - node := ASTNode{ - nodeType: ASTKeyValPair, - value: keyName, - children: []ASTNode{value}, - } - children = append(children, node) - if p.current() == tComma { - err := p.match(tComma) - if err != nil { - return ASTNode{}, nil - } - } else if p.current() == tRbrace { - err := p.match(tRbrace) - if err != nil { - return ASTNode{}, nil - } - break - } - } - return ASTNode{ - nodeType: ASTMultiSelectHash, - children: children, - }, nil -} - -func (p *Parser) projectIfSlice(left ASTNode, right ASTNode) (ASTNode, error) { - indexExpr := ASTNode{ - nodeType: ASTIndexExpression, - children: []ASTNode{left, right}, - } - if right.nodeType == ASTSlice { - right, err := p.parseProjectionRHS(bindingPowers[tStar]) - return ASTNode{ - nodeType: ASTProjection, - children: []ASTNode{indexExpr, right}, - }, err - } - return indexExpr, nil -} -func (p *Parser) parseFilter(node ASTNode) (ASTNode, error) { - var right, condition ASTNode - var err error - condition, err = p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - if err := p.match(tRbracket); err != nil { - return ASTNode{}, err - } - if p.current() == tFlatten { - right = ASTNode{nodeType: ASTIdentity} - } else { - right, err = p.parseProjectionRHS(bindingPowers[tFilter]) - if err != nil { - return ASTNode{}, err - } - } - - return ASTNode{ - nodeType: ASTFilterProjection, - children: []ASTNode{node, right, condition}, - }, nil -} - -func (p *Parser) parseDotRHS(bindingPower int) (ASTNode, error) { - lookahead := p.current() - if tokensOneOf([]tokType{tQuotedIdentifier, tUnquotedIdentifier, tStar}, lookahead) { - return p.parseExpression(bindingPower) - } else if lookahead == tLbracket { - if err := p.match(tLbracket); err != nil { - return ASTNode{}, err - } - return p.parseMultiSelectList() - } else if lookahead == tLbrace { - if err := p.match(tLbrace); err != nil { - return ASTNode{}, err - } - return p.parseMultiSelectHash() - } - return ASTNode{}, p.syntaxError("Expected identifier, lbracket, or lbrace") -} - -func (p *Parser) parseProjectionRHS(bindingPower int) (ASTNode, error) { - current := p.current() - if bindingPowers[current] < 10 { - return ASTNode{nodeType: ASTIdentity}, nil - } else if current == tLbracket { - return p.parseExpression(bindingPower) - } else if current == tFilter { - return p.parseExpression(bindingPower) - } else if current == tDot { - err := p.match(tDot) - if err != nil { - return ASTNode{}, err - } - return p.parseDotRHS(bindingPower) - } else { - return ASTNode{}, p.syntaxError("Error") - } -} - -func (p *Parser) lookahead(number int) tokType { - return p.lookaheadToken(number).tokenType -} - -func (p *Parser) current() tokType { - return p.lookahead(0) -} - -func (p *Parser) lookaheadToken(number int) token { - return p.tokens[p.index+number] -} - -func (p *Parser) advance() { - p.index++ -} - -func tokensOneOf(elements []tokType, token tokType) bool { - for _, elem := range elements { - if elem == token { - return true - } - } - return false -} - -func (p *Parser) syntaxError(msg string) SyntaxError { - return SyntaxError{ - msg: msg, - Expression: p.expression, - Offset: p.lookaheadToken(0).position, - } -} - -// Create a SyntaxError based on the provided token. -// This differs from syntaxError() which creates a SyntaxError -// based on the current lookahead token. -func (p *Parser) syntaxErrorToken(msg string, t token) SyntaxError { - return SyntaxError{ - msg: msg, - Expression: p.expression, - Offset: t.position, - } -} diff --git a/vendor/github.com/jmespath/go-jmespath/toktype_string.go b/vendor/github.com/jmespath/go-jmespath/toktype_string.go deleted file mode 100644 index c76af6866f..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/toktype_string.go +++ /dev/null @@ -1,53 +0,0 @@ -// Code generated by "stringer -type=tokType"; DO NOT EDIT. - -package jmespath - -import "strconv" - -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[tUnknown-0] - _ = x[tStar-1] - _ = x[tDot-2] - _ = x[tFilter-3] - _ = x[tFlatten-4] - _ = x[tLparen-5] - _ = x[tRparen-6] - _ = x[tLbracket-7] - _ = x[tRbracket-8] - _ = x[tLbrace-9] - _ = x[tRbrace-10] - _ = x[tOr-11] - _ = x[tPipe-12] - _ = x[tNumber-13] - _ = x[tUnquotedIdentifier-14] - _ = x[tQuotedIdentifier-15] - _ = x[tComma-16] - _ = x[tColon-17] - _ = x[tLT-18] - _ = x[tLTE-19] - _ = x[tGT-20] - _ = x[tGTE-21] - _ = x[tEQ-22] - _ = x[tNE-23] - _ = x[tJSONLiteral-24] - _ = x[tStringLiteral-25] - _ = x[tCurrent-26] - _ = x[tExpref-27] - _ = x[tAnd-28] - _ = x[tNot-29] - _ = x[tEOF-30] -} - -const _tokType_name = "tUnknowntStartDottFiltertFlattentLparentRparentLbrackettRbrackettLbracetRbracetOrtPipetNumbertUnquotedIdentifiertQuotedIdentifiertCommatColontLTtLTEtGTtGTEtEQtNEtJSONLiteraltStringLiteraltCurrenttExpreftAndtNottEOF" - -var _tokType_index = [...]uint8{0, 8, 13, 17, 24, 32, 39, 46, 55, 64, 71, 78, 81, 86, 93, 112, 129, 135, 141, 144, 148, 151, 155, 158, 161, 173, 187, 195, 202, 206, 210, 214} - -func (i tokType) String() string { - if i < 0 || i >= tokType(len(_tokType_index)-1) { - return "tokType(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _tokType_name[_tokType_index[i]:_tokType_index[i+1]] -} diff --git a/vendor/github.com/jmespath/go-jmespath/util.go b/vendor/github.com/jmespath/go-jmespath/util.go deleted file mode 100644 index ddc1b7d7d4..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/util.go +++ /dev/null @@ -1,185 +0,0 @@ -package jmespath - -import ( - "errors" - "reflect" -) - -// IsFalse determines if an object is false based on the JMESPath spec. -// JMESPath defines false values to be any of: -// - An empty string array, or hash. -// - The boolean value false. -// - nil -func isFalse(value interface{}) bool { - switch v := value.(type) { - case bool: - return !v - case []interface{}: - return len(v) == 0 - case map[string]interface{}: - return len(v) == 0 - case string: - return len(v) == 0 - case nil: - return true - } - // Try the reflection cases before returning false. - rv := reflect.ValueOf(value) - switch rv.Kind() { - case reflect.Struct: - // A struct type will never be false, even if - // all of its values are the zero type. - return false - case reflect.Slice, reflect.Map: - return rv.Len() == 0 - case reflect.Ptr: - if rv.IsNil() { - return true - } - // If it's a pointer type, we'll try to deref the pointer - // and evaluate the pointer value for isFalse. - element := rv.Elem() - return isFalse(element.Interface()) - } - return false -} - -// ObjsEqual is a generic object equality check. -// It will take two arbitrary objects and recursively determine -// if they are equal. -func objsEqual(left interface{}, right interface{}) bool { - return reflect.DeepEqual(left, right) -} - -// SliceParam refers to a single part of a slice. -// A slice consists of a start, a stop, and a step, similar to -// python slices. -type sliceParam struct { - N int - Specified bool -} - -// Slice supports [start:stop:step] style slicing that's supported in JMESPath. -func slice(slice []interface{}, parts []sliceParam) ([]interface{}, error) { - computed, err := computeSliceParams(len(slice), parts) - if err != nil { - return nil, err - } - start, stop, step := computed[0], computed[1], computed[2] - result := []interface{}{} - if step > 0 { - for i := start; i < stop; i += step { - result = append(result, slice[i]) - } - } else { - for i := start; i > stop; i += step { - result = append(result, slice[i]) - } - } - return result, nil -} - -func computeSliceParams(length int, parts []sliceParam) ([]int, error) { - var start, stop, step int - if !parts[2].Specified { - step = 1 - } else if parts[2].N == 0 { - return nil, errors.New("Invalid slice, step cannot be 0") - } else { - step = parts[2].N - } - var stepValueNegative bool - if step < 0 { - stepValueNegative = true - } else { - stepValueNegative = false - } - - if !parts[0].Specified { - if stepValueNegative { - start = length - 1 - } else { - start = 0 - } - } else { - start = capSlice(length, parts[0].N, step) - } - - if !parts[1].Specified { - if stepValueNegative { - stop = -1 - } else { - stop = length - } - } else { - stop = capSlice(length, parts[1].N, step) - } - return []int{start, stop, step}, nil -} - -func capSlice(length int, actual int, step int) int { - if actual < 0 { - actual += length - if actual < 0 { - if step < 0 { - actual = -1 - } else { - actual = 0 - } - } - } else if actual >= length { - if step < 0 { - actual = length - 1 - } else { - actual = length - } - } - return actual -} - -// ToArrayNum converts an empty interface type to a slice of float64. -// If any element in the array cannot be converted, then nil is returned -// along with a second value of false. -func toArrayNum(data interface{}) ([]float64, bool) { - // Is there a better way to do this with reflect? - if d, ok := data.([]interface{}); ok { - result := make([]float64, len(d)) - for i, el := range d { - item, ok := el.(float64) - if !ok { - return nil, false - } - result[i] = item - } - return result, true - } - return nil, false -} - -// ToArrayStr converts an empty interface type to a slice of strings. -// If any element in the array cannot be converted, then nil is returned -// along with a second value of false. If the input data could be entirely -// converted, then the converted data, along with a second value of true, -// will be returned. -func toArrayStr(data interface{}) ([]string, bool) { - // Is there a better way to do this with reflect? - if d, ok := data.([]interface{}); ok { - result := make([]string, len(d)) - for i, el := range d { - item, ok := el.(string) - if !ok { - return nil, false - } - result[i] = item - } - return result, true - } - return nil, false -} - -func isSliceType(v interface{}) bool { - if v == nil { - return false - } - return reflect.TypeOf(v).Kind() == reflect.Slice -} diff --git a/vendor/github.com/magiconair/properties/CHANGELOG.md b/vendor/github.com/magiconair/properties/CHANGELOG.md deleted file mode 100644 index 842e8e24fb..0000000000 --- a/vendor/github.com/magiconair/properties/CHANGELOG.md +++ /dev/null @@ -1,205 +0,0 @@ -## Changelog - -### [1.8.7](https://github.com/magiconair/properties/tree/v1.8.7) - 08 Dec 2022 - - * [PR #65](https://github.com/magiconair/properties/pull/65): Speedup Merge - - Thanks to [@AdityaVallabh](https://github.com/AdityaVallabh) for the patch. - - * [PR #66](https://github.com/magiconair/properties/pull/66): use github actions - -### [1.8.6](https://github.com/magiconair/properties/tree/v1.8.6) - 23 Feb 2022 - - * [PR #57](https://github.com/magiconair/properties/pull/57):Fix "unreachable code" lint error - - Thanks to [@ellie](https://github.com/ellie) for the patch. - - * [PR #63](https://github.com/magiconair/properties/pull/63): Make TestMustGetParsedDuration backwards compatible - - This patch ensures that the `TestMustGetParsedDuration` still works with `go1.3` to make the - author happy until it affects real users. - - Thanks to [@maage](https://github.com/maage) for the patch. - -### [1.8.5](https://github.com/magiconair/properties/tree/v1.8.5) - 24 Mar 2021 - - * [PR #55](https://github.com/magiconair/properties/pull/55): Fix: Encoding Bug in Comments - - When reading comments \ are loaded correctly, but when writing they are then - replaced by \\. This leads to wrong comments when writing and reading multiple times. - - Thanks to [@doxsch](https://github.com/doxsch) for the patch. - -### [1.8.4](https://github.com/magiconair/properties/tree/v1.8.4) - 23 Sep 2020 - - * [PR #50](https://github.com/magiconair/properties/pull/50): enhance error message for circular references - - Thanks to [@sriv](https://github.com/sriv) for the patch. - -### [1.8.3](https://github.com/magiconair/properties/tree/v1.8.3) - 14 Sep 2020 - - * [PR #49](https://github.com/magiconair/properties/pull/49): Include the key in error message causing the circular reference - - The change is include the key in the error message which is causing the circular - reference when parsing/loading the properties files. - - Thanks to [@haroon-sheikh](https://github.com/haroon-sheikh) for the patch. - -### [1.8.2](https://github.com/magiconair/properties/tree/v1.8.2) - 25 Aug 2020 - - * [PR #36](https://github.com/magiconair/properties/pull/36): Escape backslash on write - - This patch ensures that backslashes are escaped on write. Existing applications which - rely on the old behavior may need to be updated. - - Thanks to [@apesternikov](https://github.com/apesternikov) for the patch. - - * [PR #42](https://github.com/magiconair/properties/pull/42): Made Content-Type check whitespace agnostic in LoadURL() - - Thanks to [@aliras1](https://github.com/aliras1) for the patch. - - * [PR #41](https://github.com/magiconair/properties/pull/41): Make key/value separator configurable on Write() - - Thanks to [@mkjor](https://github.com/mkjor) for the patch. - - * [PR #40](https://github.com/magiconair/properties/pull/40): Add method to return a sorted list of keys - - Thanks to [@mkjor](https://github.com/mkjor) for the patch. - -### [1.8.1](https://github.com/magiconair/properties/tree/v1.8.1) - 10 May 2019 - - * [PR #35](https://github.com/magiconair/properties/pull/35): Close body always after request - - This patch ensures that in `LoadURL` the response body is always closed. - - Thanks to [@liubog2008](https://github.com/liubog2008) for the patch. - -### [1.8](https://github.com/magiconair/properties/tree/v1.8) - 15 May 2018 - - * [PR #26](https://github.com/magiconair/properties/pull/26): Disable expansion during loading - - This adds the option to disable property expansion during loading. - - Thanks to [@kmala](https://github.com/kmala) for the patch. - -### [1.7.6](https://github.com/magiconair/properties/tree/v1.7.6) - 14 Feb 2018 - - * [PR #29](https://github.com/magiconair/properties/pull/29): Reworked expansion logic to handle more complex cases. - - See PR for an example. - - Thanks to [@yobert](https://github.com/yobert) for the fix. - -### [1.7.5](https://github.com/magiconair/properties/tree/v1.7.5) - 13 Feb 2018 - - * [PR #28](https://github.com/magiconair/properties/pull/28): Support duplicate expansions in the same value - - Values which expand the same key multiple times (e.g. `key=${a} ${a}`) will no longer fail - with a `circular reference error`. - - Thanks to [@yobert](https://github.com/yobert) for the fix. - -### [1.7.4](https://github.com/magiconair/properties/tree/v1.7.4) - 31 Oct 2017 - - * [Issue #23](https://github.com/magiconair/properties/issues/23): Ignore blank lines with whitespaces - - * [PR #24](https://github.com/magiconair/properties/pull/24): Update keys when DisableExpansion is enabled - - Thanks to [@mgurov](https://github.com/mgurov) for the fix. - -### [1.7.3](https://github.com/magiconair/properties/tree/v1.7.3) - 10 Jul 2017 - - * [Issue #17](https://github.com/magiconair/properties/issues/17): Add [SetValue()](http://godoc.org/github.com/magiconair/properties#Properties.SetValue) method to set values generically - * [Issue #22](https://github.com/magiconair/properties/issues/22): Add [LoadMap()](http://godoc.org/github.com/magiconair/properties#LoadMap) function to load properties from a string map - -### [1.7.2](https://github.com/magiconair/properties/tree/v1.7.2) - 20 Mar 2017 - - * [Issue #15](https://github.com/magiconair/properties/issues/15): Drop gocheck dependency - * [PR #21](https://github.com/magiconair/properties/pull/21): Add [Map()](http://godoc.org/github.com/magiconair/properties#Properties.Map) and [FilterFunc()](http://godoc.org/github.com/magiconair/properties#Properties.FilterFunc) - -### [1.7.1](https://github.com/magiconair/properties/tree/v1.7.1) - 13 Jan 2017 - - * [Issue #14](https://github.com/magiconair/properties/issues/14): Decouple TestLoadExpandedFile from `$USER` - * [PR #12](https://github.com/magiconair/properties/pull/12): Load from files and URLs - * [PR #16](https://github.com/magiconair/properties/pull/16): Keep gofmt happy - * [PR #18](https://github.com/magiconair/properties/pull/18): Fix Delete() function - -### [1.7.0](https://github.com/magiconair/properties/tree/v1.7.0) - 20 Mar 2016 - - * [Issue #10](https://github.com/magiconair/properties/issues/10): Add [LoadURL,LoadURLs,MustLoadURL,MustLoadURLs](http://godoc.org/github.com/magiconair/properties#LoadURL) method to load properties from a URL. - * [Issue #11](https://github.com/magiconair/properties/issues/11): Add [LoadString,MustLoadString](http://godoc.org/github.com/magiconair/properties#LoadString) method to load properties from an UTF8 string. - * [PR #8](https://github.com/magiconair/properties/pull/8): Add [MustFlag](http://godoc.org/github.com/magiconair/properties#Properties.MustFlag) method to provide overrides via command line flags. (@pascaldekloe) - -### [1.6.0](https://github.com/magiconair/properties/tree/v1.6.0) - 11 Dec 2015 - - * Add [Decode](http://godoc.org/github.com/magiconair/properties#Properties.Decode) method to populate struct from properties via tags. - -### [1.5.6](https://github.com/magiconair/properties/tree/v1.5.6) - 18 Oct 2015 - - * Vendored in gopkg.in/check.v1 - -### [1.5.5](https://github.com/magiconair/properties/tree/v1.5.5) - 31 Jul 2015 - - * [PR #6](https://github.com/magiconair/properties/pull/6): Add [Delete](http://godoc.org/github.com/magiconair/properties#Properties.Delete) method to remove keys including comments. (@gerbenjacobs) - -### [1.5.4](https://github.com/magiconair/properties/tree/v1.5.4) - 23 Jun 2015 - - * [Issue #5](https://github.com/magiconair/properties/issues/5): Allow disabling of property expansion [DisableExpansion](http://godoc.org/github.com/magiconair/properties#Properties.DisableExpansion). When property expansion is disabled Properties become a simple key/value store and don't check for circular references. - -### [1.5.3](https://github.com/magiconair/properties/tree/v1.5.3) - 02 Jun 2015 - - * [Issue #4](https://github.com/magiconair/properties/issues/4): Maintain key order in [Filter()](http://godoc.org/github.com/magiconair/properties#Properties.Filter), [FilterPrefix()](http://godoc.org/github.com/magiconair/properties#Properties.FilterPrefix) and [FilterRegexp()](http://godoc.org/github.com/magiconair/properties#Properties.FilterRegexp) - -### [1.5.2](https://github.com/magiconair/properties/tree/v1.5.2) - 10 Apr 2015 - - * [Issue #3](https://github.com/magiconair/properties/issues/3): Don't print comments in [WriteComment()](http://godoc.org/github.com/magiconair/properties#Properties.WriteComment) if they are all empty - * Add clickable links to README - -### [1.5.1](https://github.com/magiconair/properties/tree/v1.5.1) - 08 Dec 2014 - - * Added [GetParsedDuration()](http://godoc.org/github.com/magiconair/properties#Properties.GetParsedDuration) and [MustGetParsedDuration()](http://godoc.org/github.com/magiconair/properties#Properties.MustGetParsedDuration) for values specified compatible with - [time.ParseDuration()](http://golang.org/pkg/time/#ParseDuration). - -### [1.5.0](https://github.com/magiconair/properties/tree/v1.5.0) - 18 Nov 2014 - - * Added support for single and multi-line comments (reading, writing and updating) - * The order of keys is now preserved - * Calling [Set()](http://godoc.org/github.com/magiconair/properties#Properties.Set) with an empty key now silently ignores the call and does not create a new entry - * Added a [MustSet()](http://godoc.org/github.com/magiconair/properties#Properties.MustSet) method - * Migrated test library from launchpad.net/gocheck to [gopkg.in/check.v1](http://gopkg.in/check.v1) - -### [1.4.2](https://github.com/magiconair/properties/tree/v1.4.2) - 15 Nov 2014 - - * [Issue #2](https://github.com/magiconair/properties/issues/2): Fixed goroutine leak in parser which created two lexers but cleaned up only one - -### [1.4.1](https://github.com/magiconair/properties/tree/v1.4.1) - 13 Nov 2014 - - * [Issue #1](https://github.com/magiconair/properties/issues/1): Fixed bug in Keys() method which returned an empty string - -### [1.4.0](https://github.com/magiconair/properties/tree/v1.4.0) - 23 Sep 2014 - - * Added [Keys()](http://godoc.org/github.com/magiconair/properties#Properties.Keys) to get the keys - * Added [Filter()](http://godoc.org/github.com/magiconair/properties#Properties.Filter), [FilterRegexp()](http://godoc.org/github.com/magiconair/properties#Properties.FilterRegexp) and [FilterPrefix()](http://godoc.org/github.com/magiconair/properties#Properties.FilterPrefix) to get a subset of the properties - -### [1.3.0](https://github.com/magiconair/properties/tree/v1.3.0) - 18 Mar 2014 - -* Added support for time.Duration -* Made MustXXX() failure beha[ior configurable (log.Fatal, panic](https://github.com/magiconair/properties/tree/vior configurable (log.Fatal, panic) - custom) -* Changed default of MustXXX() failure from panic to log.Fatal - -### [1.2.0](https://github.com/magiconair/properties/tree/v1.2.0) - 05 Mar 2014 - -* Added MustGet... functions -* Added support for int and uint with range checks on 32 bit platforms - -### [1.1.0](https://github.com/magiconair/properties/tree/v1.1.0) - 20 Jan 2014 - -* Renamed from goproperties to properties -* Added support for expansion of environment vars in - filenames and value expressions -* Fixed bug where value expressions were not at the - start of the string - -### [1.0.0](https://github.com/magiconair/properties/tree/v1.0.0) - 7 Jan 2014 - -* Initial release diff --git a/vendor/github.com/magiconair/properties/README.md b/vendor/github.com/magiconair/properties/README.md index e2edda025b..4872685f46 100644 --- a/vendor/github.com/magiconair/properties/README.md +++ b/vendor/github.com/magiconair/properties/README.md @@ -1,12 +1,9 @@ [![](https://img.shields.io/github/tag/magiconair/properties.svg?style=flat-square&label=release)](https://github.com/magiconair/properties/releases) -[![Travis CI Status](https://img.shields.io/travis/magiconair/properties.svg?branch=master&style=flat-square&label=travis)](https://travis-ci.org/magiconair/properties) [![License](https://img.shields.io/badge/License-BSD%202--Clause-orange.svg?style=flat-square)](https://raw.githubusercontent.com/magiconair/properties/master/LICENSE) [![GoDoc](http://img.shields.io/badge/godoc-reference-5272B4.svg?style=flat-square)](http://godoc.org/github.com/magiconair/properties) # Overview -#### Please run `git pull --tags` to update the tags. See [below](#updated-git-tags) why. - properties is a Go library for reading and writing properties files. It supports reading from multiple files or URLs and Spring style recursive @@ -99,30 +96,3 @@ $ go get -u github.com/magiconair/properties ## ToDo * Dump contents with passwords and secrets obscured - -## Updated Git tags - -#### 13 Feb 2018 - -I realized that all of the git tags I had pushed before v1.7.5 were lightweight tags -and I've only recently learned that this doesn't play well with `git describe` 😞 - -I have replaced all lightweight tags with signed tags using this script which should -retain the commit date, name and email address. Please run `git pull --tags` to update them. - -Worst case you have to reclone the repo. - -```shell -#!/bin/bash -tag=$1 -echo "Updating $tag" -date=$(git show ${tag}^0 --format=%aD | head -1) -email=$(git show ${tag}^0 --format=%aE | head -1) -name=$(git show ${tag}^0 --format=%aN | head -1) -GIT_COMMITTER_DATE="$date" GIT_COMMITTER_NAME="$name" GIT_COMMITTER_EMAIL="$email" git tag -s -f ${tag} ${tag}^0 -m ${tag} -``` - -I apologize for the inconvenience. - -Frank - diff --git a/vendor/github.com/magiconair/properties/decode.go b/vendor/github.com/magiconair/properties/decode.go index 8e6aa441d9..f5e252f8d9 100644 --- a/vendor/github.com/magiconair/properties/decode.go +++ b/vendor/github.com/magiconair/properties/decode.go @@ -189,12 +189,12 @@ func dec(p *Properties, key string, def *string, opts map[string]string, v refle for i := 0; i < v.NumField(); i++ { fv := v.Field(i) fk, def, opts := keydef(t.Field(i)) - if !fv.CanSet() { - return fmt.Errorf("cannot set %s", t.Field(i).Name) - } if fk == "-" { continue } + if !fv.CanSet() { + return fmt.Errorf("cannot set %s", t.Field(i).Name) + } if key != "" { fk = key + "." + fk } diff --git a/vendor/github.com/magiconair/properties/load.go b/vendor/github.com/magiconair/properties/load.go index 635368dc8a..6567e0c719 100644 --- a/vendor/github.com/magiconair/properties/load.go +++ b/vendor/github.com/magiconair/properties/load.go @@ -6,7 +6,7 @@ package properties import ( "fmt" - "io/ioutil" + "io" "net/http" "os" "strings" @@ -52,6 +52,15 @@ func (l *Loader) LoadBytes(buf []byte) (*Properties, error) { return l.loadBytes(buf, l.Encoding) } +// LoadReader reads an io.Reader into a Properties struct. +func (l *Loader) LoadReader(r io.Reader) (*Properties, error) { + if buf, err := io.ReadAll(r); err != nil { + return nil, err + } else { + return l.loadBytes(buf, l.Encoding) + } +} + // LoadAll reads the content of multiple URLs or files in the given order into // a Properties struct. If IgnoreMissing is true then a 404 status code or // missing file will not be reported as error. Encoding sets the encoding for @@ -91,7 +100,7 @@ func (l *Loader) LoadAll(names []string) (*Properties, error) { // If IgnoreMissing is true then a missing file will not be // reported as error. func (l *Loader) LoadFile(filename string) (*Properties, error) { - data, err := ioutil.ReadFile(filename) + data, err := os.ReadFile(filename) if err != nil { if l.IgnoreMissing && os.IsNotExist(err) { LogPrintf("properties: %s not found. skipping", filename) @@ -126,7 +135,7 @@ func (l *Loader) LoadURL(url string) (*Properties, error) { return nil, fmt.Errorf("properties: %s returned %d", url, resp.StatusCode) } - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("properties: %s error reading response. %s", url, err) } @@ -185,6 +194,12 @@ func LoadFile(filename string, enc Encoding) (*Properties, error) { return l.LoadAll([]string{filename}) } +// LoadReader reads an io.Reader into a Properties struct. +func LoadReader(r io.Reader, enc Encoding) (*Properties, error) { + l := &Loader{Encoding: enc} + return l.LoadReader(r) +} + // LoadFiles reads multiple files in the given order into // a Properties struct. If 'ignoreMissing' is true then // non-existent files will not be reported as error. @@ -224,6 +239,12 @@ func MustLoadString(s string) *Properties { return must(LoadString(s)) } +// MustLoadSReader reads an io.Reader into a Properties struct and +// panics on error. +func MustLoadReader(r io.Reader, enc Encoding) *Properties { + return must(LoadReader(r, enc)) +} + // MustLoadFile reads a file into a Properties struct and // panics on error. func MustLoadFile(filename string, enc Encoding) *Properties { diff --git a/vendor/github.com/mitchellh/mapstructure/CHANGELOG.md b/vendor/github.com/mitchellh/mapstructure/CHANGELOG.md index c758234904..ae634d1cc0 100644 --- a/vendor/github.com/mitchellh/mapstructure/CHANGELOG.md +++ b/vendor/github.com/mitchellh/mapstructure/CHANGELOG.md @@ -1,3 +1,8 @@ +## 1.5.1 + +* Wrap errors so they're compatible with `errors.Is` and `errors.As` [GH-282] +* Fix map of slices not decoding properly in certain cases. [GH-266] + ## 1.5.0 * New option `IgnoreUntaggedFields` to ignore decoding to any fields diff --git a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go index 3a754ca724..c1f99da032 100644 --- a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go +++ b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go @@ -271,7 +271,11 @@ func TextUnmarshallerHookFunc() DecodeHookFuncType { if !ok { return data, nil } - if err := unmarshaller.UnmarshalText([]byte(data.(string))); err != nil { + str, ok := data.(string) + if !ok { + str = reflect.Indirect(reflect.ValueOf(&data)).Elem().String() + } + if err := unmarshaller.UnmarshalText([]byte(str)); err != nil { return nil, err } return result, nil diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure.go b/vendor/github.com/mitchellh/mapstructure/mapstructure.go index 1efb22ac36..7581806a79 100644 --- a/vendor/github.com/mitchellh/mapstructure/mapstructure.go +++ b/vendor/github.com/mitchellh/mapstructure/mapstructure.go @@ -458,7 +458,7 @@ func (d *Decoder) decode(name string, input interface{}, outVal reflect.Value) e var err error input, err = DecodeHookExec(d.config.DecodeHook, inputVal, outVal) if err != nil { - return fmt.Errorf("error decoding '%s': %s", name, err) + return fmt.Errorf("error decoding '%s': %w", name, err) } } @@ -1123,6 +1123,8 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) if valSlice.IsNil() || d.config.ZeroFields { // Make a new slice to hold our result, same size as the original data. valSlice = reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len()) + } else if valSlice.Len() > dataVal.Len() { + valSlice = valSlice.Slice(0, dataVal.Len()) } // Accumulate any errors diff --git a/vendor/github.com/open-policy-agent/opa/ast/json/json.go b/vendor/github.com/open-policy-agent/opa/ast/json/json.go deleted file mode 100644 index 565017d58e..0000000000 --- a/vendor/github.com/open-policy-agent/opa/ast/json/json.go +++ /dev/null @@ -1,36 +0,0 @@ -package json - -// Options defines the options for JSON operations, -// currently only marshaling can be configured -type Options struct { - MarshalOptions MarshalOptions -} - -// MarshalOptions defines the options for JSON marshaling, -// currently only toggling the marshaling of location information is supported -type MarshalOptions struct { - // IncludeLocation toggles the marshaling of location information - IncludeLocation NodeToggle - // IncludeLocationText additionally/optionally includes the text of the location - IncludeLocationText bool - // ExcludeLocationFile additionally/optionally excludes the file of the location - // Note that this is inverted (i.e. not "include" as the default needs to remain false) - ExcludeLocationFile bool -} - -// NodeToggle is a generic struct to allow the toggling of -// settings for different ast node types -type NodeToggle struct { - Term bool - Package bool - Comment bool - Import bool - Rule bool - Head bool - Expr bool - SomeDecl bool - Every bool - With bool - Annotations bool - AnnotationsRef bool -} diff --git a/vendor/github.com/open-policy-agent/opa/ast/marshal.go b/vendor/github.com/open-policy-agent/opa/ast/marshal.go deleted file mode 100644 index 53fb112044..0000000000 --- a/vendor/github.com/open-policy-agent/opa/ast/marshal.go +++ /dev/null @@ -1,11 +0,0 @@ -package ast - -import ( - astJSON "github.com/open-policy-agent/opa/ast/json" -) - -// customJSON is an interface that can be implemented by AST nodes that -// allows the parser to set options for JSON operations on that node. -type customJSON interface { - setJSONOptions(astJSON.Options) -} diff --git a/vendor/github.com/open-policy-agent/opa/ast/strings.go b/vendor/github.com/open-policy-agent/opa/ast/strings.go deleted file mode 100644 index e489f6977c..0000000000 --- a/vendor/github.com/open-policy-agent/opa/ast/strings.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2016 The OPA Authors. All rights reserved. -// Use of this source code is governed by an Apache2 -// license that can be found in the LICENSE file. - -package ast - -import ( - "reflect" - "strings" -) - -// TypeName returns a human readable name for the AST element type. -func TypeName(x interface{}) string { - if _, ok := x.(*lazyObj); ok { - return "object" - } - return strings.ToLower(reflect.Indirect(reflect.ValueOf(x)).Type().Name()) -} diff --git a/vendor/github.com/open-policy-agent/opa/capabilities/doc.go b/vendor/github.com/open-policy-agent/opa/capabilities/doc.go new file mode 100644 index 0000000000..189c2e727a --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/capabilities/doc.go @@ -0,0 +1,8 @@ +// Copyright 2024 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// Deprecated: This package is intended for older projects transitioning from OPA v0.x and will remain for the lifetime of OPA v1.x, but its use is not recommended. +// For newer features and behaviours, such as defaulting to the Rego v1 syntax, use the corresponding components in the [github.com/open-policy-agent/opa/v1] package instead. +// See https://www.openpolicyagent.org/docs/latest/v0-compatibility/ for more information. +package capabilities diff --git a/vendor/github.com/open-policy-agent/opa/capabilities/v0.69.0.json b/vendor/github.com/open-policy-agent/opa/capabilities/v0.69.0.json new file mode 100644 index 0000000000..862a4555f9 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/capabilities/v0.69.0.json @@ -0,0 +1,4843 @@ +{ + "builtins": [ + { + "name": "abs", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "all", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "and", + "decl": { + "args": [ + { + "of": { + "type": "any" + }, + "type": "set" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + }, + "infix": "\u0026" + }, + { + "name": "any", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "array.concat", + "decl": { + "args": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "array.reverse", + "decl": { + "args": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "array.slice", + "decl": { + "args": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "assign", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": ":=" + }, + { + "name": "base64.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "base64.encode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "base64.is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "base64url.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "base64url.encode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "base64url.encode_no_pad", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "bits.and", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.lsh", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.negate", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.or", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.rsh", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.xor", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "cast_array", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "cast_boolean", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "cast_null", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "null" + }, + "type": "function" + } + }, + { + "name": "cast_object", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "cast_set", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "cast_string", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "ceil", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "concat", + "decl": { + "args": [ + { + "type": "string" + }, + { + "of": [ + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "contains", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "count", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.equal", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.md5", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.sha1", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.sha256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.sha512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.md5", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.parse_private_keys", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "crypto.sha1", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.sha256", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_and_verify_certificates", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_and_verify_certificates_with_options", + "decl": { + "args": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_certificate_request", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_certificates", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_keypair", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_rsa_private_key", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "div", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "infix": "/" + }, + { + "name": "endswith", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "eq", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "=" + }, + { + "name": "equal", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "==" + }, + { + "name": "floor", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "format_int", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "glob.match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "of": [ + { + "type": "null" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + } + ], + "type": "any" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "glob.quote_meta", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "graph.reachable", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "graph.reachable_paths", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "graphql.is_valid", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "graphql.parse", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "graphql.parse_and_verify", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "graphql.parse_query", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "graphql.parse_schema", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "graphql.schema_is_valid", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "gt", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "\u003e" + }, + { + "name": "gte", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "\u003e=" + }, + { + "name": "hex.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "hex.encode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "http.send", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "indexof", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "indexof_n", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "internal.member_2", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "in" + }, + { + "name": "internal.member_3", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "in" + }, + { + "name": "internal.print", + "decl": { + "args": [ + { + "dynamic": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "array" + } + ], + "type": "function" + } + }, + { + "name": "intersection", + "decl": { + "args": [ + { + "of": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "io.jwt.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "static": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "type": "string" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "io.jwt.decode_verify", + "decl": { + "args": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "array" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "io.jwt.encode_sign", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "type": "string" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "io.jwt.encode_sign_raw", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "io.jwt.verify_es256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_es384", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_es512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_hs256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_hs384", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_hs512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_ps256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_ps384", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_ps512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_rs256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_rs384", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_rs512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_array", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_boolean", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_null", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_number", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_object", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_set", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_string", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "json.filter", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "of": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "json.is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "json.marshal", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "json.marshal_with_options", + "decl": { + "args": [ + { + "type": "any" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "static": [ + { + "key": "indent", + "value": { + "type": "string" + } + }, + { + "key": "prefix", + "value": { + "type": "string" + } + }, + { + "key": "pretty", + "value": { + "type": "boolean" + } + } + ], + "type": "object" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "json.match_schema", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "static": [ + { + "key": "desc", + "value": { + "type": "string" + } + }, + { + "key": "error", + "value": { + "type": "string" + } + }, + { + "key": "field", + "value": { + "type": "string" + } + }, + { + "key": "type", + "value": { + "type": "string" + } + } + ], + "type": "object" + }, + "type": "array" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "json.patch", + "decl": { + "args": [ + { + "type": "any" + }, + { + "dynamic": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "static": [ + { + "key": "op", + "value": { + "type": "string" + } + }, + { + "key": "path", + "value": { + "type": "any" + } + } + ], + "type": "object" + }, + "type": "array" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "json.remove", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "of": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "json.unmarshal", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "json.verify_schema", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "of": [ + { + "type": "null" + }, + { + "type": "string" + } + ], + "type": "any" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "lower", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "lt", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "\u003c" + }, + { + "name": "lte", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "\u003c=" + }, + { + "name": "max", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "min", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "minus", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "number" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": [ + { + "type": "number" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + }, + "type": "function" + }, + "infix": "-" + }, + { + "name": "mul", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "infix": "*" + }, + { + "name": "neq", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "!=" + }, + { + "name": "net.cidr_contains", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "net.cidr_contains_matches", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": { + "static": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "type": "array" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "net.cidr_expand", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "of": { + "type": "string" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "net.cidr_intersects", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "net.cidr_is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "net.cidr_merge", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "of": [ + { + "type": "string" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": { + "type": "string" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "net.cidr_overlap", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "net.lookup_ip_addr", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "of": { + "type": "string" + }, + "type": "set" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "numbers.range", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "numbers.range_step", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "object.filter", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.get", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.keys", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "object.remove", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.subset", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.union", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.union_n", + "decl": { + "args": [ + { + "dynamic": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "opa.runtime", + "decl": { + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "or", + "decl": { + "args": [ + { + "of": { + "type": "any" + }, + "type": "set" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + }, + "infix": "|" + }, + { + "name": "plus", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "infix": "+" + }, + { + "name": "print", + "decl": { + "type": "function", + "variadic": { + "type": "any" + } + } + }, + { + "name": "product", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + { + "of": { + "type": "number" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "providers.aws.sign_req", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "rand.intn", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "re_match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "regex.find_all_string_submatch_n", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "regex.find_n", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "regex.globs_match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "regex.is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "regex.match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "regex.replace", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "regex.split", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "regex.template_match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "rego.metadata.chain", + "decl": { + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "rego.metadata.rule", + "decl": { + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "rego.parse_module", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "rem", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "infix": "%" + }, + { + "name": "replace", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "round", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "semver.compare", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "semver.is_valid", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "set_diff", + "decl": { + "args": [ + { + "of": { + "type": "any" + }, + "type": "set" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "sort", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "split", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "sprintf", + "decl": { + "args": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "startswith", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "strings.any_prefix_match", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "strings.any_suffix_match", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "strings.count", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "strings.render_template", + "decl": { + "args": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "strings.replace_n", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "type": "object" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "strings.reverse", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "substring", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "sum", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + { + "of": { + "type": "number" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.add_date", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.clock", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "time.date", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "time.diff", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "time.format", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "time.now_ns", + "decl": { + "result": { + "type": "number" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "time.parse_duration_ns", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.parse_ns", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.parse_rfc3339_ns", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.weekday", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "to_number", + "decl": { + "args": [ + { + "of": [ + { + "type": "null" + }, + { + "type": "boolean" + }, + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "any" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "trace", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "trim", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_left", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_prefix", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_right", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_space", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_suffix", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "type_name", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "union", + "decl": { + "args": [ + { + "of": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "units.parse", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "units.parse_bytes", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "upper", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "urlquery.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "urlquery.decode_object", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "dynamic": { + "type": "string" + }, + "type": "array" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "urlquery.encode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "urlquery.encode_object", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "uuid.parse", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "uuid.rfc4122", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "walk", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "static": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "type": "any" + } + ], + "type": "array" + }, + "type": "function" + }, + "relation": true + }, + { + "name": "yaml.is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "yaml.marshal", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "yaml.unmarshal", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + } + ], + "future_keywords": [ + "contains", + "every", + "if", + "in" + ], + "wasm_abi_versions": [ + { + "version": 1, + "minor_version": 1 + }, + { + "version": 1, + "minor_version": 2 + } + ], + "features": [ + "rule_head_ref_string_prefixes", + "rule_head_refs", + "rego_v1_import" + ] +} diff --git a/vendor/github.com/open-policy-agent/opa/capabilities/v0.70.0.json b/vendor/github.com/open-policy-agent/opa/capabilities/v0.70.0.json new file mode 100644 index 0000000000..862a4555f9 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/capabilities/v0.70.0.json @@ -0,0 +1,4843 @@ +{ + "builtins": [ + { + "name": "abs", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "all", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "and", + "decl": { + "args": [ + { + "of": { + "type": "any" + }, + "type": "set" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + }, + "infix": "\u0026" + }, + { + "name": "any", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "array.concat", + "decl": { + "args": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "array.reverse", + "decl": { + "args": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "array.slice", + "decl": { + "args": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "assign", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": ":=" + }, + { + "name": "base64.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "base64.encode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "base64.is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "base64url.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "base64url.encode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "base64url.encode_no_pad", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "bits.and", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.lsh", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.negate", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.or", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.rsh", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.xor", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "cast_array", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "cast_boolean", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "cast_null", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "null" + }, + "type": "function" + } + }, + { + "name": "cast_object", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "cast_set", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "cast_string", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "ceil", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "concat", + "decl": { + "args": [ + { + "type": "string" + }, + { + "of": [ + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "contains", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "count", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.equal", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.md5", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.sha1", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.sha256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.sha512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.md5", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.parse_private_keys", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "crypto.sha1", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.sha256", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_and_verify_certificates", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_and_verify_certificates_with_options", + "decl": { + "args": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_certificate_request", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_certificates", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_keypair", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_rsa_private_key", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "div", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "infix": "/" + }, + { + "name": "endswith", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "eq", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "=" + }, + { + "name": "equal", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "==" + }, + { + "name": "floor", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "format_int", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "glob.match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "of": [ + { + "type": "null" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + } + ], + "type": "any" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "glob.quote_meta", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "graph.reachable", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "graph.reachable_paths", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "graphql.is_valid", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "graphql.parse", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "graphql.parse_and_verify", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "graphql.parse_query", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "graphql.parse_schema", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "graphql.schema_is_valid", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "gt", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "\u003e" + }, + { + "name": "gte", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "\u003e=" + }, + { + "name": "hex.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "hex.encode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "http.send", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "indexof", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "indexof_n", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "internal.member_2", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "in" + }, + { + "name": "internal.member_3", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "in" + }, + { + "name": "internal.print", + "decl": { + "args": [ + { + "dynamic": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "array" + } + ], + "type": "function" + } + }, + { + "name": "intersection", + "decl": { + "args": [ + { + "of": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "io.jwt.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "static": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "type": "string" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "io.jwt.decode_verify", + "decl": { + "args": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "array" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "io.jwt.encode_sign", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "type": "string" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "io.jwt.encode_sign_raw", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "io.jwt.verify_es256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_es384", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_es512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_hs256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_hs384", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_hs512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_ps256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_ps384", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_ps512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_rs256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_rs384", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_rs512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_array", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_boolean", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_null", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_number", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_object", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_set", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_string", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "json.filter", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "of": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "json.is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "json.marshal", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "json.marshal_with_options", + "decl": { + "args": [ + { + "type": "any" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "static": [ + { + "key": "indent", + "value": { + "type": "string" + } + }, + { + "key": "prefix", + "value": { + "type": "string" + } + }, + { + "key": "pretty", + "value": { + "type": "boolean" + } + } + ], + "type": "object" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "json.match_schema", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "static": [ + { + "key": "desc", + "value": { + "type": "string" + } + }, + { + "key": "error", + "value": { + "type": "string" + } + }, + { + "key": "field", + "value": { + "type": "string" + } + }, + { + "key": "type", + "value": { + "type": "string" + } + } + ], + "type": "object" + }, + "type": "array" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "json.patch", + "decl": { + "args": [ + { + "type": "any" + }, + { + "dynamic": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "static": [ + { + "key": "op", + "value": { + "type": "string" + } + }, + { + "key": "path", + "value": { + "type": "any" + } + } + ], + "type": "object" + }, + "type": "array" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "json.remove", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "of": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "json.unmarshal", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "json.verify_schema", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "of": [ + { + "type": "null" + }, + { + "type": "string" + } + ], + "type": "any" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "lower", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "lt", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "\u003c" + }, + { + "name": "lte", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "\u003c=" + }, + { + "name": "max", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "min", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "minus", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "number" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": [ + { + "type": "number" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + }, + "type": "function" + }, + "infix": "-" + }, + { + "name": "mul", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "infix": "*" + }, + { + "name": "neq", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "!=" + }, + { + "name": "net.cidr_contains", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "net.cidr_contains_matches", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": { + "static": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "type": "array" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "net.cidr_expand", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "of": { + "type": "string" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "net.cidr_intersects", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "net.cidr_is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "net.cidr_merge", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "of": [ + { + "type": "string" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": { + "type": "string" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "net.cidr_overlap", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "net.lookup_ip_addr", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "of": { + "type": "string" + }, + "type": "set" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "numbers.range", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "numbers.range_step", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "object.filter", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.get", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.keys", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "object.remove", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.subset", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.union", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.union_n", + "decl": { + "args": [ + { + "dynamic": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "opa.runtime", + "decl": { + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "or", + "decl": { + "args": [ + { + "of": { + "type": "any" + }, + "type": "set" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + }, + "infix": "|" + }, + { + "name": "plus", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "infix": "+" + }, + { + "name": "print", + "decl": { + "type": "function", + "variadic": { + "type": "any" + } + } + }, + { + "name": "product", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + { + "of": { + "type": "number" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "providers.aws.sign_req", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "rand.intn", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "re_match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "regex.find_all_string_submatch_n", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "regex.find_n", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "regex.globs_match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "regex.is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "regex.match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "regex.replace", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "regex.split", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "regex.template_match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "rego.metadata.chain", + "decl": { + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "rego.metadata.rule", + "decl": { + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "rego.parse_module", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "rem", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "infix": "%" + }, + { + "name": "replace", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "round", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "semver.compare", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "semver.is_valid", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "set_diff", + "decl": { + "args": [ + { + "of": { + "type": "any" + }, + "type": "set" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "sort", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "split", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "sprintf", + "decl": { + "args": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "startswith", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "strings.any_prefix_match", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "strings.any_suffix_match", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "strings.count", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "strings.render_template", + "decl": { + "args": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "strings.replace_n", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "type": "object" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "strings.reverse", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "substring", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "sum", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + { + "of": { + "type": "number" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.add_date", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.clock", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "time.date", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "time.diff", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "time.format", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "time.now_ns", + "decl": { + "result": { + "type": "number" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "time.parse_duration_ns", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.parse_ns", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.parse_rfc3339_ns", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.weekday", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "to_number", + "decl": { + "args": [ + { + "of": [ + { + "type": "null" + }, + { + "type": "boolean" + }, + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "any" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "trace", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "trim", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_left", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_prefix", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_right", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_space", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_suffix", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "type_name", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "union", + "decl": { + "args": [ + { + "of": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "units.parse", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "units.parse_bytes", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "upper", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "urlquery.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "urlquery.decode_object", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "dynamic": { + "type": "string" + }, + "type": "array" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "urlquery.encode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "urlquery.encode_object", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "uuid.parse", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "uuid.rfc4122", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "walk", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "static": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "type": "any" + } + ], + "type": "array" + }, + "type": "function" + }, + "relation": true + }, + { + "name": "yaml.is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "yaml.marshal", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "yaml.unmarshal", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + } + ], + "future_keywords": [ + "contains", + "every", + "if", + "in" + ], + "wasm_abi_versions": [ + { + "version": 1, + "minor_version": 1 + }, + { + "version": 1, + "minor_version": 2 + } + ], + "features": [ + "rule_head_ref_string_prefixes", + "rule_head_refs", + "rego_v1_import" + ] +} diff --git a/vendor/github.com/open-policy-agent/opa/capabilities/v1.0.0.json b/vendor/github.com/open-policy-agent/opa/capabilities/v1.0.0.json new file mode 100644 index 0000000000..48a87b0c35 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/capabilities/v1.0.0.json @@ -0,0 +1,4835 @@ +{ + "builtins": [ + { + "name": "abs", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "all", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "and", + "decl": { + "args": [ + { + "of": { + "type": "any" + }, + "type": "set" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + }, + "infix": "\u0026" + }, + { + "name": "any", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "array.concat", + "decl": { + "args": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "array.reverse", + "decl": { + "args": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "array.slice", + "decl": { + "args": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "assign", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": ":=" + }, + { + "name": "base64.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "base64.encode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "base64.is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "base64url.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "base64url.encode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "base64url.encode_no_pad", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "bits.and", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.lsh", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.negate", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.or", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.rsh", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.xor", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "cast_array", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "cast_boolean", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "cast_null", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "null" + }, + "type": "function" + } + }, + { + "name": "cast_object", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "cast_set", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "cast_string", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "ceil", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "concat", + "decl": { + "args": [ + { + "type": "string" + }, + { + "of": [ + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "contains", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "count", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.equal", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.md5", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.sha1", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.sha256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.sha512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.md5", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.parse_private_keys", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "crypto.sha1", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.sha256", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_and_verify_certificates", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_and_verify_certificates_with_options", + "decl": { + "args": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_certificate_request", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_certificates", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_keypair", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_rsa_private_key", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "div", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "infix": "/" + }, + { + "name": "endswith", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "eq", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "=" + }, + { + "name": "equal", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "==" + }, + { + "name": "floor", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "format_int", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "glob.match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "of": [ + { + "type": "null" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + } + ], + "type": "any" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "glob.quote_meta", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "graph.reachable", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "graph.reachable_paths", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "graphql.is_valid", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "graphql.parse", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "graphql.parse_and_verify", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "graphql.parse_query", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "graphql.parse_schema", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "graphql.schema_is_valid", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "gt", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "\u003e" + }, + { + "name": "gte", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "\u003e=" + }, + { + "name": "hex.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "hex.encode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "http.send", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "indexof", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "indexof_n", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "internal.member_2", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "in" + }, + { + "name": "internal.member_3", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "in" + }, + { + "name": "internal.print", + "decl": { + "args": [ + { + "dynamic": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "array" + } + ], + "type": "function" + } + }, + { + "name": "intersection", + "decl": { + "args": [ + { + "of": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "io.jwt.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "static": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "type": "string" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "io.jwt.decode_verify", + "decl": { + "args": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "array" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "io.jwt.encode_sign", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "type": "string" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "io.jwt.encode_sign_raw", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "io.jwt.verify_es256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_es384", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_es512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_hs256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_hs384", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_hs512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_ps256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_ps384", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_ps512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_rs256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_rs384", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_rs512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_array", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_boolean", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_null", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_number", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_object", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_set", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_string", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "json.filter", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "of": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "json.is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "json.marshal", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "json.marshal_with_options", + "decl": { + "args": [ + { + "type": "any" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "static": [ + { + "key": "indent", + "value": { + "type": "string" + } + }, + { + "key": "prefix", + "value": { + "type": "string" + } + }, + { + "key": "pretty", + "value": { + "type": "boolean" + } + } + ], + "type": "object" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "json.match_schema", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "static": [ + { + "key": "desc", + "value": { + "type": "string" + } + }, + { + "key": "error", + "value": { + "type": "string" + } + }, + { + "key": "field", + "value": { + "type": "string" + } + }, + { + "key": "type", + "value": { + "type": "string" + } + } + ], + "type": "object" + }, + "type": "array" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "json.patch", + "decl": { + "args": [ + { + "type": "any" + }, + { + "dynamic": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "static": [ + { + "key": "op", + "value": { + "type": "string" + } + }, + { + "key": "path", + "value": { + "type": "any" + } + } + ], + "type": "object" + }, + "type": "array" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "json.remove", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "of": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "json.unmarshal", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "json.verify_schema", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "of": [ + { + "type": "null" + }, + { + "type": "string" + } + ], + "type": "any" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "lower", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "lt", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "\u003c" + }, + { + "name": "lte", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "\u003c=" + }, + { + "name": "max", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "min", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "minus", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "number" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": [ + { + "type": "number" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + }, + "type": "function" + }, + "infix": "-" + }, + { + "name": "mul", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "infix": "*" + }, + { + "name": "neq", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "!=" + }, + { + "name": "net.cidr_contains", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "net.cidr_contains_matches", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": { + "static": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "type": "array" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "net.cidr_expand", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "of": { + "type": "string" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "net.cidr_intersects", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "net.cidr_is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "net.cidr_merge", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "of": [ + { + "type": "string" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": { + "type": "string" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "net.cidr_overlap", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "net.lookup_ip_addr", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "of": { + "type": "string" + }, + "type": "set" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "numbers.range", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "numbers.range_step", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "object.filter", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.get", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.keys", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "object.remove", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.subset", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.union", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.union_n", + "decl": { + "args": [ + { + "dynamic": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "opa.runtime", + "decl": { + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "or", + "decl": { + "args": [ + { + "of": { + "type": "any" + }, + "type": "set" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + }, + "infix": "|" + }, + { + "name": "plus", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "infix": "+" + }, + { + "name": "print", + "decl": { + "type": "function", + "variadic": { + "type": "any" + } + } + }, + { + "name": "product", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + { + "of": { + "type": "number" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "providers.aws.sign_req", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "rand.intn", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "re_match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "regex.find_all_string_submatch_n", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "regex.find_n", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "regex.globs_match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "regex.is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "regex.match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "regex.replace", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "regex.split", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "regex.template_match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "rego.metadata.chain", + "decl": { + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "rego.metadata.rule", + "decl": { + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "rego.parse_module", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "rem", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "infix": "%" + }, + { + "name": "replace", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "round", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "semver.compare", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "semver.is_valid", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "set_diff", + "decl": { + "args": [ + { + "of": { + "type": "any" + }, + "type": "set" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "sort", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "split", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "sprintf", + "decl": { + "args": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "startswith", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "strings.any_prefix_match", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "strings.any_suffix_match", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "strings.count", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "strings.render_template", + "decl": { + "args": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "strings.replace_n", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "type": "object" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "strings.reverse", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "substring", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "sum", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + { + "of": { + "type": "number" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.add_date", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.clock", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "time.date", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "time.diff", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "time.format", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "time.now_ns", + "decl": { + "result": { + "type": "number" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "time.parse_duration_ns", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.parse_ns", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.parse_rfc3339_ns", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.weekday", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "to_number", + "decl": { + "args": [ + { + "of": [ + { + "type": "null" + }, + { + "type": "boolean" + }, + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "any" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "trace", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "trim", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_left", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_prefix", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_right", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_space", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_suffix", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "type_name", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "union", + "decl": { + "args": [ + { + "of": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "units.parse", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "units.parse_bytes", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "upper", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "urlquery.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "urlquery.decode_object", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "dynamic": { + "type": "string" + }, + "type": "array" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "urlquery.encode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "urlquery.encode_object", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "uuid.parse", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "uuid.rfc4122", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "walk", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "static": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "type": "any" + } + ], + "type": "array" + }, + "type": "function" + }, + "relation": true + }, + { + "name": "yaml.is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "yaml.marshal", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "yaml.unmarshal", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + } + ], + "wasm_abi_versions": [ + { + "version": 1, + "minor_version": 1 + }, + { + "version": 1, + "minor_version": 2 + } + ], + "features": [ + "rego_v1" + ] +} diff --git a/vendor/github.com/open-policy-agent/opa/capabilities/v1.0.1.json b/vendor/github.com/open-policy-agent/opa/capabilities/v1.0.1.json new file mode 100644 index 0000000000..48a87b0c35 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/capabilities/v1.0.1.json @@ -0,0 +1,4835 @@ +{ + "builtins": [ + { + "name": "abs", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "all", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "and", + "decl": { + "args": [ + { + "of": { + "type": "any" + }, + "type": "set" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + }, + "infix": "\u0026" + }, + { + "name": "any", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "array.concat", + "decl": { + "args": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "array.reverse", + "decl": { + "args": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "array.slice", + "decl": { + "args": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "assign", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": ":=" + }, + { + "name": "base64.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "base64.encode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "base64.is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "base64url.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "base64url.encode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "base64url.encode_no_pad", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "bits.and", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.lsh", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.negate", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.or", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.rsh", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.xor", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "cast_array", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "cast_boolean", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "cast_null", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "null" + }, + "type": "function" + } + }, + { + "name": "cast_object", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "cast_set", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "cast_string", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "ceil", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "concat", + "decl": { + "args": [ + { + "type": "string" + }, + { + "of": [ + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "contains", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "count", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.equal", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.md5", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.sha1", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.sha256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.sha512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.md5", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.parse_private_keys", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "crypto.sha1", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.sha256", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_and_verify_certificates", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_and_verify_certificates_with_options", + "decl": { + "args": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_certificate_request", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_certificates", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_keypair", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_rsa_private_key", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "div", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "infix": "/" + }, + { + "name": "endswith", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "eq", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "=" + }, + { + "name": "equal", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "==" + }, + { + "name": "floor", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "format_int", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "glob.match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "of": [ + { + "type": "null" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + } + ], + "type": "any" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "glob.quote_meta", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "graph.reachable", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "graph.reachable_paths", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "graphql.is_valid", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "graphql.parse", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "graphql.parse_and_verify", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "graphql.parse_query", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "graphql.parse_schema", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "graphql.schema_is_valid", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "gt", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "\u003e" + }, + { + "name": "gte", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "\u003e=" + }, + { + "name": "hex.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "hex.encode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "http.send", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "indexof", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "indexof_n", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "internal.member_2", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "in" + }, + { + "name": "internal.member_3", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "in" + }, + { + "name": "internal.print", + "decl": { + "args": [ + { + "dynamic": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "array" + } + ], + "type": "function" + } + }, + { + "name": "intersection", + "decl": { + "args": [ + { + "of": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "io.jwt.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "static": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "type": "string" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "io.jwt.decode_verify", + "decl": { + "args": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "array" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "io.jwt.encode_sign", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "type": "string" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "io.jwt.encode_sign_raw", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "io.jwt.verify_es256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_es384", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_es512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_hs256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_hs384", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_hs512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_ps256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_ps384", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_ps512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_rs256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_rs384", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_rs512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_array", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_boolean", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_null", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_number", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_object", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_set", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_string", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "json.filter", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "of": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "json.is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "json.marshal", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "json.marshal_with_options", + "decl": { + "args": [ + { + "type": "any" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "static": [ + { + "key": "indent", + "value": { + "type": "string" + } + }, + { + "key": "prefix", + "value": { + "type": "string" + } + }, + { + "key": "pretty", + "value": { + "type": "boolean" + } + } + ], + "type": "object" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "json.match_schema", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "static": [ + { + "key": "desc", + "value": { + "type": "string" + } + }, + { + "key": "error", + "value": { + "type": "string" + } + }, + { + "key": "field", + "value": { + "type": "string" + } + }, + { + "key": "type", + "value": { + "type": "string" + } + } + ], + "type": "object" + }, + "type": "array" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "json.patch", + "decl": { + "args": [ + { + "type": "any" + }, + { + "dynamic": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "static": [ + { + "key": "op", + "value": { + "type": "string" + } + }, + { + "key": "path", + "value": { + "type": "any" + } + } + ], + "type": "object" + }, + "type": "array" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "json.remove", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "of": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "json.unmarshal", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "json.verify_schema", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "of": [ + { + "type": "null" + }, + { + "type": "string" + } + ], + "type": "any" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "lower", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "lt", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "\u003c" + }, + { + "name": "lte", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "\u003c=" + }, + { + "name": "max", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "min", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "minus", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "number" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": [ + { + "type": "number" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + }, + "type": "function" + }, + "infix": "-" + }, + { + "name": "mul", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "infix": "*" + }, + { + "name": "neq", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "!=" + }, + { + "name": "net.cidr_contains", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "net.cidr_contains_matches", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": { + "static": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "type": "array" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "net.cidr_expand", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "of": { + "type": "string" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "net.cidr_intersects", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "net.cidr_is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "net.cidr_merge", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "of": [ + { + "type": "string" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": { + "type": "string" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "net.cidr_overlap", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "net.lookup_ip_addr", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "of": { + "type": "string" + }, + "type": "set" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "numbers.range", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "numbers.range_step", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "object.filter", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.get", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.keys", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "object.remove", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.subset", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.union", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.union_n", + "decl": { + "args": [ + { + "dynamic": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "opa.runtime", + "decl": { + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "or", + "decl": { + "args": [ + { + "of": { + "type": "any" + }, + "type": "set" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + }, + "infix": "|" + }, + { + "name": "plus", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "infix": "+" + }, + { + "name": "print", + "decl": { + "type": "function", + "variadic": { + "type": "any" + } + } + }, + { + "name": "product", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + { + "of": { + "type": "number" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "providers.aws.sign_req", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "rand.intn", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "re_match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "regex.find_all_string_submatch_n", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "regex.find_n", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "regex.globs_match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "regex.is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "regex.match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "regex.replace", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "regex.split", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "regex.template_match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "rego.metadata.chain", + "decl": { + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "rego.metadata.rule", + "decl": { + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "rego.parse_module", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "rem", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "infix": "%" + }, + { + "name": "replace", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "round", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "semver.compare", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "semver.is_valid", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "set_diff", + "decl": { + "args": [ + { + "of": { + "type": "any" + }, + "type": "set" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "sort", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "split", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "sprintf", + "decl": { + "args": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "startswith", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "strings.any_prefix_match", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "strings.any_suffix_match", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "strings.count", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "strings.render_template", + "decl": { + "args": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "strings.replace_n", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "type": "object" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "strings.reverse", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "substring", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "sum", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + { + "of": { + "type": "number" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.add_date", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.clock", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "time.date", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "time.diff", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "time.format", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "time.now_ns", + "decl": { + "result": { + "type": "number" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "time.parse_duration_ns", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.parse_ns", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.parse_rfc3339_ns", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.weekday", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "to_number", + "decl": { + "args": [ + { + "of": [ + { + "type": "null" + }, + { + "type": "boolean" + }, + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "any" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "trace", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "trim", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_left", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_prefix", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_right", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_space", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_suffix", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "type_name", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "union", + "decl": { + "args": [ + { + "of": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "units.parse", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "units.parse_bytes", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "upper", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "urlquery.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "urlquery.decode_object", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "dynamic": { + "type": "string" + }, + "type": "array" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "urlquery.encode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "urlquery.encode_object", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "uuid.parse", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "uuid.rfc4122", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "walk", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "static": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "type": "any" + } + ], + "type": "array" + }, + "type": "function" + }, + "relation": true + }, + { + "name": "yaml.is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "yaml.marshal", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "yaml.unmarshal", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + } + ], + "wasm_abi_versions": [ + { + "version": 1, + "minor_version": 1 + }, + { + "version": 1, + "minor_version": 2 + } + ], + "features": [ + "rego_v1" + ] +} diff --git a/vendor/github.com/open-policy-agent/opa/capabilities/v1.1.0.json b/vendor/github.com/open-policy-agent/opa/capabilities/v1.1.0.json new file mode 100644 index 0000000000..48a87b0c35 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/capabilities/v1.1.0.json @@ -0,0 +1,4835 @@ +{ + "builtins": [ + { + "name": "abs", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "all", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "and", + "decl": { + "args": [ + { + "of": { + "type": "any" + }, + "type": "set" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + }, + "infix": "\u0026" + }, + { + "name": "any", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "array.concat", + "decl": { + "args": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "array.reverse", + "decl": { + "args": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "array.slice", + "decl": { + "args": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "assign", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": ":=" + }, + { + "name": "base64.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "base64.encode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "base64.is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "base64url.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "base64url.encode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "base64url.encode_no_pad", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "bits.and", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.lsh", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.negate", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.or", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.rsh", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "bits.xor", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "cast_array", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "cast_boolean", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "cast_null", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "null" + }, + "type": "function" + } + }, + { + "name": "cast_object", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "cast_set", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "cast_string", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "ceil", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "concat", + "decl": { + "args": [ + { + "type": "string" + }, + { + "of": [ + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "contains", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "count", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.equal", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.md5", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.sha1", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.sha256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.hmac.sha512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.md5", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.parse_private_keys", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "crypto.sha1", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.sha256", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_and_verify_certificates", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_and_verify_certificates_with_options", + "decl": { + "args": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_certificate_request", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_certificates", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_keypair", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "crypto.x509.parse_rsa_private_key", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "div", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "infix": "/" + }, + { + "name": "endswith", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "eq", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "=" + }, + { + "name": "equal", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "==" + }, + { + "name": "floor", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "format_int", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "glob.match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "of": [ + { + "type": "null" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + } + ], + "type": "any" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "glob.quote_meta", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "graph.reachable", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "graph.reachable_paths", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "graphql.is_valid", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "graphql.parse", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "graphql.parse_and_verify", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "graphql.parse_query", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "graphql.parse_schema", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "graphql.schema_is_valid", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "gt", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "\u003e" + }, + { + "name": "gte", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "\u003e=" + }, + { + "name": "hex.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "hex.encode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "http.send", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "indexof", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "indexof_n", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "internal.member_2", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "in" + }, + { + "name": "internal.member_3", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "in" + }, + { + "name": "internal.print", + "decl": { + "args": [ + { + "dynamic": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "array" + } + ], + "type": "function" + } + }, + { + "name": "intersection", + "decl": { + "args": [ + { + "of": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "io.jwt.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "static": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "type": "string" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "io.jwt.decode_verify", + "decl": { + "args": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "array" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "io.jwt.encode_sign", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "type": "string" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "io.jwt.encode_sign_raw", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "io.jwt.verify_es256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_es384", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_es512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_hs256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_hs384", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_hs512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_ps256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_ps384", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_ps512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_rs256", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_rs384", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "io.jwt.verify_rs512", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_array", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_boolean", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_null", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_number", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_object", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_set", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "is_string", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "json.filter", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "of": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "json.is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "json.marshal", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "json.marshal_with_options", + "decl": { + "args": [ + { + "type": "any" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "static": [ + { + "key": "indent", + "value": { + "type": "string" + } + }, + { + "key": "prefix", + "value": { + "type": "string" + } + }, + { + "key": "pretty", + "value": { + "type": "boolean" + } + } + ], + "type": "object" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "json.match_schema", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "dynamic": { + "static": [ + { + "key": "desc", + "value": { + "type": "string" + } + }, + { + "key": "error", + "value": { + "type": "string" + } + }, + { + "key": "field", + "value": { + "type": "string" + } + }, + { + "key": "type", + "value": { + "type": "string" + } + } + ], + "type": "object" + }, + "type": "array" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "json.patch", + "decl": { + "args": [ + { + "type": "any" + }, + { + "dynamic": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "static": [ + { + "key": "op", + "value": { + "type": "string" + } + }, + { + "key": "path", + "value": { + "type": "any" + } + } + ], + "type": "object" + }, + "type": "array" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "json.remove", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "of": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "json.unmarshal", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "json.verify_schema", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "boolean" + }, + { + "of": [ + { + "type": "null" + }, + { + "type": "string" + } + ], + "type": "any" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "lower", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "lt", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "\u003c" + }, + { + "name": "lte", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "\u003c=" + }, + { + "name": "max", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "min", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "minus", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "number" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": [ + { + "type": "number" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + }, + "type": "function" + }, + "infix": "-" + }, + { + "name": "mul", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "infix": "*" + }, + { + "name": "neq", + "decl": { + "args": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + }, + "infix": "!=" + }, + { + "name": "net.cidr_contains", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "net.cidr_contains_matches", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": { + "static": [ + { + "type": "any" + }, + { + "type": "any" + } + ], + "type": "array" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "net.cidr_expand", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "of": { + "type": "string" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "net.cidr_intersects", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "net.cidr_is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "net.cidr_merge", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "of": [ + { + "type": "string" + } + ], + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "of": { + "type": "string" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "net.cidr_overlap", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "net.lookup_ip_addr", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "of": { + "type": "string" + }, + "type": "set" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "numbers.range", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "numbers.range_step", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "object.filter", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.get", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "type": "any" + }, + { + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.keys", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "object.remove", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.subset", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.union", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "object.union_n", + "decl": { + "args": [ + { + "dynamic": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "array" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "opa.runtime", + "decl": { + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "or", + "decl": { + "args": [ + { + "of": { + "type": "any" + }, + "type": "set" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + }, + "infix": "|" + }, + { + "name": "plus", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "infix": "+" + }, + { + "name": "print", + "decl": { + "type": "function", + "variadic": { + "type": "any" + } + } + }, + { + "name": "product", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + { + "of": { + "type": "number" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "providers.aws.sign_req", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "key": { + "type": "any" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "rand.intn", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "re_match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "regex.find_all_string_submatch_n", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "regex.find_n", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "number" + } + ], + "result": { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "regex.globs_match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "regex.is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "regex.match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "regex.replace", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "regex.split", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "regex.template_match", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "rego.metadata.chain", + "decl": { + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "rego.metadata.rule", + "decl": { + "result": { + "type": "any" + }, + "type": "function" + } + }, + { + "name": "rego.parse_module", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "rem", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + }, + "infix": "%" + }, + { + "name": "replace", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "round", + "decl": { + "args": [ + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "semver.compare", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "semver.is_valid", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "set_diff", + "decl": { + "args": [ + { + "of": { + "type": "any" + }, + "type": "set" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "sort", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "of": { + "type": "any" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "split", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + "type": "function" + } + }, + { + "name": "sprintf", + "decl": { + "args": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "any" + }, + "type": "array" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "startswith", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "strings.any_prefix_match", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "strings.any_suffix_match", + "decl": { + "args": [ + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "strings.count", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "strings.render_template", + "decl": { + "args": [ + { + "type": "string" + }, + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "strings.replace_n", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "type": "object" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "strings.reverse", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "substring", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "sum", + "decl": { + "args": [ + { + "of": [ + { + "dynamic": { + "type": "number" + }, + "type": "array" + }, + { + "of": { + "type": "number" + }, + "type": "set" + } + ], + "type": "any" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.add_date", + "decl": { + "args": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.clock", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "time.date", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "time.diff", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + }, + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "static": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "type": "array" + }, + "type": "function" + } + }, + { + "name": "time.format", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "time.now_ns", + "decl": { + "result": { + "type": "number" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "time.parse_duration_ns", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.parse_ns", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.parse_rfc3339_ns", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "time.weekday", + "decl": { + "args": [ + { + "of": [ + { + "type": "number" + }, + { + "static": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "array" + } + ], + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "to_number", + "decl": { + "args": [ + { + "of": [ + { + "type": "null" + }, + { + "type": "boolean" + }, + { + "type": "number" + }, + { + "type": "string" + } + ], + "type": "any" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "trace", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "trim", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_left", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_prefix", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_right", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_space", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "trim_suffix", + "decl": { + "args": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "type_name", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "union", + "decl": { + "args": [ + { + "of": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "set" + } + ], + "result": { + "of": { + "type": "any" + }, + "type": "set" + }, + "type": "function" + } + }, + { + "name": "units.parse", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "units.parse_bytes", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "number" + }, + "type": "function" + } + }, + { + "name": "upper", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "urlquery.decode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "urlquery.decode_object", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "dynamic": { + "type": "string" + }, + "type": "array" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "urlquery.encode", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "urlquery.encode_object", + "decl": { + "args": [ + { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "of": [ + { + "type": "string" + }, + { + "dynamic": { + "type": "string" + }, + "type": "array" + }, + { + "of": { + "type": "string" + }, + "type": "set" + } + ], + "type": "any" + } + }, + "type": "object" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "uuid.parse", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "dynamic": { + "key": { + "type": "string" + }, + "value": { + "type": "any" + } + }, + "type": "object" + }, + "type": "function" + } + }, + { + "name": "uuid.rfc4122", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "string" + }, + "type": "function" + }, + "nondeterministic": true + }, + { + "name": "walk", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "static": [ + { + "dynamic": { + "type": "any" + }, + "type": "array" + }, + { + "type": "any" + } + ], + "type": "array" + }, + "type": "function" + }, + "relation": true + }, + { + "name": "yaml.is_valid", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "boolean" + }, + "type": "function" + } + }, + { + "name": "yaml.marshal", + "decl": { + "args": [ + { + "type": "any" + } + ], + "result": { + "type": "string" + }, + "type": "function" + } + }, + { + "name": "yaml.unmarshal", + "decl": { + "args": [ + { + "type": "string" + } + ], + "result": { + "type": "any" + }, + "type": "function" + } + } + ], + "wasm_abi_versions": [ + { + "version": 1, + "minor_version": 1 + }, + { + "version": 1, + "minor_version": 2 + } + ], + "features": [ + "rego_v1" + ] +} diff --git a/vendor/github.com/open-policy-agent/opa/internal/bundle/utils.go b/vendor/github.com/open-policy-agent/opa/internal/bundle/utils.go index 064649733a..3d67d56929 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/bundle/utils.go +++ b/vendor/github.com/open-policy-agent/opa/internal/bundle/utils.go @@ -11,10 +11,10 @@ import ( "os" "path/filepath" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/bundle" - "github.com/open-policy-agent/opa/resolver/wasm" - "github.com/open-policy-agent/opa/storage" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/bundle" + "github.com/open-policy-agent/opa/v1/resolver/wasm" + "github.com/open-policy-agent/opa/v1/storage" ) // LoadWasmResolversFromStore will lookup all Wasm modules from the store along with the diff --git a/vendor/github.com/open-policy-agent/opa/internal/compiler/utils.go b/vendor/github.com/open-policy-agent/opa/internal/compiler/utils.go index 4d80aeeef9..dfb781e19b 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/compiler/utils.go +++ b/vendor/github.com/open-policy-agent/opa/internal/compiler/utils.go @@ -5,9 +5,9 @@ package compiler import ( - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/schemas" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/schemas" + "github.com/open-policy-agent/opa/v1/util" ) type SchemaFile string @@ -32,7 +32,10 @@ func VerifyAuthorizationPolicySchema(compiler *ast.Compiler, ref ast.Ref) error schemaSet := ast.NewSchemaSet() schemaSet.Put(ast.SchemaRootRef, schemaDefinitions[AuthorizationPolicySchema]) - errs := ast.NewCompiler().WithSchemas(schemaSet).PassesTypeCheckRules(rules) + errs := ast.NewCompiler(). + WithDefaultRegoVersion(compiler.DefaultRegoVersion()). + WithSchemas(schemaSet). + PassesTypeCheckRules(rules) if len(errs) > 0 { return errs diff --git a/vendor/github.com/open-policy-agent/opa/internal/compiler/wasm/opa/callgraph.csv b/vendor/github.com/open-policy-agent/opa/internal/compiler/wasm/opa/callgraph.csv index 48c809d656..473497abbd 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/compiler/wasm/opa/callgraph.csv +++ b/vendor/github.com/open-policy-agent/opa/internal/compiler/wasm/opa/callgraph.csv @@ -749,12 +749,12 @@ opa_set_get,opa_value_hash opa_set_get,opa_value_compare opa_number_try_int,opa_atoi64 opa_number_try_int,opa_abort -opa_value_get,opa_abort opa_value_get,opa_atoi64 opa_value_get,opa_value_hash opa_value_get,opa_value_compare -opa_value_compare_number,opa_atoi64 +opa_value_get,opa_abort opa_value_compare_number,opa_abort +opa_value_compare_number,opa_atoi64 opa_value_compare_number,opa_number_to_bf opa_value_compare_number,mpd_qcmp opa_value_compare_number,mpd_del @@ -779,10 +779,10 @@ opa_value_compare_set,opa_value_compare_set opa_value_compare_set,opa_abort opa_number_hash,opa_atof64 opa_number_hash,opa_abort -opa_value_iter,opa_abort opa_value_iter,opa_atoi64 opa_value_iter,opa_value_hash opa_value_iter,opa_value_compare +opa_value_iter,opa_abort opa_object_keys,opa_malloc opa_object_keys,opa_free opa_object_keys,opa_value_compare @@ -817,7 +817,6 @@ opa_value_merge,opa_malloc opa_value_merge,opa_value_get opa_value_merge,__opa_object_insert opa_value_merge,opa_value_merge -opa_value_merge,opa_abort opa_value_merge,opa_atoi64 opa_value_merge,opa_value_hash opa_value_merge,opa_value_compare_number @@ -825,6 +824,7 @@ opa_value_merge,opa_strncmp opa_value_merge,opa_value_compare opa_value_merge,opa_value_compare_object opa_value_merge,opa_value_compare_set +opa_value_merge,opa_abort __opa_object_insert,opa_value_hash __opa_object_insert,opa_value_compare __opa_object_insert,__opa_value_free @@ -904,8 +904,8 @@ opa_value_remove_path,opa_value_get opa_value_remove_path,opa_object_remove opa_lookup,opa_value_get opa_lookup,opa_value_iter -opa_lookup,opa_atoi64 opa_lookup,opa_abort +opa_lookup,opa_atoi64 opa_mapping_init,opa_json_parse opa_mapping_lookup,opa_lookup node::re2\28std::__1::basic_string\2c\20std::__1::allocator\20>\20const&\29,std::__1::basic_string\2c\20std::__1::allocator\20>::assign\28char\20const*\29 diff --git a/vendor/github.com/open-policy-agent/opa/internal/compiler/wasm/opa/opa.wasm b/vendor/github.com/open-policy-agent/opa/internal/compiler/wasm/opa/opa.wasm index eb3147b8a8..667b9cdd49 100644 Binary files a/vendor/github.com/open-policy-agent/opa/internal/compiler/wasm/opa/opa.wasm and b/vendor/github.com/open-policy-agent/opa/internal/compiler/wasm/opa/opa.wasm differ diff --git a/vendor/github.com/open-policy-agent/opa/internal/compiler/wasm/wasm.go b/vendor/github.com/open-policy-agent/opa/internal/compiler/wasm/wasm.go index 9a5cebec54..08dfe44862 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/compiler/wasm/wasm.go +++ b/vendor/github.com/open-policy-agent/opa/internal/compiler/wasm/wasm.go @@ -12,7 +12,6 @@ import ( "fmt" "io" - "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/internal/compiler/wasm/opa" "github.com/open-policy-agent/opa/internal/debug" "github.com/open-policy-agent/opa/internal/wasm/encoding" @@ -20,8 +19,9 @@ import ( "github.com/open-policy-agent/opa/internal/wasm/module" "github.com/open-policy-agent/opa/internal/wasm/types" "github.com/open-policy-agent/opa/internal/wasm/util" - "github.com/open-policy-agent/opa/ir" - opatypes "github.com/open-policy-agent/opa/types" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/ir" + opatypes "github.com/open-policy-agent/opa/v1/types" ) // Record Wasm ABI version in exported global variable diff --git a/vendor/github.com/open-policy-agent/opa/internal/config/config.go b/vendor/github.com/open-policy-agent/opa/internal/config/config.go index b1a9731f65..fdac487720 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/config/config.go +++ b/vendor/github.com/open-policy-agent/opa/internal/config/config.go @@ -15,11 +15,11 @@ import ( "sigs.k8s.io/yaml" "github.com/open-policy-agent/opa/internal/strvals" - "github.com/open-policy-agent/opa/keys" - "github.com/open-policy-agent/opa/logging" - "github.com/open-policy-agent/opa/plugins/rest" - "github.com/open-policy-agent/opa/tracing" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/keys" + "github.com/open-policy-agent/opa/v1/logging" + "github.com/open-policy-agent/opa/v1/plugins/rest" + "github.com/open-policy-agent/opa/v1/tracing" + "github.com/open-policy-agent/opa/v1/util" ) // ServiceOptions stores the options passed to ParseServicesConfig diff --git a/vendor/github.com/open-policy-agent/opa/internal/edittree/edittree.go b/vendor/github.com/open-policy-agent/opa/internal/edittree/edittree.go index 9cfaee8baf..4a4f8101f8 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/edittree/edittree.go +++ b/vendor/github.com/open-policy-agent/opa/internal/edittree/edittree.go @@ -146,14 +146,13 @@ package edittree import ( - "encoding/json" "fmt" "math/big" "sort" "strings" - "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/internal/edittree/bitvector" + "github.com/open-policy-agent/opa/v1/ast" ) // Deletions are encoded with a nil value pointer. @@ -213,10 +212,10 @@ func (e *EditTree) getKeyHash(key *ast.Term) (int, bool) { case ast.Null, ast.Boolean, ast.String, ast.Var: equal = func(y ast.Value) bool { return x == y } case ast.Number: - if xi, err := json.Number(x).Int64(); err == nil { + if xi, ok := x.Int64(); ok { equal = func(y ast.Value) bool { if y, ok := y.(ast.Number); ok { - if yi, err := json.Number(y).Int64(); err == nil { + if yi, ok := y.Int64(); ok { return xi == yi } } @@ -725,9 +724,9 @@ func (e *EditTree) Unfold(path ast.Ref) (*EditTree, error) { // Fall back to looking up the key in e.value. // Extend the tree if key is present. Error otherwise. - if v, err := x.Find(ast.Ref{ast.IntNumberTerm(idx)}); err == nil { + if v, err := x.Find(ast.Ref{ast.InternedIntNumberTerm(idx)}); err == nil { // TODO: Consider a more efficient "Replace" function that special-cases this for arrays instead? - _, err := e.Delete(ast.IntNumberTerm(idx)) + _, err := e.Delete(ast.InternedIntNumberTerm(idx)) if err != nil { return nil, err } @@ -1026,8 +1025,7 @@ func (e *EditTree) Exists(path ast.Ref) bool { } // Fallback if child lookup failed. // We have to ensure that the lookup term is a number here, or Find will fail. - k := ast.Ref{ast.IntNumberTerm(idx)}.Concat(path[1:]) - _, err = x.Find(k) + _, err = x.Find(ast.Ref{ast.InternedIntNumberTerm(idx)}.Concat(path[1:])) return err == nil default: // Catch all primitive types. diff --git a/vendor/github.com/open-policy-agent/opa/internal/future/filter_imports.go b/vendor/github.com/open-policy-agent/opa/internal/future/filter_imports.go index 2863aad4e9..eb6091cc6e 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/future/filter_imports.go +++ b/vendor/github.com/open-policy-agent/opa/internal/future/filter_imports.go @@ -4,7 +4,7 @@ package future -import "github.com/open-policy-agent/opa/ast" +import "github.com/open-policy-agent/opa/v1/ast" // FilterFutureImports filters OUT any future imports from the passed slice of // `*ast.Import`s. @@ -35,3 +35,15 @@ func IsFutureKeyword(imp *ast.Import, kw string) bool { path[1].Equal(ast.StringTerm("keywords")) && path[2].Equal(ast.StringTerm(kw)) } + +func WhichFutureKeyword(imp *ast.Import) (string, bool) { + path := imp.Path.Value.(ast.Ref) + if len(path) == 3 && + ast.FutureRootDocument.Equal(path[0]) && + path[1].Equal(ast.StringTerm("keywords")) { + if str, ok := path[2].Value.(ast.String); ok { + return string(str), true + } + } + return "", false +} diff --git a/vendor/github.com/open-policy-agent/opa/internal/future/parser_opts.go b/vendor/github.com/open-policy-agent/opa/internal/future/parser_opts.go index 804702b945..84a5292870 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/future/parser_opts.go +++ b/vendor/github.com/open-policy-agent/opa/internal/future/parser_opts.go @@ -7,7 +7,7 @@ package future import ( "fmt" - "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/v1/ast" ) // ParserOptionsFromFutureImports transforms a slice of `ast.Import`s into the diff --git a/vendor/github.com/open-policy-agent/opa/internal/gojsonschema/schemaReferencePool.go b/vendor/github.com/open-policy-agent/opa/internal/gojsonschema/schemaReferencePool.go index 876419f56c..515702095b 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/gojsonschema/schemaReferencePool.go +++ b/vendor/github.com/open-policy-agent/opa/internal/gojsonschema/schemaReferencePool.go @@ -25,10 +25,6 @@ package gojsonschema -import ( - "fmt" -) - type schemaReferencePool struct { documents map[string]*SubSchema } @@ -44,7 +40,7 @@ func newSchemaReferencePool() *schemaReferencePool { func (p *schemaReferencePool) Get(ref string) (r *SubSchema, o bool) { if internalLogEnabled { - internalLog(fmt.Sprintf("Schema Reference ( %s )", ref)) + internalLog("Schema Reference ( %s )", ref) } if sch, ok := p.documents[ref]; ok { @@ -60,7 +56,7 @@ func (p *schemaReferencePool) Get(ref string) (r *SubSchema, o bool) { func (p *schemaReferencePool) Add(ref string, sch *SubSchema) { if internalLogEnabled { - internalLog(fmt.Sprintf("Add Schema Reference %s to pool", ref)) + internalLog("Add Schema Reference %s to pool", ref) } if _, ok := p.documents[ref]; !ok { p.documents[ref] = sch diff --git a/vendor/github.com/open-policy-agent/opa/internal/gojsonschema/validation.go b/vendor/github.com/open-policy-agent/opa/internal/gojsonschema/validation.go index 7c86e37245..efdea58b6b 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/gojsonschema/validation.go +++ b/vendor/github.com/open-policy-agent/opa/internal/gojsonschema/validation.go @@ -348,7 +348,7 @@ func (v *SubSchema) validateSchema(currentSubSchema *SubSchema, currentNode inte } } - if currentSubSchema.dependencies != nil && len(currentSubSchema.dependencies) > 0 { + if len(currentSubSchema.dependencies) > 0 { if currentNodeMap, ok := currentNode.(map[string]interface{}); ok { for elementKey := range currentNodeMap { if dependency, ok := currentSubSchema.dependencies[elementKey]; ok { @@ -469,7 +469,7 @@ func (v *SubSchema) validateArray(currentSubSchema *SubSchema, value []interface result.mergeErrors(validationResult) } } else { - if currentSubSchema.ItemsChildren != nil && len(currentSubSchema.ItemsChildren) > 0 { + if len(currentSubSchema.ItemsChildren) > 0 { nbItems := len(currentSubSchema.ItemsChildren) diff --git a/vendor/github.com/open-policy-agent/opa/internal/gqlparser/validator/rules/fields_on_correct_type.go b/vendor/github.com/open-policy-agent/opa/internal/gqlparser/validator/rules/fields_on_correct_type.go index d536e5e5f4..f681767475 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/gqlparser/validator/rules/fields_on_correct_type.go +++ b/vendor/github.com/open-policy-agent/opa/internal/gqlparser/validator/rules/fields_on_correct_type.go @@ -27,7 +27,7 @@ func init() { } addError( - Message(message), + Message(message), //nolint:govet At(field.Position), ) }) diff --git a/vendor/github.com/open-policy-agent/opa/internal/gqlparser/validator/rules/fragments_on_composite_types.go b/vendor/github.com/open-policy-agent/opa/internal/gqlparser/validator/rules/fragments_on_composite_types.go index 66bd348c47..861e3b16cf 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/gqlparser/validator/rules/fragments_on_composite_types.go +++ b/vendor/github.com/open-policy-agent/opa/internal/gqlparser/validator/rules/fragments_on_composite_types.go @@ -20,7 +20,7 @@ func init() { message := fmt.Sprintf(`Fragment cannot condition on non composite type "%s".`, inlineFragment.TypeCondition) addError( - Message(message), + Message(message), //nolint:govet At(inlineFragment.Position), ) }) @@ -33,7 +33,7 @@ func init() { message := fmt.Sprintf(`Fragment "%s" cannot condition on non composite type "%s".`, fragment.Name, fragment.TypeCondition) addError( - Message(message), + Message(message), //nolint:govet At(fragment.Position), ) }) diff --git a/vendor/github.com/open-policy-agent/opa/internal/json/patch/patch.go b/vendor/github.com/open-policy-agent/opa/internal/json/patch/patch.go index 31c89869da..5506180799 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/json/patch/patch.go +++ b/vendor/github.com/open-policy-agent/opa/internal/json/patch/patch.go @@ -7,7 +7,7 @@ package patch import ( "strings" - "github.com/open-policy-agent/opa/storage" + "github.com/open-policy-agent/opa/v1/storage" ) // ParsePatchPathEscaped returns a new path for the given escaped str. diff --git a/vendor/github.com/open-policy-agent/opa/internal/planner/planner.go b/vendor/github.com/open-policy-agent/opa/internal/planner/planner.go index b75d26ddab..160775c0e9 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/planner/planner.go +++ b/vendor/github.com/open-policy-agent/opa/internal/planner/planner.go @@ -11,10 +11,10 @@ import ( "io" "sort" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/ast/location" "github.com/open-policy-agent/opa/internal/debug" - "github.com/open-policy-agent/opa/ir" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/ast/location" + "github.com/open-policy-agent/opa/v1/ir" ) // QuerySet represents the input to the planner. @@ -1037,7 +1037,7 @@ func (p *Planner) planExprCall(e *ast.Expr, iter planiter) error { args = p.defaultOperands() } else if decl, ok := p.decls[operator]; ok { relation = decl.Relation - arity = len(decl.Decl.Args()) + arity = decl.Decl.Arity() void = decl.Decl.Result() == nil name = operator p.externs[operator] = decl @@ -1519,7 +1519,7 @@ func (p *Planner) planValue(t ast.Value, loc *ast.Location, iter planiter) error p.loc = loc return p.planObjectComprehension(v, iter) default: - return fmt.Errorf("%v term not implemented", ast.TypeName(v)) + return fmt.Errorf("%v term not implemented", ast.ValueName(v)) } } diff --git a/vendor/github.com/open-policy-agent/opa/internal/planner/rules.go b/vendor/github.com/open-policy-agent/opa/internal/planner/rules.go index f5d6f3fc6c..2f424da526 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/planner/rules.go +++ b/vendor/github.com/open-policy-agent/opa/internal/planner/rules.go @@ -4,7 +4,7 @@ import ( "fmt" "sort" - "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/v1/ast" ) // funcstack implements a simple map structure used to keep track of virtual diff --git a/vendor/github.com/open-policy-agent/opa/internal/planner/varstack.go b/vendor/github.com/open-policy-agent/opa/internal/planner/varstack.go index dccff1b5c1..0df6bcd8b2 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/planner/varstack.go +++ b/vendor/github.com/open-policy-agent/opa/internal/planner/varstack.go @@ -5,8 +5,8 @@ package planner import ( - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/ir" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/ir" ) type varstack []map[ast.Var]ir.Local diff --git a/vendor/github.com/open-policy-agent/opa/internal/providers/aws/ecr.go b/vendor/github.com/open-policy-agent/opa/internal/providers/aws/ecr.go index 179b5b5d5e..55e587e9f5 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/providers/aws/ecr.go +++ b/vendor/github.com/open-policy-agent/opa/internal/providers/aws/ecr.go @@ -11,7 +11,7 @@ import ( "time" "github.com/open-policy-agent/opa/internal/version" - "github.com/open-policy-agent/opa/logging" + "github.com/open-policy-agent/opa/v1/logging" ) // Values taken from diff --git a/vendor/github.com/open-policy-agent/opa/internal/providers/aws/kms.go b/vendor/github.com/open-policy-agent/opa/internal/providers/aws/kms.go index 77c0bc9349..6dfb06a496 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/providers/aws/kms.go +++ b/vendor/github.com/open-policy-agent/opa/internal/providers/aws/kms.go @@ -10,7 +10,7 @@ import ( "time" "github.com/open-policy-agent/opa/internal/version" - "github.com/open-policy-agent/opa/logging" + "github.com/open-policy-agent/opa/v1/logging" ) // Values taken from diff --git a/vendor/github.com/open-policy-agent/opa/internal/providers/aws/signing_v4.go b/vendor/github.com/open-policy-agent/opa/internal/providers/aws/signing_v4.go index bfb780754b..1e50d01f92 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/providers/aws/signing_v4.go +++ b/vendor/github.com/open-policy-agent/opa/internal/providers/aws/signing_v4.go @@ -13,13 +13,13 @@ import ( "io" "net/http" "net/url" - "sort" "strings" "time" v4 "github.com/open-policy-agent/opa/internal/providers/aws/v4" - "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/util" ) func stringFromTerm(t *ast.Term) string { @@ -67,19 +67,6 @@ func sha256MAC(message string, key []byte) []byte { return mac.Sum(nil) } -func sortKeys(strMap map[string][]string) []string { - keys := make([]string, len(strMap)) - - i := 0 - for k := range strMap { - keys[i] = k - i++ - } - sort.Strings(keys) - - return keys -} - // SignRequest modifies an http.Request to include an AWS V4 signature based on the provided credentials. func SignRequest(req *http.Request, service string, creds Credentials, theTime time.Time, sigVersion string) error { // General ref. https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html @@ -168,7 +155,7 @@ func SignV4(headers map[string][]string, method string, theURL *url.URL, body [] canonicalReq += theURL.RawQuery + "\n" // RAW Query String // include the values for the signed headers - orderedKeys := sortKeys(headersToSign) + orderedKeys := util.KeysSorted(headersToSign) for _, k := range orderedKeys { canonicalReq += k + ":" + strings.Join(headersToSign[k], ",") + "\n" } diff --git a/vendor/github.com/open-policy-agent/opa/internal/providers/aws/util.go b/vendor/github.com/open-policy-agent/opa/internal/providers/aws/util.go index e033da7460..9ce9af90da 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/providers/aws/util.go +++ b/vendor/github.com/open-policy-agent/opa/internal/providers/aws/util.go @@ -5,7 +5,7 @@ import ( "io" "net/http" - "github.com/open-policy-agent/opa/logging" + "github.com/open-policy-agent/opa/v1/logging" ) // DoRequestWithClient is a convenience function to get the body of an HTTP response with diff --git a/vendor/github.com/open-policy-agent/opa/internal/ref/ref.go b/vendor/github.com/open-policy-agent/opa/internal/ref/ref.go index 6e84df4b08..173b5a3c1b 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/ref/ref.go +++ b/vendor/github.com/open-policy-agent/opa/internal/ref/ref.go @@ -9,8 +9,8 @@ import ( "errors" "strings" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/storage" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/storage" ) // ParseDataPath returns a ref from the slash separated path s rooted at data. diff --git a/vendor/github.com/open-policy-agent/opa/internal/rego/opa/options.go b/vendor/github.com/open-policy-agent/opa/internal/rego/opa/options.go index ea1e339c1b..072e37667a 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/rego/opa/options.go +++ b/vendor/github.com/open-policy-agent/opa/internal/rego/opa/options.go @@ -4,11 +4,11 @@ import ( "io" "time" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/metrics" - "github.com/open-policy-agent/opa/topdown/builtins" - "github.com/open-policy-agent/opa/topdown/cache" - "github.com/open-policy-agent/opa/topdown/print" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/metrics" + "github.com/open-policy-agent/opa/v1/topdown/builtins" + "github.com/open-policy-agent/opa/v1/topdown/cache" + "github.com/open-policy-agent/opa/v1/topdown/print" ) // Result holds the evaluation result. @@ -18,13 +18,14 @@ type Result struct { // EvalOpts define options for performing an evaluation. type EvalOpts struct { - Input *interface{} - Metrics metrics.Metrics - Entrypoint int32 - Time time.Time - Seed io.Reader - InterQueryBuiltinCache cache.InterQueryCache - NDBuiltinCache builtins.NDBCache - PrintHook print.Hook - Capabilities *ast.Capabilities + Input *interface{} + Metrics metrics.Metrics + Entrypoint int32 + Time time.Time + Seed io.Reader + InterQueryBuiltinCache cache.InterQueryCache + InterQueryBuiltinValueCache cache.InterQueryValueCache + NDBuiltinCache builtins.NDBCache + PrintHook print.Hook + Capabilities *ast.Capabilities } diff --git a/vendor/github.com/open-policy-agent/opa/internal/report/report.go b/vendor/github.com/open-policy-agent/opa/internal/report/report.go index 145d0a9465..55f4cfe210 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/report/report.go +++ b/vendor/github.com/open-policy-agent/opa/internal/report/report.go @@ -17,12 +17,12 @@ import ( "sync" "time" - "github.com/open-policy-agent/opa/keys" - "github.com/open-policy-agent/opa/logging" + "github.com/open-policy-agent/opa/v1/keys" + "github.com/open-policy-agent/opa/v1/logging" + "github.com/open-policy-agent/opa/v1/version" - "github.com/open-policy-agent/opa/plugins/rest" - "github.com/open-policy-agent/opa/util" - "github.com/open-policy-agent/opa/version" + "github.com/open-policy-agent/opa/v1/plugins/rest" + "github.com/open-policy-agent/opa/v1/util" ) // ExternalServiceURL is the base HTTP URL for a telemetry service. diff --git a/vendor/github.com/open-policy-agent/opa/internal/runtime/init/init.go b/vendor/github.com/open-policy-agent/opa/internal/runtime/init/init.go index b1a5b71577..814847a12a 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/runtime/init/init.go +++ b/vendor/github.com/open-policy-agent/opa/internal/runtime/init/init.go @@ -12,12 +12,12 @@ import ( "path/filepath" "strings" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/bundle" storedversion "github.com/open-policy-agent/opa/internal/version" - "github.com/open-policy-agent/opa/loader" - "github.com/open-policy-agent/opa/metrics" - "github.com/open-policy-agent/opa/storage" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/bundle" + "github.com/open-policy-agent/opa/v1/loader" + "github.com/open-policy-agent/opa/v1/metrics" + "github.com/open-policy-agent/opa/v1/storage" ) // InsertAndCompileOptions contains the input for the operation. @@ -53,6 +53,7 @@ func InsertAndCompile(ctx context.Context, opts InsertAndCompileOptions) (*Inser } compiler := ast.NewCompiler(). + WithDefaultRegoVersion(opts.ParserOptions.RegoVersion). SetErrorLimit(opts.MaxErrors). WithPathConflictsCheck(storage.NonEmpty(ctx, opts.Store, opts.Txn)). WithEnablePrintStatements(opts.EnablePrintStatements) diff --git a/vendor/github.com/open-policy-agent/opa/internal/strvals/parser.go b/vendor/github.com/open-policy-agent/opa/internal/strvals/parser.go index 1fc07f68c3..1eceb83df9 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/strvals/parser.go +++ b/vendor/github.com/open-policy-agent/opa/internal/strvals/parser.go @@ -31,7 +31,7 @@ var ErrNotList = errors.New("not a list") // MaxIndex is the maximum index that will be allowed by setIndex. // The default value 65536 = 1024 * 64 -var MaxIndex = 65536 +const MaxIndex = 65536 // ToYAML takes a string of arguments and converts to a YAML document. func ToYAML(s string) (string, error) { diff --git a/vendor/github.com/open-policy-agent/opa/internal/version/version.go b/vendor/github.com/open-policy-agent/opa/internal/version/version.go index 1c2e9ecd01..dc52733fc2 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/version/version.go +++ b/vendor/github.com/open-policy-agent/opa/internal/version/version.go @@ -10,8 +10,8 @@ import ( "fmt" "runtime" - "github.com/open-policy-agent/opa/storage" - "github.com/open-policy-agent/opa/version" + "github.com/open-policy-agent/opa/v1/storage" + "github.com/open-policy-agent/opa/v1/version" ) var versionPath = storage.MustParsePath("/system/version") diff --git a/vendor/github.com/open-policy-agent/opa/internal/wasm/encoding/reader.go b/vendor/github.com/open-policy-agent/opa/internal/wasm/encoding/reader.go index 35e6059c72..7120392ce2 100644 --- a/vendor/github.com/open-policy-agent/opa/internal/wasm/encoding/reader.go +++ b/vendor/github.com/open-policy-agent/opa/internal/wasm/encoding/reader.go @@ -809,19 +809,19 @@ func readLimits(r io.Reader, l *module.Limit) error { return err } - min, err := leb128.ReadVarUint32(r) + minLim, err := leb128.ReadVarUint32(r) if err != nil { return err } - l.Min = min + l.Min = minLim if b == 1 { - max, err := leb128.ReadVarUint32(r) + maxLim, err := leb128.ReadVarUint32(r) if err != nil { return err } - l.Max = &max + l.Max = &maxLim } else if b != 0 { return fmt.Errorf("illegal limit flag") } diff --git a/vendor/github.com/open-policy-agent/opa/topdown/glob.go b/vendor/github.com/open-policy-agent/opa/topdown/glob.go deleted file mode 100644 index 116602db74..0000000000 --- a/vendor/github.com/open-policy-agent/opa/topdown/glob.go +++ /dev/null @@ -1,95 +0,0 @@ -package topdown - -import ( - "strings" - "sync" - - "github.com/gobwas/glob" - - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" -) - -const globCacheMaxSize = 100 - -var globCacheLock = sync.Mutex{} -var globCache map[string]glob.Glob - -func builtinGlobMatch(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { - pattern, err := builtins.StringOperand(operands[0].Value, 1) - if err != nil { - return err - } - - var delimiters []rune - switch operands[1].Value.(type) { - case ast.Null: - delimiters = []rune{} - case *ast.Array: - delimiters, err = builtins.RuneSliceOperand(operands[1].Value, 2) - if err != nil { - return err - } - if len(delimiters) == 0 { - delimiters = []rune{'.'} - } - default: - return builtins.NewOperandTypeErr(2, operands[1].Value, "array", "null") - } - - match, err := builtins.StringOperand(operands[2].Value, 3) - if err != nil { - return err - } - - builder := strings.Builder{} - builder.WriteString(string(pattern)) - builder.WriteRune('-') - for _, v := range delimiters { - builder.WriteRune(v) - } - id := builder.String() - - m, err := globCompileAndMatch(id, string(pattern), string(match), delimiters) - if err != nil { - return err - } - return iter(ast.BooleanTerm(m)) -} - -func globCompileAndMatch(id, pattern, match string, delimiters []rune) (bool, error) { - globCacheLock.Lock() - defer globCacheLock.Unlock() - p, ok := globCache[id] - if !ok { - var err error - if p, err = glob.Compile(pattern, delimiters...); err != nil { - return false, err - } - if len(globCache) >= globCacheMaxSize { - // Delete a (semi-)random key to make room for the new one. - for k := range globCache { - delete(globCache, k) - break - } - } - globCache[id] = p - } - out := p.Match(match) - return out, nil -} - -func builtinGlobQuoteMeta(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { - pattern, err := builtins.StringOperand(operands[0].Value, 1) - if err != nil { - return err - } - - return iter(ast.StringTerm(glob.QuoteMeta(string(pattern)))) -} - -func init() { - globCache = map[string]glob.Glob{} - RegisterBuiltinFunc(ast.GlobMatch.Name, builtinGlobMatch) - RegisterBuiltinFunc(ast.GlobQuoteMeta.Name, builtinGlobQuoteMeta) -} diff --git a/vendor/github.com/open-policy-agent/opa/topdown/type_name.go b/vendor/github.com/open-policy-agent/opa/topdown/type_name.go deleted file mode 100644 index 0a8b44aed3..0000000000 --- a/vendor/github.com/open-policy-agent/opa/topdown/type_name.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2018 The OPA Authors. All rights reserved. -// Use of this source code is governed by an Apache2 -// license that can be found in the LICENSE file. - -package topdown - -import ( - "fmt" - - "github.com/open-policy-agent/opa/ast" -) - -func builtinTypeName(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { - switch operands[0].Value.(type) { - case ast.Null: - return iter(ast.StringTerm("null")) - case ast.Boolean: - return iter(ast.StringTerm("boolean")) - case ast.Number: - return iter(ast.StringTerm("number")) - case ast.String: - return iter(ast.StringTerm("string")) - case *ast.Array: - return iter(ast.StringTerm("array")) - case ast.Object: - return iter(ast.StringTerm("object")) - case ast.Set: - return iter(ast.StringTerm("set")) - } - - return fmt.Errorf("illegal value") -} - -func init() { - RegisterBuiltinFunc(ast.TypeNameBuiltin.Name, builtinTypeName) -} diff --git a/vendor/github.com/open-policy-agent/opa/util/maps.go b/vendor/github.com/open-policy-agent/opa/util/maps.go deleted file mode 100644 index d943b4d0a8..0000000000 --- a/vendor/github.com/open-policy-agent/opa/util/maps.go +++ /dev/null @@ -1,10 +0,0 @@ -package util - -// Values returns a slice of values from any map. Copied from golang.org/x/exp/maps. -func Values[M ~map[K]V, K comparable, V any](m M) []V { - r := make([]V, 0, len(m)) - for _, v := range m { - r = append(r, v) - } - return r -} diff --git a/vendor/github.com/open-policy-agent/opa/ast/annotations.go b/vendor/github.com/open-policy-agent/opa/v1/ast/annotations.go similarity index 97% rename from vendor/github.com/open-policy-agent/opa/ast/annotations.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/annotations.go index 7d09379fd5..297c6907cd 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/annotations.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/annotations.go @@ -11,9 +11,9 @@ import ( "sort" "strings" - astJSON "github.com/open-policy-agent/opa/ast/json" "github.com/open-policy-agent/opa/internal/deepcopy" - "github.com/open-policy-agent/opa/util" + astJSON "github.com/open-policy-agent/opa/v1/ast/json" + "github.com/open-policy-agent/opa/v1/util" ) const ( @@ -38,9 +38,8 @@ type ( Custom map[string]interface{} `json:"custom,omitempty"` Location *Location `json:"location,omitempty"` - comments []*Comment - node Node - jsonOptions astJSON.Options + comments []*Comment + node Node } // SchemaAnnotation contains a schema declaration for the document identified by the path. @@ -77,8 +76,6 @@ type ( Annotations *Annotations `json:"annotations,omitempty"` Location *Location `json:"location,omitempty"` // The location of the node the annotations are applied to - jsonOptions astJSON.Options - node Node // The node the annotations are applied to } @@ -181,13 +178,6 @@ func (a *Annotations) GetTargetPath() Ref { } } -func (a *Annotations) setJSONOptions(opts astJSON.Options) { - a.jsonOptions = opts - if a.Location != nil { - a.Location.JSONOptions = opts - } -} - func (a *Annotations) MarshalJSON() ([]byte, error) { if a == nil { return []byte(`{"scope":""}`), nil @@ -229,7 +219,7 @@ func (a *Annotations) MarshalJSON() ([]byte, error) { data["custom"] = a.Custom } - if a.jsonOptions.MarshalOptions.IncludeLocation.Annotations { + if astJSON.GetOptions().MarshalOptions.IncludeLocation.Annotations { if a.Location != nil { data["location"] = a.Location } @@ -249,7 +239,6 @@ func NewAnnotationsRef(a *Annotations) *AnnotationsRef { Path: a.GetTargetPath(), Annotations: a, node: a.node, - jsonOptions: a.jsonOptions, } } @@ -282,10 +271,20 @@ func (ar *AnnotationsRef) MarshalJSON() ([]byte, error) { data["annotations"] = ar.Annotations } - if ar.jsonOptions.MarshalOptions.IncludeLocation.AnnotationsRef { + if astJSON.GetOptions().MarshalOptions.IncludeLocation.AnnotationsRef { if ar.Location != nil { data["location"] = ar.Location } + + // The location set for the schema ref terms is wrong (always set to + // row 1) and not really useful anyway.. so strip it out before marshalling + for _, schema := range ar.Annotations.Schemas { + if schema.Path != nil { + for _, term := range schema.Path { + term.Location = nil + } + } + } } return json.Marshal(data) @@ -520,7 +519,7 @@ func attachRuleAnnotations(mod *Module) { var j int var found bool for i, a := range cpy { - if rule.Ref().Equal(a.GetTargetPath()) { + if rule.Ref().GroundPrefix().Equal(a.GetTargetPath()) { if a.Scope == annotationScopeDocument { rule.Annotations = append(rule.Annotations, a) } else if a.Scope == annotationScopeRule && rule.Loc().Row > a.Location.Row { diff --git a/vendor/github.com/open-policy-agent/opa/ast/builtins.go b/vendor/github.com/open-policy-agent/opa/v1/ast/builtins.go similarity index 91% rename from vendor/github.com/open-policy-agent/opa/ast/builtins.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/builtins.go index f54d91d317..9585620dca 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/builtins.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/builtins.go @@ -7,7 +7,7 @@ package ast import ( "strings" - "github.com/open-policy-agent/opa/types" + "github.com/open-policy-agent/opa/v1/types" ) // Builtins is the registry of built-in functions supported by OPA. @@ -563,7 +563,7 @@ var Abs = &Builtin{ Description: "Returns the number without its sign.", Decl: types.NewFunction( types.Args( - types.Named("x", types.N), + types.Named("x", types.N).Description("the number to take the absolute value of"), ), types.Named("y", types.N).Description("the absolute value of `x`"), ), @@ -593,10 +593,10 @@ var BitsOr = &Builtin{ Description: "Returns the bitwise \"OR\" of two integers.", Decl: types.NewFunction( types.Args( - types.Named("x", types.N), - types.Named("y", types.N), + types.Named("x", types.N).Description("the first integer"), + types.Named("y", types.N).Description("the second integer"), ), - types.Named("z", types.N), + types.Named("z", types.N).Description("the bitwise OR of `x` and `y`"), ), } @@ -605,10 +605,10 @@ var BitsAnd = &Builtin{ Description: "Returns the bitwise \"AND\" of two integers.", Decl: types.NewFunction( types.Args( - types.Named("x", types.N), - types.Named("y", types.N), + types.Named("x", types.N).Description("the first integer"), + types.Named("y", types.N).Description("the second integer"), ), - types.Named("z", types.N), + types.Named("z", types.N).Description("the bitwise AND of `x` and `y`"), ), } @@ -617,9 +617,9 @@ var BitsNegate = &Builtin{ Description: "Returns the bitwise negation (flip) of an integer.", Decl: types.NewFunction( types.Args( - types.Named("x", types.N), + types.Named("x", types.N).Description("the integer to negate"), ), - types.Named("z", types.N), + types.Named("z", types.N).Description("the bitwise negation of `x`"), ), } @@ -628,10 +628,10 @@ var BitsXOr = &Builtin{ Description: "Returns the bitwise \"XOR\" (exclusive-or) of two integers.", Decl: types.NewFunction( types.Args( - types.Named("x", types.N), - types.Named("y", types.N), + types.Named("x", types.N).Description("the first integer"), + types.Named("y", types.N).Description("the second integer"), ), - types.Named("z", types.N), + types.Named("z", types.N).Description("the bitwise XOR of `x` and `y`"), ), } @@ -640,10 +640,10 @@ var BitsShiftLeft = &Builtin{ Description: "Returns a new integer with its bits shifted `s` bits to the left.", Decl: types.NewFunction( types.Args( - types.Named("x", types.N), - types.Named("s", types.N), + types.Named("x", types.N).Description("the integer to shift"), + types.Named("s", types.N).Description("the number of bits to shift"), ), - types.Named("z", types.N), + types.Named("z", types.N).Description("the result of shifting `x` `s` bits to the left"), ), } @@ -652,10 +652,10 @@ var BitsShiftRight = &Builtin{ Description: "Returns a new integer with its bits shifted `s` bits to the right.", Decl: types.NewFunction( types.Args( - types.Named("x", types.N), - types.Named("s", types.N), + types.Named("x", types.N).Description("the integer to shift"), + types.Named("s", types.N).Description("the number of bits to shift"), ), - types.Named("z", types.N), + types.Named("z", types.N).Description("the result of shifting `x` `s` bits to the right"), ), } @@ -671,8 +671,8 @@ var And = &Builtin{ Description: "Returns the intersection of two sets.", Decl: types.NewFunction( types.Args( - types.Named("x", types.NewSet(types.A)), - types.Named("y", types.NewSet(types.A)), + types.Named("x", types.NewSet(types.A)).Description("the first set"), + types.Named("y", types.NewSet(types.A)).Description("the second set"), ), types.Named("z", types.NewSet(types.A)).Description("the intersection of `x` and `y`"), ), @@ -749,7 +749,7 @@ var Sum = &Builtin{ types.Named("collection", types.NewAny( types.NewSet(types.N), types.NewArray(nil, types.N), - )), + )).Description("the set or array of numbers to sum"), ), types.Named("n", types.N).Description("the sum of all elements"), ), @@ -758,13 +758,13 @@ var Sum = &Builtin{ var Product = &Builtin{ Name: "product", - Description: "Muliplies elements of an array or set of numbers", + Description: "Multiplies elements of an array or set of numbers", Decl: types.NewFunction( types.Args( types.Named("collection", types.NewAny( types.NewSet(types.N), types.NewArray(nil, types.N), - )), + )).Description("the set or array of numbers to multiply"), ), types.Named("n", types.N).Description("the product of all elements"), ), @@ -779,7 +779,7 @@ var Max = &Builtin{ types.Named("collection", types.NewAny( types.NewSet(types.A), types.NewArray(nil, types.A), - )), + )).Description("the set or array to be searched"), ), types.Named("n", types.A).Description("the maximum of all elements"), ), @@ -794,7 +794,7 @@ var Min = &Builtin{ types.Named("collection", types.NewAny( types.NewSet(types.A), types.NewArray(nil, types.A), - )), + )).Description("the set or array to be searched"), ), types.Named("n", types.A).Description("the minimum of all elements"), ), @@ -829,8 +829,8 @@ var ArrayConcat = &Builtin{ Description: "Concatenates two arrays.", Decl: types.NewFunction( types.Args( - types.Named("x", types.NewArray(nil, types.A)), - types.Named("y", types.NewArray(nil, types.A)), + types.Named("x", types.NewArray(nil, types.A)).Description("the first array"), + types.Named("y", types.NewArray(nil, types.A)).Description("the second array"), ), types.Named("z", types.NewArray(nil, types.A)).Description("the concatenation of `x` and `y`"), ), @@ -875,9 +875,9 @@ var ToNumber = &Builtin{ types.S, types.B, types.NewNull(), - )), + )).Description("value to convert"), ), - types.Named("num", types.N), + types.Named("num", types.N).Description("the numeric representation of `x`"), ), Categories: conversions, } @@ -894,7 +894,7 @@ var RegexMatch = &Builtin{ types.Named("pattern", types.S).Description("regular expression"), types.Named("value", types.S).Description("value to match against `pattern`"), ), - types.Named("result", types.B), + types.Named("result", types.B).Description("true if `value` matches `pattern`"), ), } @@ -905,7 +905,7 @@ var RegexIsValid = &Builtin{ types.Args( types.Named("pattern", types.S).Description("regular expression"), ), - types.Named("result", types.B), + types.Named("result", types.B).Description("true if `pattern` is a valid regular expression"), ), } @@ -918,7 +918,7 @@ var RegexFindAllStringSubmatch = &Builtin{ types.Named("value", types.S).Description("string to match"), types.Named("number", types.N).Description("number of matches to return; `-1` means all matches"), ), - types.Named("output", types.NewArray(nil, types.NewArray(nil, types.S))), + types.Named("output", types.NewArray(nil, types.NewArray(nil, types.S))).Description("array of all matches"), ), } @@ -932,7 +932,7 @@ var RegexTemplateMatch = &Builtin{ types.Named("delimiter_start", types.S).Description("start delimiter of the regular expression in `template`"), types.Named("delimiter_end", types.S).Description("end delimiter of the regular expression in `template`"), ), - types.Named("result", types.B), + types.Named("result", types.B).Description("true if `value` matches the `template`"), ), } // TODO(sr): example:`regex.template_match("urn:foo:{.*}", "urn:foo:bar:baz", "{", "}")`` returns ``true``. @@ -974,10 +974,10 @@ var GlobsMatch = &Builtin{ The set of regex symbols is limited for this builtin: only ` + "`.`, `*`, `+`, `[`, `-`, `]` and `\\` are treated as special symbols.", Decl: types.NewFunction( types.Args( - types.Named("glob1", types.S), - types.Named("glob2", types.S), + types.Named("glob1", types.S).Description("first glob-style regular expression"), + types.Named("glob2", types.S).Description("second glob-style regular expression"), ), - types.Named("result", types.B), + types.Named("result", types.B).Description("true if the intersection of `glob1` and `glob2` matches a non-empty set of non-empty strings"), ), } @@ -1033,13 +1033,13 @@ var Concat = &Builtin{ Description: "Joins a set or array of strings with a delimiter.", Decl: types.NewFunction( types.Args( - types.Named("delimiter", types.S), + types.Named("delimiter", types.S).Description("string to use as a delimiter"), types.Named("collection", types.NewAny( types.NewSet(types.S), types.NewArray(nil, types.S), )).Description("strings to join"), ), - types.Named("output", types.S), + types.Named("output", types.S).Description("the joined string"), ), Categories: stringsCat, } @@ -1088,7 +1088,7 @@ var Substring = &Builtin{ Description: "Returns the portion of a string for a given `offset` and a `length`. If `length < 0`, `output` is the remainder of the string.", Decl: types.NewFunction( types.Args( - types.Named("value", types.S), + types.Named("value", types.S).Description("string to extract substring from"), types.Named("offset", types.N).Description("offset, must be positive"), types.Named("length", types.N).Description("length of the substring starting from `offset`"), ), @@ -1215,7 +1215,7 @@ The old string comparisons are done in argument order.`, ).Description("replacement pairs"), types.Named("value", types.S).Description("string to replace substring matches in"), ), - types.Named("output", types.S), + types.Named("output", types.S).Description("string with replaced substrings"), ), } @@ -1228,7 +1228,7 @@ var RegexReplace = &Builtin{ types.Named("pattern", types.S).Description("regex pattern to be applied"), types.Named("value", types.S).Description("regex value"), ), - types.Named("output", types.S), + types.Named("output", types.S).Description("string with replaced substrings"), ), } @@ -1327,9 +1327,9 @@ var StringReverse = &Builtin{ Description: "Reverses a given string.", Decl: types.NewFunction( types.Args( - types.Named("x", types.S), + types.Named("x", types.S).Description("string to reverse"), ), - types.Named("y", types.S), + types.Named("y", types.S).Description("reversed string"), ), Categories: stringsCat, } @@ -1359,8 +1359,8 @@ var RandIntn = &Builtin{ Description: "Returns a random integer between `0` and `n` (`n` exclusive). If `n` is `0`, then `y` is always `0`. For any given argument pair (`str`, `n`), the output will be consistent throughout a query evaluation.", Decl: types.NewFunction( types.Args( - types.Named("str", types.S), - types.Named("n", types.N), + types.Named("str", types.S).Description("seed string for the random number"), + types.Named("n", types.N).Description("upper bound of the random number (exclusive)"), ), types.Named("y", types.N).Description("random integer in the range `[0, abs(n))`"), ), @@ -1373,8 +1373,8 @@ var NumbersRange = &Builtin{ Description: "Returns an array of numbers in the given (inclusive) range. If `a==b`, then `range == [a]`; if `a > b`, then `range` is in descending order.", Decl: types.NewFunction( types.Args( - types.Named("a", types.N), - types.Named("b", types.N), + types.Named("a", types.N).Description("the start of the range"), + types.Named("b", types.N).Description("the end of the range (inclusive)"), ), types.Named("range", types.NewArray(nil, types.N)).Description("the range between `a` and `b`"), ), @@ -1389,9 +1389,9 @@ var NumbersRangeStep = &Builtin{ `, Decl: types.NewFunction( types.Args( - types.Named("a", types.N), - types.Named("b", types.N), - types.Named("step", types.N), + types.Named("a", types.N).Description("the start of the range"), + types.Named("b", types.N).Description("the end of the range (inclusive)"), + types.Named("step", types.N).Description("the step between numbers in the range"), ), types.Named("range", types.NewArray(nil, types.N)).Description("the range between `a` and `b` in `step` increments"), ), @@ -1403,12 +1403,16 @@ var NumbersRangeStep = &Builtin{ var UnitsParse = &Builtin{ Name: "units.parse", - Description: `Converts strings like "10G", "5K", "4M", "1500m" and the like into a number. -This number can be a non-integer, such as 1.5, 0.22, etc. Supports standard metric decimal and -binary SI units (e.g., K, Ki, M, Mi, G, Gi etc.) m, K, M, G, T, P, and E are treated as decimal -units and Ki, Mi, Gi, Ti, Pi, and Ei are treated as binary units. + Description: `Converts strings like "10G", "5K", "4M", "1500m", and the like into a number. +This number can be a non-integer, such as 1.5, 0.22, etc. Scientific notation is supported, +allowing values such as "1e-3K" (1) or "2.5e6M" (2.5 million M). + +Supports standard metric decimal and binary SI units (e.g., K, Ki, M, Mi, G, Gi, etc.) where +m, K, M, G, T, P, and E are treated as decimal units and Ki, Mi, Gi, Ti, Pi, and Ei are treated as +binary units. -Note that 'm' and 'M' are case-sensitive, to allow distinguishing between "milli" and "mega" units respectively. Other units are case-insensitive.`, +Note that 'm' and 'M' are case-sensitive to allow distinguishing between "milli" and "mega" units +respectively. Other units are case-insensitive.`, Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("the unit to parse"), @@ -1419,10 +1423,14 @@ Note that 'm' and 'M' are case-sensitive, to allow distinguishing between "milli var UnitsParseBytes = &Builtin{ Name: "units.parse_bytes", - Description: `Converts strings like "10GB", "5K", "4mb" into an integer number of bytes. -Supports standard byte units (e.g., KB, KiB, etc.) KB, MB, GB, and TB are treated as decimal -units and KiB, MiB, GiB, and TiB are treated as binary units. The bytes symbol (b/B) in the -unit is optional and omitting it wil give the same result (e.g. Mi and MiB).`, + Description: `Converts strings like "10GB", "5K", "4mb", or "1e6KB" into an integer number of bytes. + +Supports standard byte units (e.g., KB, KiB, etc.) where KB, MB, GB, and TB are treated as decimal +units, and KiB, MiB, GiB, and TiB are treated as binary units. Scientific notation is supported, +enabling values like "1.5e3MB" (1500MB) or "2e6GiB" (2 million GiB). + +The bytes symbol (b/B) in the unit is optional; omitting it will yield the same result (e.g., "Mi" +and "MiB" are equivalent).`, Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("the byte unit to parse"), @@ -1443,7 +1451,7 @@ var UUIDRFC4122 = &Builtin{ Description: "Returns a new UUIDv4.", Decl: types.NewFunction( types.Args( - types.Named("k", types.S), + types.Named("k", types.S).Description("seed string"), ), types.Named("output", types.S).Description("a version 4 UUID; for any given `k`, the output will be consistent throughout a query evaluation"), ), @@ -1456,7 +1464,7 @@ var UUIDParse = &Builtin{ Categories: nil, Decl: types.NewFunction( types.Args( - types.Named("uuid", types.S), + types.Named("uuid", types.S).Description("UUID string to parse"), ), types.Named("result", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))).Description("Properties of UUID if valid (version, variant, etc). Undefined otherwise."), ), @@ -1479,7 +1487,7 @@ var JSONFilter = &Builtin{ types.Named("object", types.NewObject( nil, types.NewDynamicProperty(types.A, types.A), - )), + )).Description("object to filter"), types.Named("paths", types.NewAny( types.NewArray( nil, @@ -1517,7 +1525,7 @@ var JSONRemove = &Builtin{ types.Named("object", types.NewObject( nil, types.NewDynamicProperty(types.A, types.A), - )), + )).Description("object to remove paths from"), types.Named("paths", types.NewAny( types.NewArray( nil, @@ -1553,7 +1561,7 @@ var JSONPatch = &Builtin{ "Additionally works on sets, where a value contained in the set is considered to be its path.", Decl: types.NewFunction( types.Args( - types.Named("object", types.A), // TODO(sr): types.A? + types.Named("object", types.A).Description("the object to patch"), // TODO(sr): types.A? types.Named("patches", types.NewArray( nil, types.NewObject( @@ -1563,7 +1571,7 @@ var JSONPatch = &Builtin{ }, types.NewDynamicProperty(types.A, types.A), ), - )), + )).Description("the JSON patches to apply"), ), types.Named("output", types.A).Description("result obtained after consecutively applying all patch operations in `patches`"), ), @@ -1589,15 +1597,13 @@ var ObjectSubset = &Builtin{ types.Named("super", types.NewAny(types.NewObject( nil, types.NewDynamicProperty(types.A, types.A), - ), - types.NewSet(types.A), + ), types.NewSet(types.A), types.NewArray(nil, types.A), )).Description("object to test if sub is a subset of"), types.Named("sub", types.NewAny(types.NewObject( nil, types.NewDynamicProperty(types.A, types.A), - ), - types.NewSet(types.A), + ), types.NewSet(types.A), types.NewArray(nil, types.A), )).Description("object to test if super is a superset of"), ), @@ -1614,11 +1620,11 @@ var ObjectUnion = &Builtin{ types.Named("a", types.NewObject( nil, types.NewDynamicProperty(types.A, types.A), - )), + )).Description("left-hand object"), types.Named("b", types.NewObject( nil, types.NewDynamicProperty(types.A, types.A), - )), + )).Description("right-hand object"), ), types.Named("output", types.A).Description("a new object which is the result of an asymmetric recursive union of two objects where conflicts are resolved by choosing the key from the right-hand object `b`"), ), // TODO(sr): types.A? ^^^^^^^ (also below) @@ -1633,7 +1639,7 @@ var ObjectUnionN = &Builtin{ types.Named("objects", types.NewArray( nil, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)), - )), + )).Description("list of objects to merge"), ), types.Named("output", types.A).Description("asymmetric recursive union of all objects in `objects`, merged from left to right, where conflicts are resolved by choosing the key from the right-hand object"), ), @@ -1672,7 +1678,7 @@ var ObjectFilter = &Builtin{ types.NewArray(nil, types.A), types.NewSet(types.A), types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)), - )), + )).Description("keys to keep in `object`"), ), types.Named("filtered", types.A).Description("remaining data from `object` with only keys specified in `keys`"), ), @@ -1772,7 +1778,7 @@ var Base64Encode = &Builtin{ Description: "Serializes the input string into base64 encoding.", Decl: types.NewFunction( types.Args( - types.Named("x", types.S), + types.Named("x", types.S).Description("string to encode"), ), types.Named("y", types.S).Description("base64 serialization of `x`"), ), @@ -1784,7 +1790,7 @@ var Base64Decode = &Builtin{ Description: "Deserializes the base64 encoded input string.", Decl: types.NewFunction( types.Args( - types.Named("x", types.S), + types.Named("x", types.S).Description("string to decode"), ), types.Named("y", types.S).Description("base64 deserialization of `x`"), ), @@ -1796,7 +1802,7 @@ var Base64IsValid = &Builtin{ Description: "Verifies the input string is base64 encoded.", Decl: types.NewFunction( types.Args( - types.Named("x", types.S), + types.Named("x", types.S).Description("string to check"), ), types.Named("result", types.B).Description("`true` if `x` is valid base64 encoded value, `false` otherwise"), ), @@ -1808,7 +1814,7 @@ var Base64UrlEncode = &Builtin{ Description: "Serializes the input string into base64url encoding.", Decl: types.NewFunction( types.Args( - types.Named("x", types.S), + types.Named("x", types.S).Description("string to encode"), ), types.Named("y", types.S).Description("base64url serialization of `x`"), ), @@ -1820,7 +1826,7 @@ var Base64UrlEncodeNoPad = &Builtin{ Description: "Serializes the input string into base64url encoding without padding.", Decl: types.NewFunction( types.Args( - types.Named("x", types.S), + types.Named("x", types.S).Description("string to encode"), ), types.Named("y", types.S).Description("base64url serialization of `x`"), ), @@ -1832,7 +1838,7 @@ var Base64UrlDecode = &Builtin{ Description: "Deserializes the base64url encoded input string.", Decl: types.NewFunction( types.Args( - types.Named("x", types.S), + types.Named("x", types.S).Description("string to decode"), ), types.Named("y", types.S).Description("base64url deserialization of `x`"), ), @@ -1844,7 +1850,7 @@ var URLQueryDecode = &Builtin{ Description: "Decodes a URL-encoded input string.", Decl: types.NewFunction( types.Args( - types.Named("x", types.S), + types.Named("x", types.S).Description("the URL-encoded string"), ), types.Named("y", types.S).Description("URL-encoding deserialization of `x`"), ), @@ -1856,7 +1862,7 @@ var URLQueryEncode = &Builtin{ Description: "Encodes the input string into a URL-encoded string.", Decl: types.NewFunction( types.Args( - types.Named("x", types.S), + types.Named("x", types.S).Description("the string to encode"), ), types.Named("y", types.S).Description("URL-encoding serialization of `x`"), ), @@ -1875,7 +1881,11 @@ var URLQueryEncodeObject = &Builtin{ types.NewAny( types.S, types.NewArray(nil, types.S), - types.NewSet(types.S)))))), + types.NewSet(types.S)), + ), + ), + ).Description("the object to encode"), + ), types.Named("y", types.S).Description("the URL-encoded serialization of `object`"), ), Categories: encoding, @@ -1937,7 +1947,7 @@ var HexEncode = &Builtin{ Description: "Serializes the input string using hex-encoding.", Decl: types.NewFunction( types.Args( - types.Named("x", types.S), + types.Named("x", types.S).Description("string to encode"), ), types.Named("y", types.S).Description("serialization of `x` using hex-encoding"), ), @@ -2219,7 +2229,7 @@ var ParseRFC3339Nanos = &Builtin{ Description: "Returns the time in nanoseconds parsed from the string in RFC3339 format. `undefined` if the result would be outside the valid time range that can fit within an `int64`.", Decl: types.NewFunction( types.Args( - types.Named("value", types.S), + types.Named("value", types.S).Description("input string to parse in RFC3339 format"), ), types.Named("ns", types.N).Description("`value` in nanoseconds since epoch"), ), @@ -2300,9 +2310,9 @@ var AddDate = &Builtin{ Decl: types.NewFunction( types.Args( types.Named("ns", types.N).Description("nanoseconds since the epoch"), - types.Named("years", types.N), - types.Named("months", types.N), - types.Named("days", types.N), + types.Named("years", types.N).Description("number of years to add"), + types.Named("months", types.N).Description("number of months to add"), + types.Named("days", types.N).Description("number of days to add"), ), types.Named("output", types.N).Description("nanoseconds since the epoch representing the input time, with years, months and days added"), ), @@ -2316,11 +2326,11 @@ var Diff = &Builtin{ types.Named("ns1", types.NewAny( types.N, types.NewArray([]types.Type{types.N, types.S}, nil), - )), + )).Description("nanoseconds since the epoch; or a two-element array of the nanoseconds, and a timezone string"), types.Named("ns2", types.NewAny( types.N, types.NewArray([]types.Type{types.N, types.S}, nil), - )), + )).Description("nanoseconds since the epoch; or a two-element array of the nanoseconds, and a timezone string"), ), types.Named("output", types.NewArray([]types.Type{types.N, types.N, types.N, types.N, types.N, types.N}, nil)).Description("difference between `ns1` and `ns2` (in their supplied timezones, if supplied, or UTC) as array of numbers: `[years, months, days, hours, minutes, seconds]`"), ), @@ -2440,7 +2450,7 @@ var CryptoMd5 = &Builtin{ Description: "Returns a string representing the input string hashed with the MD5 function", Decl: types.NewFunction( types.Args( - types.Named("x", types.S), + types.Named("x", types.S).Description("input string"), ), types.Named("y", types.S).Description("MD5-hash of `x`"), ), @@ -2451,7 +2461,7 @@ var CryptoSha1 = &Builtin{ Description: "Returns a string representing the input string hashed with the SHA1 function", Decl: types.NewFunction( types.Args( - types.Named("x", types.S), + types.Named("x", types.S).Description("input string"), ), types.Named("y", types.S).Description("SHA1-hash of `x`"), ), @@ -2462,7 +2472,7 @@ var CryptoSha256 = &Builtin{ Description: "Returns a string representing the input string hashed with the SHA256 function", Decl: types.NewFunction( types.Args( - types.Named("x", types.S), + types.Named("x", types.S).Description("input string"), ), types.Named("y", types.S).Description("SHA256-hash of `x`"), ), @@ -2539,7 +2549,7 @@ var WalkBuiltin = &Builtin{ Description: "Generates `[path, value]` tuples for all nested documents of `x` (recursively). Queries can use `walk` to traverse documents nested under `x`.", Decl: types.NewFunction( types.Args( - types.Named("x", types.A), + types.Named("x", types.A).Description("value to walk"), ), types.Named("output", types.NewArray( []types.Type{ @@ -2602,7 +2612,7 @@ var IsNumber = &Builtin{ Description: "Returns `true` if the input value is a number.", Decl: types.NewFunction( types.Args( - types.Named("x", types.A), + types.Named("x", types.A).Description("input value"), ), types.Named("result", types.B).Description("`true` if `x` is a number, `false` otherwise."), ), @@ -2614,7 +2624,7 @@ var IsString = &Builtin{ Description: "Returns `true` if the input value is a string.", Decl: types.NewFunction( types.Args( - types.Named("x", types.A), + types.Named("x", types.A).Description("input value"), ), types.Named("result", types.B).Description("`true` if `x` is a string, `false` otherwise."), ), @@ -2626,7 +2636,7 @@ var IsBoolean = &Builtin{ Description: "Returns `true` if the input value is a boolean.", Decl: types.NewFunction( types.Args( - types.Named("x", types.A), + types.Named("x", types.A).Description("input value"), ), types.Named("result", types.B).Description("`true` if `x` is an boolean, `false` otherwise."), ), @@ -2638,7 +2648,7 @@ var IsArray = &Builtin{ Description: "Returns `true` if the input value is an array.", Decl: types.NewFunction( types.Args( - types.Named("x", types.A), + types.Named("x", types.A).Description("input value"), ), types.Named("result", types.B).Description("`true` if `x` is an array, `false` otherwise."), ), @@ -2650,7 +2660,7 @@ var IsSet = &Builtin{ Description: "Returns `true` if the input value is a set.", Decl: types.NewFunction( types.Args( - types.Named("x", types.A), + types.Named("x", types.A).Description("input value"), ), types.Named("result", types.B).Description("`true` if `x` is a set, `false` otherwise."), ), @@ -2662,7 +2672,7 @@ var IsObject = &Builtin{ Description: "Returns true if the input value is an object", Decl: types.NewFunction( types.Args( - types.Named("x", types.A), + types.Named("x", types.A).Description("input value"), ), types.Named("result", types.B).Description("`true` if `x` is an object, `false` otherwise."), ), @@ -2674,7 +2684,7 @@ var IsNull = &Builtin{ Description: "Returns `true` if the input value is null.", Decl: types.NewFunction( types.Args( - types.Named("x", types.A), + types.Named("x", types.A).Description("input value"), ), types.Named("result", types.B).Description("`true` if `x` is null, `false` otherwise."), ), @@ -2691,7 +2701,7 @@ var TypeNameBuiltin = &Builtin{ Description: "Returns the type of its input value.", Decl: types.NewFunction( types.Args( - types.Named("x", types.A), + types.Named("x", types.A).Description("input value"), ), types.Named("type", types.S).Description(`one of "null", "boolean", "number", "string", "array", "object", "set"`), ), @@ -2708,9 +2718,11 @@ var HTTPSend = &Builtin{ Description: "Returns a HTTP response to the given HTTP request.", Decl: types.NewFunction( types.Args( - types.Named("request", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))), + types.Named("request", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))). + Description("the HTTP request object"), ), - types.Named("response", types.NewObject(nil, types.NewDynamicProperty(types.A, types.A))), + types.Named("response", types.NewObject(nil, types.NewDynamicProperty(types.A, types.A))). + Description("the HTTP response object"), ), Nondeterministic: true, } @@ -2725,8 +2737,10 @@ var GraphQLParse = &Builtin{ Description: "Returns AST objects for a given GraphQL query and schema after validating the query against the schema. Returns undefined if errors were encountered during parsing or validation. The query and/or schema can be either GraphQL strings or AST objects from the other GraphQL builtin functions.", Decl: types.NewFunction( types.Args( - types.Named("query", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))), - types.Named("schema", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))), + types.Named("query", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))). + Description("the GraphQL query"), + types.Named("schema", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))). + Description("the GraphQL schema"), ), types.Named("output", types.NewArray([]types.Type{ types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)), @@ -2741,8 +2755,10 @@ var GraphQLParseAndVerify = &Builtin{ Description: "Returns a boolean indicating success or failure alongside the parsed ASTs for a given GraphQL query and schema after validating the query against the schema. The query and/or schema can be either GraphQL strings or AST objects from the other GraphQL builtin functions.", Decl: types.NewFunction( types.Args( - types.Named("query", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))), - types.Named("schema", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))), + types.Named("query", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))). + Description("the GraphQL query"), + types.Named("schema", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))). + Description("the GraphQL schema"), ), types.Named("output", types.NewArray([]types.Type{ types.B, @@ -2759,7 +2775,7 @@ var GraphQLParseQuery = &Builtin{ Description: "Returns an AST object for a GraphQL query.", Decl: types.NewFunction( types.Args( - types.Named("query", types.S), + types.Named("query", types.S).Description("GraphQL query string"), ), types.Named("output", types.NewObject(nil, types.NewDynamicProperty(types.A, types.A))).Description("AST object for the GraphQL query."), ), @@ -2772,7 +2788,7 @@ var GraphQLParseSchema = &Builtin{ Description: "Returns an AST object for a GraphQL schema.", Decl: types.NewFunction( types.Args( - types.Named("schema", types.S), + types.Named("schema", types.S).Description("GraphQL schema string"), ), types.Named("output", types.NewObject(nil, types.NewDynamicProperty(types.A, types.A))).Description("AST object for the GraphQL schema."), ), @@ -2785,8 +2801,10 @@ var GraphQLIsValid = &Builtin{ Description: "Checks that a GraphQL query is valid against a given schema. The query and/or schema can be either GraphQL strings or AST objects from the other GraphQL builtin functions.", Decl: types.NewFunction( types.Args( - types.Named("query", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))), - types.Named("schema", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))), + types.Named("query", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))). + Description("the GraphQL query"), + types.Named("schema", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))). + Description("the GraphQL schema"), ), types.Named("output", types.B).Description("`true` if the query is valid under the given schema. `false` otherwise."), ), @@ -2799,7 +2817,8 @@ var GraphQLSchemaIsValid = &Builtin{ Description: "Checks that the input is a valid GraphQL schema. The schema can be either a GraphQL string or an AST object from the other GraphQL builtin functions.", Decl: types.NewFunction( types.Args( - types.Named("schema", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))), + types.Named("schema", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))). + Description("the schema to verify"), ), types.Named("output", types.B).Description("`true` if the schema is a valid GraphQL schema. `false` otherwise."), ), @@ -2869,11 +2888,14 @@ var ProvidersAWSSignReqObj = &Builtin{ Description: "Signs an HTTP request object for Amazon Web Services. Currently implements [AWS Signature Version 4 request signing](https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html) by the `Authorization` header method.", Decl: types.NewFunction( types.Args( - types.Named("request", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))), - types.Named("aws_config", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))), - types.Named("time_ns", types.N), + types.Named("request", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))). + Description("HTTP request object"), + types.Named("aws_config", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))). + Description("AWS configuration object"), + types.Named("time_ns", types.N).Description("nanoseconds since the epoch"), ), - types.Named("signed_request", types.NewObject(nil, types.NewDynamicProperty(types.A, types.A))), + types.Named("signed_request", types.NewObject(nil, types.NewDynamicProperty(types.A, types.A))). + Description("HTTP request object with `Authorization` header"), ), Categories: providersAWSCat, } @@ -2890,7 +2912,8 @@ var RegoParseModule = &Builtin{ types.Named("filename", types.S).Description("file name to attach to AST nodes' locations"), types.Named("rego", types.S).Description("Rego module"), ), - types.Named("output", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))), // TODO(tsandall): import AST schema + types.Named("output", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))). + Description("AST object for the Rego module"), ), } @@ -2958,12 +2981,12 @@ var GlobMatch = &Builtin{ Description: "Parses and matches strings against the glob notation. Not to be confused with `regex.globs_match`.", Decl: types.NewFunction( types.Args( - types.Named("pattern", types.S), + types.Named("pattern", types.S).Description("glob pattern"), types.Named("delimiters", types.NewAny( types.NewArray(nil, types.S), types.NewNull(), )).Description("glob pattern delimiters, e.g. `[\".\", \":\"]`, defaults to `[\".\"]` if unset. If `delimiters` is `null`, glob match without delimiter."), - types.Named("match", types.S), + types.Named("match", types.S).Description("string to match against `pattern`"), ), types.Named("result", types.B).Description("true if `match` can be found in `pattern` which is separated by `delimiters`"), ), @@ -2974,7 +2997,7 @@ var GlobQuoteMeta = &Builtin{ Description: "Returns a string which represents a version of the pattern where all asterisks have been escaped.", Decl: types.NewFunction( types.Args( - types.Named("pattern", types.S), + types.Named("pattern", types.S).Description("glob pattern"), ), types.Named("output", types.S).Description("the escaped string of `pattern`"), ), @@ -2990,10 +3013,10 @@ var NetCIDRIntersects = &Builtin{ Description: "Checks if a CIDR intersects with another CIDR (e.g. `192.168.0.0/16` overlaps with `192.168.1.0/24`). Supports both IPv4 and IPv6 notations.", Decl: types.NewFunction( types.Args( - types.Named("cidr1", types.S), - types.Named("cidr2", types.S), + types.Named("cidr1", types.S).Description("first CIDR"), + types.Named("cidr2", types.S).Description("second CIDR"), ), - types.Named("result", types.B), + types.Named("result", types.B).Description("`true` if `cidr1` intersects with `cidr2`"), ), } @@ -3002,7 +3025,7 @@ var NetCIDRExpand = &Builtin{ Description: "Expands CIDR to set of hosts (e.g., `net.cidr_expand(\"192.168.0.0/30\")` generates 4 hosts: `{\"192.168.0.0\", \"192.168.0.1\", \"192.168.0.2\", \"192.168.0.3\"}`).", Decl: types.NewFunction( types.Args( - types.Named("cidr", types.S), + types.Named("cidr", types.S).Description("CIDR to expand"), ), types.Named("hosts", types.NewSet(types.S)).Description("set of IP addresses the CIDR `cidr` expands to"), ), @@ -3013,10 +3036,10 @@ var NetCIDRContains = &Builtin{ Description: "Checks if a CIDR or IP is contained within another CIDR. `output` is `true` if `cidr_or_ip` (e.g. `127.0.0.64/26` or `127.0.0.1`) is contained within `cidr` (e.g. `127.0.0.1/24`) and `false` otherwise. Supports both IPv4 and IPv6 notations.", Decl: types.NewFunction( types.Args( - types.Named("cidr", types.S), - types.Named("cidr_or_ip", types.S), + types.Named("cidr", types.S).Description("CIDR to check against"), + types.Named("cidr_or_ip", types.S).Description("CIDR or IP to check"), ), - types.Named("result", types.B), + types.Named("result", types.B).Description("`true` if `cidr_or_ip` is contained within `cidr`"), ), } @@ -3026,8 +3049,8 @@ var NetCIDRContainsMatches = &Builtin{ "This function is similar to `net.cidr_contains` except it allows callers to pass collections of CIDRs or IPs as arguments and returns the matches (as opposed to a boolean result indicating a match between two CIDRs/IPs).", Decl: types.NewFunction( types.Args( - types.Named("cidrs", netCidrContainsMatchesOperandType), - types.Named("cidrs_or_ips", netCidrContainsMatchesOperandType), + types.Named("cidrs", netCidrContainsMatchesOperandType).Description("CIDRs to check against"), + types.Named("cidrs_or_ips", netCidrContainsMatchesOperandType).Description("CIDRs or IPs to check"), ), types.Named("output", types.NewSet(types.NewArray([]types.Type{types.A, types.A}, nil))).Description("tuples identifying matches where `cidrs_or_ips` are contained within `cidrs`"), ), @@ -3054,9 +3077,9 @@ var NetCIDRIsValid = &Builtin{ Description: "Parses an IPv4/IPv6 CIDR and returns a boolean indicating if the provided CIDR is valid.", Decl: types.NewFunction( types.Args( - types.Named("cidr", types.S), + types.Named("cidr", types.S).Description("CIDR to validate"), ), - types.Named("result", types.B), + types.Named("result", types.B).Description("`true` if `cidr` is a valid CIDR"), ), } @@ -3101,7 +3124,7 @@ var SemVerIsValid = &Builtin{ Description: "Validates that the input is a valid SemVer string.", Decl: types.NewFunction( types.Args( - types.Named("vsn", types.A), + types.Named("vsn", types.A).Description("input to validate"), ), types.Named("result", types.B).Description("`true` if `vsn` is a valid SemVer; `false` otherwise"), ), @@ -3112,8 +3135,8 @@ var SemVerCompare = &Builtin{ Description: "Compares valid SemVer formatted version strings.", Decl: types.NewFunction( types.Args( - types.Named("a", types.S), - types.Named("b", types.S), + types.Named("a", types.S).Description("first version string"), + types.Named("b", types.S).Description("second version string"), ), types.Named("result", types.N).Description("`-1` if `a < b`; `1` if `a > b`; `0` if `a == b`"), ), @@ -3364,7 +3387,7 @@ func (b *Builtin) Ref() Ref { // IsTargetPos returns true if a variable in the i-th position will be bound by // evaluating the call expression. func (b *Builtin) IsTargetPos(i int) bool { - return len(b.Decl.FuncArgs().Args) == i + return b.Decl.Arity() == i } func init() { diff --git a/vendor/github.com/open-policy-agent/opa/ast/capabilities.go b/vendor/github.com/open-policy-agent/opa/v1/ast/capabilities.go similarity index 85% rename from vendor/github.com/open-policy-agent/opa/ast/capabilities.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/capabilities.go index 3b95d79e57..e7d561d9e8 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/capabilities.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/capabilities.go @@ -14,10 +14,10 @@ import ( "sort" "strings" - caps "github.com/open-policy-agent/opa/capabilities" "github.com/open-policy-agent/opa/internal/semver" "github.com/open-policy-agent/opa/internal/wasm/sdk/opa/capabilities" - "github.com/open-policy-agent/opa/util" + caps "github.com/open-policy-agent/opa/v1/capabilities" + "github.com/open-policy-agent/opa/v1/util" ) // VersonIndex contains an index from built-in function name, language feature, @@ -52,6 +52,7 @@ var minVersionIndex = func() VersionIndex { // heads, they wouldn't be able to parse them. const FeatureRefHeadStringPrefixes = "rule_head_ref_string_prefixes" const FeatureRefHeads = "rule_head_refs" +const FeatureRegoV1 = "rego_v1" const FeatureRegoV1Import = "rego_v1_import" // Capabilities defines a structure containing data that describes the capabilities @@ -83,8 +84,30 @@ type WasmABIVersion struct { Minor int `json:"minor_version"` } +type CapabilitiesOptions struct { + regoVersion RegoVersion +} + +func newCapabilitiesOptions(opts []CapabilitiesOption) CapabilitiesOptions { + co := CapabilitiesOptions{} + for _, opt := range opts { + opt(&co) + } + return co +} + +type CapabilitiesOption func(*CapabilitiesOptions) + +func CapabilitiesRegoVersion(regoVersion RegoVersion) CapabilitiesOption { + return func(o *CapabilitiesOptions) { + o.regoVersion = regoVersion + } +} + // CapabilitiesForThisVersion returns the capabilities of this version of OPA. -func CapabilitiesForThisVersion() *Capabilities { +func CapabilitiesForThisVersion(opts ...CapabilitiesOption) *Capabilities { + co := newCapabilitiesOptions(opts) + f := &Capabilities{} for _, vers := range capabilities.ABIVersions() { @@ -97,17 +120,29 @@ func CapabilitiesForThisVersion() *Capabilities { return f.Builtins[i].Name < f.Builtins[j].Name }) - for kw := range futureKeywords { - f.FutureKeywords = append(f.FutureKeywords, kw) - } - sort.Strings(f.FutureKeywords) + if co.regoVersion == RegoV0 || co.regoVersion == RegoV0CompatV1 { + for kw := range allFutureKeywords { + f.FutureKeywords = append(f.FutureKeywords, kw) + } - f.Features = []string{ - FeatureRefHeadStringPrefixes, - FeatureRefHeads, - FeatureRegoV1Import, + f.Features = []string{ + FeatureRefHeadStringPrefixes, + FeatureRefHeads, + FeatureRegoV1Import, + } + } else { + for kw := range futureKeywords { + f.FutureKeywords = append(f.FutureKeywords, kw) + } + + f.Features = []string{ + FeatureRegoV1, + } } + sort.Strings(f.FutureKeywords) + sort.Strings(f.Features) + return f } diff --git a/vendor/github.com/open-policy-agent/opa/ast/check.go b/vendor/github.com/open-policy-agent/opa/v1/ast/check.go similarity index 94% rename from vendor/github.com/open-policy-agent/opa/ast/check.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/check.go index 23d1ed8fa1..57c2fa5d75 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/check.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/check.go @@ -9,8 +9,8 @@ import ( "sort" "strings" - "github.com/open-policy-agent/opa/types" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/types" + "github.com/open-policy-agent/opa/v1/util" ) type varRewriter func(Ref) Ref @@ -33,15 +33,16 @@ type typeChecker struct { allowNet []string input types.Type allowUndefinedFuncs bool + schemaTypes map[string]types.Type } // newTypeChecker returns a new typeChecker object that has no errors. func newTypeChecker() *typeChecker { - tc := &typeChecker{} - tc.exprCheckers = map[string]exprChecker{ - "eq": tc.checkExprEq, + return &typeChecker{ + exprCheckers: map[string]exprChecker{ + "eq": checkExprEq, + }, } - return tc } func (tc *typeChecker) newEnv(exist *TypeEnv) *TypeEnv { @@ -59,6 +60,7 @@ func (tc *typeChecker) copy() *typeChecker { return newTypeChecker(). WithVarRewriter(tc.varRewriter). WithSchemaSet(tc.ss). + WithSchemaTypes(tc.schemaTypes). WithAllowNet(tc.allowNet). WithInputType(tc.input). WithAllowUndefinedFunctionCalls(tc.allowUndefinedFuncs). @@ -81,6 +83,11 @@ func (tc *typeChecker) WithSchemaSet(ss *SchemaSet) *typeChecker { return tc } +func (tc *typeChecker) WithSchemaTypes(schemaTypes map[string]types.Type) *typeChecker { + tc.schemaTypes = schemaTypes + return tc +} + func (tc *typeChecker) WithAllowNet(hosts []string) *typeChecker { tc.allowNet = hosts return tc @@ -121,6 +128,7 @@ func (tc *typeChecker) CheckBody(env *TypeEnv, body Body) (*TypeEnv, Errors) { errors := []*Error{} env = tc.newEnv(env) + vis := newRefChecker(env, tc.varRewriter) WalkExprs(body, func(expr *Expr) bool { @@ -131,7 +139,8 @@ func (tc *typeChecker) CheckBody(env *TypeEnv, body Body) (*TypeEnv, Errors) { hasClosureErrors := len(closureErrs) > 0 - vis := newRefChecker(env, tc.varRewriter) + // reset errors from previous iteration + vis.errs = nil NewGenericVisitor(vis.Visit).Walk(expr) for _, err := range vis.errs { errors = append(errors, err) @@ -196,20 +205,47 @@ func (tc *typeChecker) checkClosures(env *TypeEnv, expr *Expr) Errors { return result } +func (tc *typeChecker) getSchemaType(schemaAnnot *SchemaAnnotation, rule *Rule) (types.Type, *Error) { + if tc.schemaTypes == nil { + tc.schemaTypes = make(map[string]types.Type) + } + + if refType, exists := tc.schemaTypes[schemaAnnot.Schema.String()]; exists { + return refType, nil + } + + refType, err := processAnnotation(tc.ss, schemaAnnot, rule, tc.allowNet) + if err != nil { + return nil, err + } + + if refType == nil { + return nil, nil + } + + tc.schemaTypes[schemaAnnot.Schema.String()] = refType + return refType, nil + +} + func (tc *typeChecker) checkRule(env *TypeEnv, as *AnnotationSet, rule *Rule) { env = env.wrap() schemaAnnots := getRuleAnnotation(as, rule) for _, schemaAnnot := range schemaAnnots { - ref, refType, err := processAnnotation(tc.ss, schemaAnnot, rule, tc.allowNet) + refType, err := tc.getSchemaType(schemaAnnot, rule) if err != nil { tc.err([]*Error{err}) continue } - if ref == nil && refType == nil { + + ref := schemaAnnot.Path + // if we do not have a ref or a reftype, we should not evaluate this rule. + if ref == nil || refType == nil { continue } + prefixRef, t := getPrefix(env, ref) if t == nil || len(prefixRef) == len(ref) { env.tree.Put(ref, refType) @@ -267,7 +303,7 @@ func (tc *typeChecker) checkRule(env *TypeEnv, as *AnnotationSet, rule *Rule) { var err error tpe, err = nestedObject(cpy, objPath, typeV) if err != nil { - tc.err([]*Error{NewError(TypeErr, rule.Head.Location, err.Error())}) + tc.err([]*Error{NewError(TypeErr, rule.Head.Location, err.Error())}) //nolint:govet tpe = nil } } else { @@ -327,7 +363,7 @@ func (tc *typeChecker) checkExpr(env *TypeEnv, expr *Expr) *Error { // If the type checker wasn't provided with a required capabilities // structure then just skip. In some cases, type checking might be run // without the need to record what builtins are required. - if tc.required != nil { + if tc.required != nil && tc.builtins != nil { if bi, ok := tc.builtins[operator]; ok { tc.required.addBuiltinSorted(bi) } @@ -404,17 +440,16 @@ func (tc *typeChecker) checkExprBuiltin(env *TypeEnv, expr *Expr) *Error { return nil } -func (tc *typeChecker) checkExprEq(env *TypeEnv, expr *Expr) *Error { +func checkExprEq(env *TypeEnv, expr *Expr) *Error { pre := getArgTypes(env, expr.Operands()) - exp := Equality.Decl.FuncArgs() - if len(pre) < len(exp.Args) { - return newArgError(expr.Location, expr.Operator(), "too few arguments", pre, exp) + if len(pre) < Equality.Decl.Arity() { + return newArgError(expr.Location, expr.Operator(), "too few arguments", pre, Equality.Decl.FuncArgs()) } - if len(exp.Args) < len(pre) { - return newArgError(expr.Location, expr.Operator(), "too many arguments", pre, exp) + if Equality.Decl.Arity() < len(pre) { + return newArgError(expr.Location, expr.Operator(), "too many arguments", pre, Equality.Decl.FuncArgs()) } a, b := expr.Operand(0), expr.Operand(1) @@ -658,7 +693,6 @@ func rewriteVarsNop(node Ref) Ref { } func newRefChecker(env *TypeEnv, f varRewriter) *refChecker { - if f == nil { f = rewriteVarsNop } @@ -1266,17 +1300,17 @@ func getRuleAnnotation(as *AnnotationSet, rule *Rule) (result []*SchemaAnnotatio return result } -func processAnnotation(ss *SchemaSet, annot *SchemaAnnotation, rule *Rule, allowNet []string) (Ref, types.Type, *Error) { +func processAnnotation(ss *SchemaSet, annot *SchemaAnnotation, rule *Rule, allowNet []string) (types.Type, *Error) { var schema interface{} if annot.Schema != nil { if ss == nil { - return nil, nil, nil + return nil, nil } schema = ss.Get(annot.Schema) if schema == nil { - return nil, nil, NewError(TypeErr, rule.Location, "undefined schema: %v", annot.Schema) + return nil, NewError(TypeErr, rule.Location, "undefined schema: %v", annot.Schema) } } else if annot.Definition != nil { schema = *annot.Definition @@ -1284,10 +1318,10 @@ func processAnnotation(ss *SchemaSet, annot *SchemaAnnotation, rule *Rule, allow tpe, err := loadSchema(schema, allowNet) if err != nil { - return nil, nil, NewError(TypeErr, rule.Location, err.Error()) + return nil, NewError(TypeErr, rule.Location, err.Error()) //nolint:govet } - return annot.Path, tpe, nil + return tpe, nil } func errAnnotationRedeclared(a *Annotations, other *Location) *Error { diff --git a/vendor/github.com/open-policy-agent/opa/ast/compare.go b/vendor/github.com/open-policy-agent/opa/v1/ast/compare.go similarity index 87% rename from vendor/github.com/open-policy-agent/opa/ast/compare.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/compare.go index 3bb6f2a75d..24e61712e7 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/compare.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/compare.go @@ -151,14 +151,7 @@ func Compare(a, b interface{}) int { } return 1 case Var: - b := b.(Var) - if a.Equal(b) { - return 0 - } - if a < b { - return -1 - } - return 1 + return VarCompare(a, b.(Var)) case Ref: b := b.(Ref) return termSliceCompare(a, b) @@ -181,7 +174,7 @@ func Compare(a, b interface{}) int { if cmp := Compare(a.Term, b.Term); cmp != 0 { return cmp } - return Compare(a.Body, b.Body) + return a.Body.Compare(b.Body) case *ObjectComprehension: b := b.(*ObjectComprehension) if cmp := Compare(a.Key, b.Key); cmp != 0 { @@ -190,13 +183,13 @@ func Compare(a, b interface{}) int { if cmp := Compare(a.Value, b.Value); cmp != 0 { return cmp } - return Compare(a.Body, b.Body) + return a.Body.Compare(b.Body) case *SetComprehension: b := b.(*SetComprehension) if cmp := Compare(a.Term, b.Term); cmp != 0 { return cmp } - return Compare(a.Body, b.Body) + return a.Body.Compare(b.Body) case Call: b := b.(Call) return termSliceCompare(a, b) @@ -394,3 +387,54 @@ func withSliceCompare(a, b []*With) int { } return 0 } + +func VarCompare(a, b Var) int { + if a == b { + return 0 + } + if a < b { + return -1 + } + return 1 +} + +func TermValueCompare(a, b *Term) int { + return a.Value.Compare(b.Value) +} + +func ValueEqual(a, b Value) bool { + // TODO(ae): why doesn't this work the same? + // + // case interface{ Equal(Value) bool }: + // return v.Equal(b) + // + // When put on top, golangci-lint even flags the other cases as unreachable.. + // but TestTopdownVirtualCache will have failing test cases when we replace + // the other cases with the above one.. 🤔 + switch v := a.(type) { + case Null: + return v.Equal(b) + case Boolean: + return v.Equal(b) + case Number: + return v.Equal(b) + case String: + return v.Equal(b) + case Var: + return v.Equal(b) + case Ref: + return v.Equal(b) + case *Array: + return v.Equal(b) + } + + return a.Compare(b) == 0 +} + +func RefCompare(a, b Ref) int { + return termSliceCompare(a, b) +} + +func RefEqual(a, b Ref) bool { + return termSliceEqual(a, b) +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/compile.go b/vendor/github.com/open-policy-agent/opa/v1/ast/compile.go similarity index 94% rename from vendor/github.com/open-policy-agent/opa/ast/compile.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/compile.go index c59cfede62..9b0302474e 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/compile.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/compile.go @@ -8,16 +8,18 @@ import ( "errors" "fmt" "io" + "maps" + "slices" "sort" "strconv" "strings" - "github.com/open-policy-agent/opa/ast/location" "github.com/open-policy-agent/opa/internal/debug" "github.com/open-policy-agent/opa/internal/gojsonschema" - "github.com/open-policy-agent/opa/metrics" - "github.com/open-policy-agent/opa/types" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/ast/location" + "github.com/open-policy-agent/opa/v1/metrics" + "github.com/open-policy-agent/opa/v1/types" + "github.com/open-policy-agent/opa/v1/util" ) // CompileErrorLimitDefault is the default number errors a compiler will allow before @@ -117,7 +119,7 @@ type Compiler struct { // with the key being the generated name and value being the original. RewrittenVars map[Var]Var - // Capabliities required by the modules that were compiled. + // Capabilities required by the modules that were compiled. Required *Capabilities localvargen *localVarGenerator @@ -127,6 +129,7 @@ type Compiler struct { maxErrs int sorted []string // list of sorted module names pathExists func([]string) (bool, error) + pathConflictCheckRoots []string after map[string][]CompilerStageDefinition metrics metrics.Metrics capabilities *Capabilities // user-supplied capabilities @@ -149,6 +152,11 @@ type Compiler struct { allowUndefinedFuncCalls bool // don't error on calls to unknown functions. evalMode CompilerEvalMode // rewriteTestRulesForTracing bool // rewrite test rules to capture dynamic values for tracing. + defaultRegoVersion RegoVersion +} + +func (c *Compiler) DefaultRegoVersion() RegoVersion { + return c.defaultRegoVersion } // CompilerStage defines the interface for stages in the compiler. @@ -310,6 +318,7 @@ func NewCompiler() *Compiler { deprecatedBuiltinsMap: map[string]struct{}{}, comprehensionIndices: map[*Term]*ComprehensionIndex{}, debug: debug.Discard(), + defaultRegoVersion: DefaultRegoVersion, } c.ModuleTree = NewModuleTree(nil) @@ -326,7 +335,7 @@ func NewCompiler() *Compiler { {"InitLocalVarGen", "compile_stage_init_local_var_gen", c.initLocalVarGen}, {"RewriteRuleHeadRefs", "compile_stage_rewrite_rule_head_refs", c.rewriteRuleHeadRefs}, {"CheckKeywordOverrides", "compile_stage_check_keyword_overrides", c.checkKeywordOverrides}, - {"CheckDuplicateImports", "compile_stage_check_duplicate_imports", c.checkDuplicateImports}, + {"CheckDuplicateImports", "compile_stage_check_imports", c.checkImports}, {"RemoveImports", "compile_stage_remove_imports", c.removeImports}, {"SetModuleTree", "compile_stage_set_module_tree", c.setModuleTree}, {"SetRuleTree", "compile_stage_set_rule_tree", c.setRuleTree}, // depends on RewriteRuleHeadRefs @@ -383,6 +392,15 @@ func (c *Compiler) WithPathConflictsCheck(fn func([]string) (bool, error)) *Comp return c } +// WithPathConflictsCheckRoots enables checking path conflicts from the specified root instead +// of the top root node. Limiting conflict checks to a known set of roots, such as bundle roots, +// improves performance. Each root has the format of a "/"-delimited string, excluding the "data" +// root document. +func (c *Compiler) WithPathConflictsCheckRoots(rootPaths []string) *Compiler { + c.pathConflictCheckRoots = rootPaths + return c +} + // WithStageAfter registers a stage to run during compilation after // the named stage. func (c *Compiler) WithStageAfter(after string, stage CompilerStageDefinition) *Compiler { @@ -422,24 +440,21 @@ func (c *Compiler) WithDebug(sink io.Writer) *Compiler { return c } -// WithBuiltins is deprecated. Use WithCapabilities instead. +// WithBuiltins is deprecated. +// Deprecated: Use WithCapabilities instead. func (c *Compiler) WithBuiltins(builtins map[string]*Builtin) *Compiler { - c.customBuiltins = make(map[string]*Builtin) - for k, v := range builtins { - c.customBuiltins[k] = v - } + c.customBuiltins = maps.Clone(builtins) return c } -// WithUnsafeBuiltins is deprecated. Use WithCapabilities instead. +// WithUnsafeBuiltins is deprecated. +// Deprecated: Use WithCapabilities instead. func (c *Compiler) WithUnsafeBuiltins(unsafeBuiltins map[string]struct{}) *Compiler { - for name := range unsafeBuiltins { - c.unsafeBuiltinsMap[name] = struct{}{} - } + maps.Copy(c.unsafeBuiltinsMap, unsafeBuiltins) return c } -// WithStrict enables strict mode in the compiler. +// WithStrict toggles strict mode in the compiler. func (c *Compiler) WithStrict(strict bool) *Compiler { c.strict = strict return c @@ -544,7 +559,7 @@ func (c *Compiler) ComprehensionIndex(term *Term) *ComprehensionIndex { // otherwise, the ref is used to perform a ruleset lookup. func (c *Compiler) GetArity(ref Ref) int { if bi := c.builtins[ref.String()]; bi != nil { - return len(bi.Decl.FuncArgs().Args) + return bi.Decl.Arity() } rules := c.GetRulesExact(ref) if len(rules) == 0 { @@ -652,7 +667,7 @@ func (c *Compiler) GetRulesWithPrefix(ref Ref) (rules []*Rule) { return rules } -func extractRules(s []util.T) []*Rule { +func extractRules(s []any) []*Rule { rules := make([]*Rule, len(s)) for i := range s { rules[i] = s[i].(*Rule) @@ -795,7 +810,7 @@ func (c *Compiler) GetRulesDynamicWithOpts(ref Ref, opts RulesOptions) []*Rule { } // Utility: add all rule values to the set. -func insertRules(set map[*Rule]struct{}, rules []util.T) { +func insertRules(set map[*Rule]struct{}, rules []any) { for _, rule := range rules { set[rule.(*Rule)] = struct{}{} } @@ -840,7 +855,7 @@ func (c *Compiler) PassesTypeCheckRules(rules []*Rule) Errors { tpe, err := loadSchema(schema, allowNet) if err != nil { - return Errors{NewError(TypeErr, nil, err.Error())} + return Errors{NewError(TypeErr, nil, err.Error())} //nolint:govet } c.inputType = tpe } @@ -892,6 +907,13 @@ func (c *Compiler) WithModuleLoader(f ModuleLoader) *Compiler { return c } +// WithDefaultRegoVersion sets the default Rego version to use when a module doesn't specify one; +// such as when it's hand-crafted instead of parsed. +func (c *Compiler) WithDefaultRegoVersion(regoVersion RegoVersion) *Compiler { + c.defaultRegoVersion = regoVersion + return c +} + func (c *Compiler) counterAdd(name string, n uint64) { if c.metrics == nil { return @@ -949,6 +971,13 @@ func (c *Compiler) buildComprehensionIndices() { } } +var ( + keywordsTerm = StringTerm("keywords") + pathTerm = StringTerm("path") + annotationsTerm = StringTerm("annotations") + futureKeywordsPrefix = Ref{FutureRootDocument, keywordsTerm} +) + // buildRequiredCapabilities updates the required capabilities on the compiler // to include any keyword and feature dependencies present in the modules. The // built-in function dependencies will have already been added by the type @@ -958,62 +987,81 @@ func (c *Compiler) buildRequiredCapabilities() { features := map[string]struct{}{} // extract required keywords from modules + keywords := map[string]struct{}{} - futureKeywordsPrefix := Ref{FutureRootDocument, StringTerm("keywords")} + for _, name := range c.sorted { for _, imp := range c.imports[name] { + mod := c.Modules[name] path := imp.Path.Value.(Ref) switch { case path.Equal(RegoV1CompatibleRef): - features[FeatureRegoV1Import] = struct{}{} + if !c.moduleIsRegoV1(mod) { + features[FeatureRegoV1Import] = struct{}{} + } case path.HasPrefix(futureKeywordsPrefix): if len(path) == 2 { - for kw := range futureKeywords { - keywords[kw] = struct{}{} + if c.moduleIsRegoV1(mod) { + for kw := range futureKeywords { + keywords[kw] = struct{}{} + } + } else { + for kw := range allFutureKeywords { + keywords[kw] = struct{}{} + } } } else { - keywords[string(path[2].Value.(String))] = struct{}{} + kw := string(path[2].Value.(String)) + if c.moduleIsRegoV1(mod) { + for allowedKw := range futureKeywords { + if kw == allowedKw { + keywords[kw] = struct{}{} + break + } + } + } else { + for allowedKw := range allFutureKeywords { + if kw == allowedKw { + keywords[kw] = struct{}{} + break + } + } + } } } } } - c.Required.FutureKeywords = stringMapToSortedSlice(keywords) + c.Required.FutureKeywords = util.KeysSorted(keywords) // extract required features from modules for _, name := range c.sorted { - for _, rule := range c.Modules[name].Rules { - refLen := len(rule.Head.Reference) - if refLen >= 3 { - if refLen > len(rule.Head.Reference.ConstantPrefix()) { - features[FeatureRefHeads] = struct{}{} - } else { - features[FeatureRefHeadStringPrefixes] = struct{}{} + mod := c.Modules[name] + + if c.moduleIsRegoV1(mod) { + features[FeatureRegoV1] = struct{}{} + } else { + for _, rule := range mod.Rules { + refLen := len(rule.Head.Reference) + if refLen >= 3 { + if refLen > len(rule.Head.Reference.ConstantPrefix()) { + features[FeatureRefHeads] = struct{}{} + } else { + features[FeatureRefHeadStringPrefixes] = struct{}{} + } } } } } - c.Required.Features = stringMapToSortedSlice(features) + c.Required.Features = util.KeysSorted(features) for i, bi := range c.Required.Builtins { c.Required.Builtins[i] = bi.Minimal() } } -func stringMapToSortedSlice(xs map[string]struct{}) []string { - if len(xs) == 0 { - return nil - } - s := make([]string, 0, len(xs)) - for k := range xs { - s = append(s, k) - } - sort.Strings(s) - return s -} - // checkRecursion ensures that there are no recursive definitions, i.e., there are // no cycles in the Graph. func (c *Compiler) checkRecursion() { @@ -1056,12 +1104,12 @@ func (c *Compiler) checkRuleConflicts() { } kinds := make(map[RuleKind]struct{}, len(node.Values)) - defaultRules := 0 completeRules := 0 partialRules := 0 arities := make(map[int]struct{}, len(node.Values)) name := "" var conflicts []Ref + defaultRules := make([]*Rule, 0) for _, rule := range node.Values { r := rule.(*Rule) @@ -1070,7 +1118,7 @@ func (c *Compiler) checkRuleConflicts() { kinds[r.Head.RuleKind()] = struct{}{} arities[len(r.Head.Args)] = struct{}{} if r.Default { - defaultRules++ + defaultRules = append(defaultRules, r) } // Single-value rules may not have any other rules in their extent. @@ -1126,8 +1174,21 @@ func (c *Compiler) checkRuleConflicts() { case len(kinds) > 1 || len(arities) > 1 || (completeRules >= 1 && partialRules >= 1): c.err(NewError(TypeErr, node.Values[0].(*Rule).Loc(), "conflicting rules %v found", name)) - case defaultRules > 1: - c.err(NewError(TypeErr, node.Values[0].(*Rule).Loc(), "multiple default rules %s found", name)) + case len(defaultRules) > 1: + + defaultRuleLocations := strings.Builder{} + defaultRuleLocations.WriteString(defaultRules[0].Loc().String()) + for i := 1; i < len(defaultRules); i++ { + defaultRuleLocations.WriteString(", ") + defaultRuleLocations.WriteString(defaultRules[i].Loc().String()) + } + + c.err(NewError( + TypeErr, + defaultRules[0].Module.Package.Loc(), + "multiple default rules %s found at %s", + name, defaultRuleLocations.String()), + ) } return false @@ -1158,7 +1219,7 @@ func (c *Compiler) checkRuleConflicts() { continue // don't self-conflict } msg := fmt.Sprintf("%v conflicts with rule %v defined at %v", childMod.Package, rule.Head.Ref(), rule.Loc()) - c.err(NewError(TypeErr, mod.Package.Loc(), msg)) + c.err(NewError(TypeErr, mod.Package.Loc(), msg)) //nolint:govet } } } @@ -1542,6 +1603,10 @@ func (c *Compiler) checkTypes() { } func (c *Compiler) checkUnsafeBuiltins() { + if len(c.unsafeBuiltinsMap) == 0 { + return + } + for _, name := range c.sorted { errs := checkUnsafeBuiltins(c.unsafeBuiltinsMap, c.Modules[name]) for _, err := range errs { @@ -1551,6 +1616,17 @@ func (c *Compiler) checkUnsafeBuiltins() { } func (c *Compiler) checkDeprecatedBuiltins() { + checkNeeded := false + for _, b := range c.Required.Builtins { + if _, found := c.deprecatedBuiltinsMap[b.Name]; found { + checkNeeded = true + break + } + } + if !checkNeeded { + return + } + for _, name := range c.sorted { mod := c.Modules[name] if c.strict || mod.regoV1Compatible() { @@ -1639,7 +1715,7 @@ func (c *Compiler) init() { if schema := c.schemaSet.Get(SchemaRootRef); schema != nil { tpe, err := loadSchema(schema, c.capabilities.AllowNet) if err != nil { - c.err(NewError(TypeErr, nil, err.Error())) + c.err(NewError(TypeErr, nil, err.Error())) //nolint:govet } else { c.inputType = tpe } @@ -1699,12 +1775,22 @@ func (c *Compiler) GetAnnotationSet() *AnnotationSet { return c.annotationSet } -func (c *Compiler) checkDuplicateImports() { +func (c *Compiler) checkImports() { modules := make([]*Module, 0, len(c.Modules)) + supportsRegoV1Import := c.capabilities.ContainsFeature(FeatureRegoV1Import) || + c.capabilities.ContainsFeature(FeatureRegoV1) + for _, name := range c.sorted { mod := c.Modules[name] - if c.strict || mod.regoV1Compatible() { + + for _, imp := range mod.Imports { + if !supportsRegoV1Import && RegoV1CompatibleRef.Equal(imp.Path.Value) { + c.err(NewError(CompileErr, imp.Loc(), "rego.v1 import is not supported")) + } + } + + if c.strict || c.moduleIsRegoV1Compatible(mod) { modules = append(modules, mod) } } @@ -1718,7 +1804,7 @@ func (c *Compiler) checkDuplicateImports() { func (c *Compiler) checkKeywordOverrides() { for _, name := range c.sorted { mod := c.Modules[name] - if c.strict || mod.regoV1Compatible() { + if c.strict || c.moduleIsRegoV1Compatible(mod) { errs := checkRootDocumentOverrides(mod) for _, err := range errs { c.err(err) @@ -1727,6 +1813,34 @@ func (c *Compiler) checkKeywordOverrides() { } } +func (c *Compiler) moduleIsRegoV1(mod *Module) bool { + if mod.regoVersion == RegoUndefined { + switch c.defaultRegoVersion { + case RegoUndefined: + c.err(NewError(CompileErr, mod.Package.Loc(), "cannot determine rego version for module")) + return false + case RegoV1: + return true + } + return false + } + return mod.regoVersion == RegoV1 +} + +func (c *Compiler) moduleIsRegoV1Compatible(mod *Module) bool { + if mod.regoVersion == RegoUndefined { + switch c.defaultRegoVersion { + case RegoUndefined: + c.err(NewError(CompileErr, mod.Package.Loc(), "cannot determine rego version for module")) + return false + case RegoV1, RegoV0CompatV1: + return true + } + return false + } + return mod.regoV1Compatible() +} + // resolveAllRefs resolves references in expressions to their fully qualified values. // // For instance, given the following module: @@ -1761,7 +1875,7 @@ func (c *Compiler) resolveAllRefs() { WalkRules(mod, func(rule *Rule) bool { err := resolveRefsInRule(globals, rule) if err != nil { - c.err(NewError(CompileErr, rule.Location, err.Error())) + c.err(NewError(CompileErr, rule.Location, err.Error())) //nolint:govet } return false }) @@ -1786,7 +1900,7 @@ func (c *Compiler) resolveAllRefs() { parsed, err := c.moduleLoader(c.Modules) if err != nil { - c.err(NewError(CompileErr, nil, err.Error())) + c.err(NewError(CompileErr, nil, err.Error())) //nolint:govet return } @@ -1859,6 +1973,9 @@ func (c *Compiler) rewriteRuleHeadRefs() { cannotSpeakStringPrefixRefs = false case FeatureRefHeads: cannotSpeakGeneralRefs = false + case FeatureRegoV1: + cannotSpeakStringPrefixRefs = false + cannotSpeakGeneralRefs = false } } @@ -2110,8 +2227,10 @@ func containsPrintCall(x interface{}) bool { return found } +var printRef = Print.Ref() + func isPrintCall(x *Expr) bool { - return x.IsCall() && x.Operator().Equal(Print.Ref()) + return x.IsCall() && x.Operator().Equal(printRef) } // rewriteRefsInHead will rewrite rules so that the head does not contain any @@ -2346,8 +2465,8 @@ func getPrimaryRuleAnnotations(as *AnnotationSet, rule *Rule) *Annotations { } // Sort by annotation location; chain must start with annotations declared closest to rule, then going outward - sort.SliceStable(annots, func(i, j int) bool { - return annots[i].Location.Compare(annots[j].Location) > 0 + slices.SortStableFunc(annots, func(a, b *Annotations) int { + return -a.Location.Compare(b.Location) }) return annots[0] @@ -2401,12 +2520,15 @@ func rewriteRegoMetadataCalls(metadataChainVar *Var, metadataRuleVar *Var, body return errs } +var regoMetadataChainRef = RegoMetadataChain.Ref() +var regoMetadataRuleRef = RegoMetadataRule.Ref() + func isRegoMetadataChainCall(x *Expr) bool { - return x.IsCall() && x.Operator().Equal(RegoMetadataChain.Ref()) + return x.IsCall() && x.Operator().Equal(regoMetadataChainRef) } func isRegoMetadataRuleCall(x *Expr) bool { - return x.IsCall() && x.Operator().Equal(RegoMetadataRule.Ref()) + return x.IsCall() && x.Operator().Equal(regoMetadataRuleRef) } func createMetadataChain(chain []*AnnotationsRef) (*Term, *Error) { @@ -2416,14 +2538,14 @@ func createMetadataChain(chain []*AnnotationsRef) (*Term, *Error) { p := link.Path.toArray(). Slice(1, -1) // Dropping leading 'data' element of path obj := NewObject( - Item(StringTerm("path"), NewTerm(p)), + Item(pathTerm, NewTerm(p)), ) if link.Annotations != nil { annotObj, err := link.Annotations.toObject() if err != nil { return nil, err } - obj.Insert(StringTerm("annotations"), NewTerm(*annotObj)) + obj.Insert(annotationsTerm, NewTerm(*annotObj)) } metaArray = metaArray.Append(NewTerm(obj)) } @@ -2538,9 +2660,7 @@ func (c *Compiler) rewriteLocalVarsInRule(rule *Rule, unusedArgs VarSet, argsSta // For rewritten vars use the collection of all variables that // were in the stack at some point in time. - for k, v := range stack.rewritten { - c.RewrittenVars[k] = v - } + maps.Copy(c.RewrittenVars, stack.rewritten) rule.Body = body @@ -2608,9 +2728,7 @@ func (xform *rewriteNestedHeadVarLocalTransform) Visit(x interface{}) bool { stop = true } - for k, v := range stack.rewritten { - xform.RewrittenVars[k] = v - } + maps.Copy(xform.RewrittenVars, stack.rewritten) return stop } @@ -2677,7 +2795,7 @@ func (vis *ruleArgLocalRewriter) Visit(x interface{}) Visitor { Walk(vis, vcpy) return k, vcpy, nil }); err != nil { - vis.errs = append(vis.errs, NewError(CompileErr, t.Location, err.Error())) + vis.errs = append(vis.errs, NewError(CompileErr, t.Location, err.Error())) //nolint:govet } else { t.Value = cpy } @@ -2937,13 +3055,12 @@ func (qc *queryCompiler) rewriteLocalVars(_ *QueryContext, body Body) (Body, err if len(err) != 0 { return nil, err } - qc.rewritten = make(map[Var]Var, len(stack.rewritten)) - for k, v := range stack.rewritten { - // The vars returned during the rewrite will include all seen vars, - // even if they're not declared with an assignment operation. We don't - // want to include these inside the rewritten set though. - qc.rewritten[k] = v - } + + // The vars returned during the rewrite will include all seen vars, + // even if they're not declared with an assignment operation. We don't + // want to include these inside the rewritten set though. + qc.rewritten = maps.Clone(stack.rewritten) + return body, nil } @@ -3171,9 +3288,7 @@ func getComprehensionIndex(dbg debug.Debug, arity func(Ref) int, candidates VarS result = append(result, NewTerm(v)) } - sort.Slice(result, func(i, j int) bool { - return result[i].Value.Compare(result[j].Value) < 0 - }) + slices.SortFunc(result, TermValueCompare) debugRes := make([]*Term, len(result)) for i, r := range result { @@ -3298,12 +3413,7 @@ func NewModuleTree(mods map[string]*Module) *ModuleTreeNode { root := &ModuleTreeNode{ Children: map[Value]*ModuleTreeNode{}, } - names := make([]string, 0, len(mods)) - for name := range mods { - names = append(names, name) - } - sort.Strings(names) - for _, name := range names { + for _, name := range util.KeysSorted(mods) { m := mods[name] node := root for i, x := range m.Package.Path { @@ -3380,7 +3490,7 @@ func (n *ModuleTreeNode) DepthFirst(f func(*ModuleTreeNode) bool) { // rule path. type TreeNode struct { Key Value - Values []util.T + Values []any Children map[Value]*TreeNode Sorted []Value Hide bool @@ -3500,9 +3610,7 @@ func (n *TreeNode) DepthFirst(f func(*TreeNode) bool) { } func (n *TreeNode) sort() { - sort.Slice(n.Sorted, func(i, j int) bool { - return n.Sorted[i].Compare(n.Sorted[j]) < 0 - }) + slices.SortFunc(n.Sorted, Value.Compare) } func treeNodeFromRef(ref Ref, rule *Rule) *TreeNode { @@ -3513,7 +3621,7 @@ func treeNodeFromRef(ref Ref, rule *Rule) *TreeNode { Children: nil, } if rule != nil { - node.Values = []util.T{rule} + node.Values = []any{rule} } for i := len(ref) - 2; i >= 0; i-- { @@ -3540,9 +3648,7 @@ func (n *TreeNode) flattenChildren() []Ref { }) } - sort.Slice(ret.s, func(i, j int) bool { - return ret.s[i].Compare(ret.s[j]) < 0 - }) + slices.SortFunc(ret.s, RefCompare) return ret.s } @@ -3780,8 +3886,8 @@ func (vs unsafeVars) Vars() (result []unsafeVarLoc) { }) } - sort.Slice(result, func(i, j int) bool { - return result[i].Loc.Compare(result[j].Loc) < 0 + slices.SortFunc(result, func(a, b unsafeVarLoc) int { + return a.Loc.Compare(b.Loc) }) return result @@ -4993,23 +5099,13 @@ func (s *localDeclaredVars) Copy() *localDeclaredVars { for i := range s.vars { stack.vars = append(stack.vars, newDeclaredVarSet()) - for k, v := range s.vars[i].vs { - stack.vars[0].vs[k] = v - } - for k, v := range s.vars[i].reverse { - stack.vars[0].reverse[k] = v - } - for k, v := range s.vars[i].count { - stack.vars[0].count[k] = v - } - for k, v := range s.vars[i].occurrence { - stack.vars[0].occurrence[k] = v - } + maps.Copy(stack.vars[0].vs, s.vars[i].vs) + maps.Copy(stack.vars[0].reverse, s.vars[i].reverse) + maps.Copy(stack.vars[0].occurrence, s.vars[i].occurrence) + maps.Copy(stack.vars[0].count, s.vars[i].count) } - for k, v := range s.rewritten { - stack.rewritten[k] = v - } + maps.Copy(stack.rewritten, s.rewritten) return stack } @@ -5258,7 +5354,7 @@ func rewriteEveryStatement(g *localVarGenerator, stack *localDeclaredVars, expr if v := every.Key.Value.(Var); !v.IsWildcard() { gv, err := rewriteDeclaredVar(g, stack, v, declaredVar) if err != nil { - return nil, append(errs, NewError(CompileErr, every.Loc(), err.Error())) + return nil, append(errs, NewError(CompileErr, every.Loc(), err.Error())) //nolint:govet } every.Key.Value = gv } @@ -5270,7 +5366,7 @@ func rewriteEveryStatement(g *localVarGenerator, stack *localDeclaredVars, expr if v := every.Value.Value.(Var); !v.IsWildcard() { gv, err := rewriteDeclaredVar(g, stack, v, declaredVar) if err != nil { - return nil, append(errs, NewError(CompileErr, every.Loc(), err.Error())) + return nil, append(errs, NewError(CompileErr, every.Loc(), err.Error())) //nolint:govet } every.Value.Value = gv } @@ -5288,7 +5384,7 @@ func rewriteSomeDeclStatement(g *localVarGenerator, stack *localDeclaredVars, ex switch v := decl.Symbols[i].Value.(type) { case Var: if _, err := rewriteDeclaredVar(g, stack, v, declaredVar); err != nil { - return nil, append(errs, NewError(CompileErr, decl.Loc(), err.Error())) + return nil, append(errs, NewError(CompileErr, decl.Loc(), err.Error())) //nolint:govet } case Call: var key, val, container *Term @@ -5316,7 +5412,7 @@ func rewriteSomeDeclStatement(g *localVarGenerator, stack *localDeclaredVars, ex for _, v0 := range outputVarsForExprEq(e, container.Vars()).Sorted() { if _, err := rewriteDeclaredVar(g, stack, v0, declaredVar); err != nil { - return nil, append(errs, NewError(CompileErr, decl.Loc(), err.Error())) + return nil, append(errs, NewError(CompileErr, decl.Loc(), err.Error())) //nolint:govet } } return rewriteDeclaredVarsInExpr(g, stack, e, errs, strict) @@ -5332,8 +5428,7 @@ func rewriteDeclaredVarsInExpr(g *localVarGenerator, stack *localDeclaredVars, e case *Term: stop, errs = rewriteDeclaredVarsInTerm(g, stack, x, errs, strict) case *With: - errs = rewriteDeclaredVarsInTermRecursive(g, stack, x.Value, errs, strict) - stop = true + stop, errs = true, rewriteDeclaredVarsInWithRecursive(g, stack, x, errs, strict) } return stop }) @@ -5371,7 +5466,7 @@ func rewriteDeclaredAssignment(g *localVarGenerator, stack *localDeclaredVars, e switch v := t.Value.(type) { case Var: if gv, err := rewriteDeclaredVar(g, stack, v, assignedVar); err != nil { - errs = append(errs, NewError(CompileErr, t.Location, err.Error())) + errs = append(errs, NewError(CompileErr, t.Location, err.Error())) //nolint:govet } else { t.Value = gv } @@ -5386,14 +5481,14 @@ func rewriteDeclaredAssignment(g *localVarGenerator, stack *localDeclaredVars, e case Ref: if RootDocumentRefs.Contains(t) { if gv, err := rewriteDeclaredVar(g, stack, v[0].Value.(Var), assignedVar); err != nil { - errs = append(errs, NewError(CompileErr, t.Location, err.Error())) + errs = append(errs, NewError(CompileErr, t.Location, err.Error())) //nolint:govet } else { t.Value = gv } return true } } - errs = append(errs, NewError(CompileErr, t.Location, "cannot assign to %v", TypeName(t.Value))) + errs = append(errs, NewError(CompileErr, t.Location, "cannot assign to %v", ValueName(t.Value))) return true } @@ -5466,20 +5561,38 @@ func rewriteDeclaredVarsInTerm(g *localVarGenerator, stack *localDeclaredVars, t } func rewriteDeclaredVarsInTermRecursive(g *localVarGenerator, stack *localDeclaredVars, term *Term, errs Errors, strict bool) Errors { - WalkNodes(term, func(n Node) bool { + WalkTerms(term, func(t *Term) bool { var stop bool - switch n := n.(type) { - case *With: - errs = rewriteDeclaredVarsInTermRecursive(g, stack, n.Value, errs, strict) - stop = true - case *Term: - stop, errs = rewriteDeclaredVarsInTerm(g, stack, n, errs, strict) - } + stop, errs = rewriteDeclaredVarsInTerm(g, stack, t, errs, strict) return stop }) return errs } +func rewriteDeclaredVarsInWithRecursive(g *localVarGenerator, stack *localDeclaredVars, w *With, errs Errors, strict bool) Errors { + // NOTE(sr): `with input as` and `with input.a.b.c as` are deliberately skipped here: `input` could + // have been shadowed by a local variable/argument but should NOT be replaced in the `with` target. + // + // We cannot drop `input` from the stack since it's conceivable to do `with input[input] as` where + // the second input is meant to be the local var. It's a terrible idea, but when you're shadowing + // `input` those might be your thing. + errs = rewriteDeclaredVarsInTermRecursive(g, stack, w.Target, errs, strict) + if sdwInput, ok := stack.Declared(InputRootDocument.Value.(Var)); ok { // Was "input" shadowed... + switch value := w.Target.Value.(type) { + case Var: + if sdwInput.Equal(value) { // ...and replaced? If so, fix it + w.Target.Value = InputRootRef + } + case Ref: + if sdwInput.Equal(value[0].Value.(Var)) { + w.Target.Value.(Ref)[0].Value = InputRootDocument.Value + } + } + } + // No special handling of the `with` value + return rewriteDeclaredVarsInTermRecursive(g, stack, w.Value, errs, strict) +} + func rewriteDeclaredVarsInArrayComprehension(g *localVarGenerator, stack *localDeclaredVars, v *ArrayComprehension, errs Errors, strict bool) Errors { used := NewVarSet() used.Update(v.Term.Vars()) @@ -5746,7 +5859,7 @@ func safetyErrorSlice(unsafe unsafeVars, rewritten map[Var]Var) (result Errors) v = w } if !v.IsGenerated() { - if _, ok := futureKeywords[string(v)]; ok { + if _, ok := allFutureKeywords[string(v)]; ok { result = append(result, NewError(UnsafeVarErr, pair.Loc, "var %[1]v is unsafe (hint: `import future.keywords.%[1]v` to import a future keyword)", v)) continue @@ -5764,8 +5877,8 @@ func safetyErrorSlice(unsafe unsafeVars, rewritten map[Var]Var) (result Errors) // the latter are not meaningful to the user.) pairs := unsafe.Slice() - sort.Slice(pairs, func(i, j int) bool { - return pairs[i].Expr.Location.Compare(pairs[j].Expr.Location) < 0 + slices.SortFunc(pairs, func(a, b unsafePair) int { + return a.Expr.Location.Compare(b.Expr.Location) }) // Report at most one error per generated variable. @@ -5832,12 +5945,7 @@ func newRefSet(x ...Ref) *refSet { // ContainsPrefix returns true if r is prefixed by any of the existing refs in the set. func (rs *refSet) ContainsPrefix(r Ref) bool { - for i := range rs.s { - if r.HasPrefix(rs.s[i]) { - return true - } - } - return false + return slices.ContainsFunc(rs.s, r.HasPrefix) } // AddPrefix inserts r into the set if r is not prefixed by any existing @@ -5862,8 +5970,6 @@ func (rs *refSet) Sorted() []*Term { for i := range rs.s { terms[i] = NewTerm(rs.s[i]) } - sort.Slice(terms, func(i, j int) bool { - return terms[i].Value.Compare(terms[j].Value) < 0 - }) + slices.SortFunc(terms, TermValueCompare) return terms } diff --git a/vendor/github.com/open-policy-agent/opa/ast/compilehelper.go b/vendor/github.com/open-policy-agent/opa/v1/ast/compilehelper.go similarity index 92% rename from vendor/github.com/open-policy-agent/opa/ast/compilehelper.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/compilehelper.go index dd48884f9d..7d81d45e6d 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/compilehelper.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/compilehelper.go @@ -31,7 +31,9 @@ func CompileModulesWithOpt(modules map[string]string, opts CompileOpts) (*Compil parsed[f] = pm } - compiler := NewCompiler().WithEnablePrintStatements(opts.EnablePrintStatements) + compiler := NewCompiler(). + WithDefaultRegoVersion(opts.ParserOptions.RegoVersion). + WithEnablePrintStatements(opts.EnablePrintStatements) compiler.Compile(parsed) if compiler.Failed() { diff --git a/vendor/github.com/open-policy-agent/opa/ast/compilemetrics.go b/vendor/github.com/open-policy-agent/opa/v1/ast/compilemetrics.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/ast/compilemetrics.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/compilemetrics.go diff --git a/vendor/github.com/open-policy-agent/opa/ast/conflicts.go b/vendor/github.com/open-policy-agent/opa/v1/ast/conflicts.go similarity index 63% rename from vendor/github.com/open-policy-agent/opa/ast/conflicts.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/conflicts.go index c2713ad576..685cc6b694 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/conflicts.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/conflicts.go @@ -5,6 +5,7 @@ package ast import ( + "slices" "strings" ) @@ -18,8 +19,33 @@ func CheckPathConflicts(c *Compiler, exists func([]string) (bool, error)) Errors return nil } - for _, node := range root.Children { - errs = append(errs, checkDocumentConflicts(node, exists, nil)...) + if len(c.pathConflictCheckRoots) == 0 || slices.Contains(c.pathConflictCheckRoots, "") { + for _, child := range root.Children { + errs = append(errs, checkDocumentConflicts(child, exists, nil)...) + } + return errs + } + + for _, rootPath := range c.pathConflictCheckRoots { + // traverse AST from `path` to go to the new root + paths := strings.Split(rootPath, "/") + node := root + for _, key := range paths { + node = node.Child(String(key)) + if node == nil { + break + } + } + + if node == nil { + // could not find the node from the AST (e.g. `path` is from a data file) + // then no conflict is possible + continue + } + + for _, child := range node.Children { + errs = append(errs, checkDocumentConflicts(child, exists, paths)...) + } } return errs diff --git a/vendor/github.com/open-policy-agent/opa/ast/doc.go b/vendor/github.com/open-policy-agent/opa/v1/ast/doc.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/ast/doc.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/doc.go diff --git a/vendor/github.com/open-policy-agent/opa/ast/env.go b/vendor/github.com/open-policy-agent/opa/v1/ast/env.go similarity index 99% rename from vendor/github.com/open-policy-agent/opa/ast/env.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/env.go index c767aafefb..fb374b1739 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/env.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/env.go @@ -8,8 +8,8 @@ import ( "fmt" "strings" - "github.com/open-policy-agent/opa/types" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/types" + "github.com/open-policy-agent/opa/v1/util" ) // TypeEnv contains type info for static analysis such as type checking. diff --git a/vendor/github.com/open-policy-agent/opa/ast/errors.go b/vendor/github.com/open-policy-agent/opa/v1/ast/errors.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/ast/errors.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/errors.go diff --git a/vendor/github.com/open-policy-agent/opa/ast/index.go b/vendor/github.com/open-policy-agent/opa/v1/ast/index.go similarity index 94% rename from vendor/github.com/open-policy-agent/opa/ast/index.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/index.go index cb0cbea323..63cd480d13 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/index.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/index.go @@ -8,8 +8,9 @@ import ( "fmt" "sort" "strings" + "sync" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/util" ) // RuleIndex defines the interface for rule indices. @@ -62,9 +63,16 @@ type baseDocEqIndex struct { onlyGroundRefs bool } +var ( + equalityRef = Equality.Ref() + equalRef = Equal.Ref() + globMatchRef = GlobMatch.Ref() + internalPrintRef = InternalPrint.Ref() +) + func newBaseDocEqIndex(isVirtual func(Ref) bool) *baseDocEqIndex { return &baseDocEqIndex{ - skipIndexing: NewSet(NewTerm(InternalPrint.Ref())), + skipIndexing: NewSet(NewTerm(internalPrintRef)), isVirtual: isVirtual, root: newTrieNodeImpl(), onlyGroundRefs: true, @@ -130,8 +138,15 @@ func (i *baseDocEqIndex) Build(rules []*Rule) bool { } func (i *baseDocEqIndex) Lookup(resolver ValueResolver) (*IndexResult, error) { + tr := ttrPool.Get().(*trieTraversalResult) - tr := newTrieTraversalResult() + defer func() { + clear(tr.unordered) + tr.ordering = tr.ordering[:0] + tr.values.clear() + + ttrPool.Put(tr) + }() err := i.root.Traverse(resolver, tr) if err != nil { @@ -255,17 +270,17 @@ func (i *refindices) Update(rule *Rule, expr *Expr) { op := expr.Operator() switch { - case op.Equal(Equality.Ref()): + case op.Equal(equalityRef): i.updateEq(rule, expr) - case op.Equal(Equal.Ref()) && len(expr.Operands()) == 2: + case op.Equal(equalRef) && len(expr.Operands()) == 2: // NOTE(tsandall): if equal() is called with more than two arguments the // output value is being captured in which case the indexer cannot // exclude the rule if the equal() call would return false (because the // false value must still be produced.) i.updateEq(rule, expr) - case op.Equal(GlobMatch.Ref()) && len(expr.Operands()) == 3: + case op.Equal(globMatchRef) && len(expr.Operands()) == 3: // NOTE(sr): Same as with equal() above -- 4 operands means the output // of `glob.match` is captured and the rule can thus not be excluded. i.updateGlobMatch(rule, expr) @@ -354,7 +369,7 @@ func (i *refindices) updateGlobMatch(rule *Rule, expr *Expr) { if ref == nil { for j, arg := range args { if arg.Equal(match) { - ref = Ref{FunctionArgRootDocument, IntNumberTerm(j)} + ref = Ref{FunctionArgRootDocument, InternedIntNumberTerm(j)} } } } @@ -412,13 +427,22 @@ type trieWalker interface { type trieTraversalResult struct { unordered map[int][]*ruleNode ordering []int - values Set + values *set +} + +var ttrPool = sync.Pool{ + New: func() any { + return newTrieTraversalResult() + }, } func newTrieTraversalResult() *trieTraversalResult { return &trieTraversalResult{ unordered: map[int][]*ruleNode{}, - values: NewSet(), + // Number 3 is arbitrary, but seemed to be the most common number of values + // stored when benchmarking the trie traversal against a large policy library + // (Regal). + values: newset(3), } } @@ -432,7 +456,7 @@ func (tr *trieTraversalResult) Add(t *trieNode) { tr.unordered[root] = append(nodes, node) } if t.values != nil { - t.values.Foreach(func(v *Term) { tr.values.Add(v) }) + t.values.Foreach(tr.values.insertNoGuard) } } @@ -764,7 +788,7 @@ func eqOperandsToRefAndValue(isVirtual func(Ref) bool, args []*Term, a, b *Term) for i, arg := range args { if arg.Value.Compare(v) == 0 { if bval, ok := indexValue(b); ok { - return &refindex{Ref: Ref{FunctionArgRootDocument, IntNumberTerm(i)}, Value: bval}, true + return &refindex{Ref: Ref{FunctionArgRootDocument, InternedIntNumberTerm(i)}, Value: bval}, true } } } diff --git a/vendor/github.com/open-policy-agent/opa/ast/internal/scanner/scanner.go b/vendor/github.com/open-policy-agent/opa/v1/ast/internal/scanner/scanner.go similarity index 95% rename from vendor/github.com/open-policy-agent/opa/ast/internal/scanner/scanner.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/internal/scanner/scanner.go index a0200ac18d..4558f91415 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/internal/scanner/scanner.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/internal/scanner/scanner.go @@ -9,8 +9,9 @@ import ( "io" "unicode" "unicode/utf8" + "unsafe" - "github.com/open-policy-agent/opa/ast/internal/tokens" + "github.com/open-policy-agent/opa/v1/ast/internal/tokens" ) const bom = 0xFEFF @@ -18,31 +19,31 @@ const bom = 0xFEFF // Scanner is used to tokenize an input stream of // Rego source code. type Scanner struct { + keywords map[string]tokens.Token + bs []byte + errors []Error + tabs []int offset int row int col int - bs []byte - curr rune width int - errors []Error - keywords map[string]tokens.Token - tabs []int + curr rune regoV1Compatible bool } // Error represents a scanner error. type Error struct { - Pos Position Message string + Pos Position } // Position represents a point in the scanned source code. type Position struct { + Tabs []int // positions of any tabs preceding Col Offset int // start offset in bytes End int // end offset in bytes Row int // line number computed in bytes Col int // column number computed in bytes - Tabs []int // positions of any tabs preceding Col } // New returns an initialized scanner that will scan @@ -270,7 +271,8 @@ func (s *Scanner) scanIdentifier() string { for isLetter(s.curr) || isDigit(s.curr) { s.next() } - return string(s.bs[start : s.offset-1]) + + return byteSliceToString(s.bs[start : s.offset-1]) } func (s *Scanner) scanNumber() string { @@ -321,7 +323,7 @@ func (s *Scanner) scanNumber() string { } } - return string(s.bs[start : s.offset-1]) + return byteSliceToString(s.bs[start : s.offset-1]) } func (s *Scanner) scanString() string { @@ -355,7 +357,7 @@ func (s *Scanner) scanString() string { } } - return string(s.bs[start : s.offset-1]) + return byteSliceToString(s.bs[start : s.offset-1]) } func (s *Scanner) scanRawString() string { @@ -370,7 +372,8 @@ func (s *Scanner) scanRawString() string { break } } - return string(s.bs[start : s.offset-1]) + + return byteSliceToString(s.bs[start : s.offset-1]) } func (s *Scanner) scanComment() string { @@ -383,7 +386,8 @@ func (s *Scanner) scanComment() string { if s.offset > 1 && s.bs[s.offset-2] == '\r' { end = end - 1 } - return string(s.bs[start:end]) + + return byteSliceToString(s.bs[start:end]) } func (s *Scanner) next() { @@ -413,7 +417,7 @@ func (s *Scanner) next() { if s.curr == '\n' { s.row++ s.col = 0 - s.tabs = []int{} + s.tabs = s.tabs[:0] } else { s.col++ if s.curr == '\t' { @@ -453,3 +457,7 @@ func (s *Scanner) error(reason string) { Col: s.col, }, Message: reason}) } + +func byteSliceToString(bs []byte) string { + return unsafe.String(unsafe.SliceData(bs), len(bs)) +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/internal/tokens/tokens.go b/vendor/github.com/open-policy-agent/opa/v1/ast/internal/tokens/tokens.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/ast/internal/tokens/tokens.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/internal/tokens/tokens.go diff --git a/vendor/github.com/open-policy-agent/opa/v1/ast/interning.go b/vendor/github.com/open-policy-agent/opa/v1/ast/interning.go new file mode 100644 index 0000000000..17b10231b7 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/interning.go @@ -0,0 +1,1098 @@ +// Copyright 2024 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import "strconv" + +// NOTE! Great care must be taken **not** to modify the terms returned +// from these functions, as they are shared across all callers. + +var ( + booleanTrueTerm = &Term{Value: Boolean(true)} + booleanFalseTerm = &Term{Value: Boolean(false)} + + // since this is by far the most common negative number + minusOneTerm = &Term{Value: Number("-1")} + + InternedNullTerm = &Term{Value: Null{}} +) + +// InternedBooleanTerm returns an interned term with the given boolean value. +func InternedBooleanTerm(b bool) *Term { + if b { + return booleanTrueTerm + } + + return booleanFalseTerm +} + +// InternedIntNumberTerm returns a term with the given integer value. The term is +// cached between -1 to 512, and for values outside of that range, this function +// is equivalent to ast.IntNumberTerm. +func InternedIntNumberTerm(i int) *Term { + if i >= 0 && i < len(intNumberTerms) { + return intNumberTerms[i] + } + + if i == -1 { + return minusOneTerm + } + + return &Term{Value: Number(strconv.Itoa(i))} +} + +// InternedIntFromString returns a term with the given integer value if the string +// maps to an interned term. If the string does not map to an interned term, nil is +// returned. +func InternedIntNumberTermFromString(s string) *Term { + if term, ok := stringToIntNumberTermMap[s]; ok { + return term + } + + return nil +} + +// HasInternedIntNumberTerm returns true if the given integer value maps to an interned +// term, otherwise false. +func HasInternedIntNumberTerm(i int) bool { + return i >= -1 && i < len(intNumberTerms) +} + +var stringToIntNumberTermMap = map[string]*Term{ + "-1": minusOneTerm, + "0": intNumberTerms[0], + "1": intNumberTerms[1], + "2": intNumberTerms[2], + "3": intNumberTerms[3], + "4": intNumberTerms[4], + "5": intNumberTerms[5], + "6": intNumberTerms[6], + "7": intNumberTerms[7], + "8": intNumberTerms[8], + "9": intNumberTerms[9], + "10": intNumberTerms[10], + "11": intNumberTerms[11], + "12": intNumberTerms[12], + "13": intNumberTerms[13], + "14": intNumberTerms[14], + "15": intNumberTerms[15], + "16": intNumberTerms[16], + "17": intNumberTerms[17], + "18": intNumberTerms[18], + "19": intNumberTerms[19], + "20": intNumberTerms[20], + "21": intNumberTerms[21], + "22": intNumberTerms[22], + "23": intNumberTerms[23], + "24": intNumberTerms[24], + "25": intNumberTerms[25], + "26": intNumberTerms[26], + "27": intNumberTerms[27], + "28": intNumberTerms[28], + "29": intNumberTerms[29], + "30": intNumberTerms[30], + "31": intNumberTerms[31], + "32": intNumberTerms[32], + "33": intNumberTerms[33], + "34": intNumberTerms[34], + "35": intNumberTerms[35], + "36": intNumberTerms[36], + "37": intNumberTerms[37], + "38": intNumberTerms[38], + "39": intNumberTerms[39], + "40": intNumberTerms[40], + "41": intNumberTerms[41], + "42": intNumberTerms[42], + "43": intNumberTerms[43], + "44": intNumberTerms[44], + "45": intNumberTerms[45], + "46": intNumberTerms[46], + "47": intNumberTerms[47], + "48": intNumberTerms[48], + "49": intNumberTerms[49], + "50": intNumberTerms[50], + "51": intNumberTerms[51], + "52": intNumberTerms[52], + "53": intNumberTerms[53], + "54": intNumberTerms[54], + "55": intNumberTerms[55], + "56": intNumberTerms[56], + "57": intNumberTerms[57], + "58": intNumberTerms[58], + "59": intNumberTerms[59], + "60": intNumberTerms[60], + "61": intNumberTerms[61], + "62": intNumberTerms[62], + "63": intNumberTerms[63], + "64": intNumberTerms[64], + "65": intNumberTerms[65], + "66": intNumberTerms[66], + "67": intNumberTerms[67], + "68": intNumberTerms[68], + "69": intNumberTerms[69], + "70": intNumberTerms[70], + "71": intNumberTerms[71], + "72": intNumberTerms[72], + "73": intNumberTerms[73], + "74": intNumberTerms[74], + "75": intNumberTerms[75], + "76": intNumberTerms[76], + "77": intNumberTerms[77], + "78": intNumberTerms[78], + "79": intNumberTerms[79], + "80": intNumberTerms[80], + "81": intNumberTerms[81], + "82": intNumberTerms[82], + "83": intNumberTerms[83], + "84": intNumberTerms[84], + "85": intNumberTerms[85], + "86": intNumberTerms[86], + "87": intNumberTerms[87], + "88": intNumberTerms[88], + "89": intNumberTerms[89], + "90": intNumberTerms[90], + "91": intNumberTerms[91], + "92": intNumberTerms[92], + "93": intNumberTerms[93], + "94": intNumberTerms[94], + "95": intNumberTerms[95], + "96": intNumberTerms[96], + "97": intNumberTerms[97], + "98": intNumberTerms[98], + "99": intNumberTerms[99], + "100": intNumberTerms[100], + "101": intNumberTerms[101], + "102": intNumberTerms[102], + "103": intNumberTerms[103], + "104": intNumberTerms[104], + "105": intNumberTerms[105], + "106": intNumberTerms[106], + "107": intNumberTerms[107], + "108": intNumberTerms[108], + "109": intNumberTerms[109], + "110": intNumberTerms[110], + "111": intNumberTerms[111], + "112": intNumberTerms[112], + "113": intNumberTerms[113], + "114": intNumberTerms[114], + "115": intNumberTerms[115], + "116": intNumberTerms[116], + "117": intNumberTerms[117], + "118": intNumberTerms[118], + "119": intNumberTerms[119], + "120": intNumberTerms[120], + "121": intNumberTerms[121], + "122": intNumberTerms[122], + "123": intNumberTerms[123], + "124": intNumberTerms[124], + "125": intNumberTerms[125], + "126": intNumberTerms[126], + "127": intNumberTerms[127], + "128": intNumberTerms[128], + "129": intNumberTerms[129], + "130": intNumberTerms[130], + "131": intNumberTerms[131], + "132": intNumberTerms[132], + "133": intNumberTerms[133], + "134": intNumberTerms[134], + "135": intNumberTerms[135], + "136": intNumberTerms[136], + "137": intNumberTerms[137], + "138": intNumberTerms[138], + "139": intNumberTerms[139], + "140": intNumberTerms[140], + "141": intNumberTerms[141], + "142": intNumberTerms[142], + "143": intNumberTerms[143], + "144": intNumberTerms[144], + "145": intNumberTerms[145], + "146": intNumberTerms[146], + "147": intNumberTerms[147], + "148": intNumberTerms[148], + "149": intNumberTerms[149], + "150": intNumberTerms[150], + "151": intNumberTerms[151], + "152": intNumberTerms[152], + "153": intNumberTerms[153], + "154": intNumberTerms[154], + "155": intNumberTerms[155], + "156": intNumberTerms[156], + "157": intNumberTerms[157], + "158": intNumberTerms[158], + "159": intNumberTerms[159], + "160": intNumberTerms[160], + "161": intNumberTerms[161], + "162": intNumberTerms[162], + "163": intNumberTerms[163], + "164": intNumberTerms[164], + "165": intNumberTerms[165], + "166": intNumberTerms[166], + "167": intNumberTerms[167], + "168": intNumberTerms[168], + "169": intNumberTerms[169], + "170": intNumberTerms[170], + "171": intNumberTerms[171], + "172": intNumberTerms[172], + "173": intNumberTerms[173], + "174": intNumberTerms[174], + "175": intNumberTerms[175], + "176": intNumberTerms[176], + "177": intNumberTerms[177], + "178": intNumberTerms[178], + "179": intNumberTerms[179], + "180": intNumberTerms[180], + "181": intNumberTerms[181], + "182": intNumberTerms[182], + "183": intNumberTerms[183], + "184": intNumberTerms[184], + "185": intNumberTerms[185], + "186": intNumberTerms[186], + "187": intNumberTerms[187], + "188": intNumberTerms[188], + "189": intNumberTerms[189], + "190": intNumberTerms[190], + "191": intNumberTerms[191], + "192": intNumberTerms[192], + "193": intNumberTerms[193], + "194": intNumberTerms[194], + "195": intNumberTerms[195], + "196": intNumberTerms[196], + "197": intNumberTerms[197], + "198": intNumberTerms[198], + "199": intNumberTerms[199], + "200": intNumberTerms[200], + "201": intNumberTerms[201], + "202": intNumberTerms[202], + "203": intNumberTerms[203], + "204": intNumberTerms[204], + "205": intNumberTerms[205], + "206": intNumberTerms[206], + "207": intNumberTerms[207], + "208": intNumberTerms[208], + "209": intNumberTerms[209], + "210": intNumberTerms[210], + "211": intNumberTerms[211], + "212": intNumberTerms[212], + "213": intNumberTerms[213], + "214": intNumberTerms[214], + "215": intNumberTerms[215], + "216": intNumberTerms[216], + "217": intNumberTerms[217], + "218": intNumberTerms[218], + "219": intNumberTerms[219], + "220": intNumberTerms[220], + "221": intNumberTerms[221], + "222": intNumberTerms[222], + "223": intNumberTerms[223], + "224": intNumberTerms[224], + "225": intNumberTerms[225], + "226": intNumberTerms[226], + "227": intNumberTerms[227], + "228": intNumberTerms[228], + "229": intNumberTerms[229], + "230": intNumberTerms[230], + "231": intNumberTerms[231], + "232": intNumberTerms[232], + "233": intNumberTerms[233], + "234": intNumberTerms[234], + "235": intNumberTerms[235], + "236": intNumberTerms[236], + "237": intNumberTerms[237], + "238": intNumberTerms[238], + "239": intNumberTerms[239], + "240": intNumberTerms[240], + "241": intNumberTerms[241], + "242": intNumberTerms[242], + "243": intNumberTerms[243], + "244": intNumberTerms[244], + "245": intNumberTerms[245], + "246": intNumberTerms[246], + "247": intNumberTerms[247], + "248": intNumberTerms[248], + "249": intNumberTerms[249], + "250": intNumberTerms[250], + "251": intNumberTerms[251], + "252": intNumberTerms[252], + "253": intNumberTerms[253], + "254": intNumberTerms[254], + "255": intNumberTerms[255], + "256": intNumberTerms[256], + "257": intNumberTerms[257], + "258": intNumberTerms[258], + "259": intNumberTerms[259], + "260": intNumberTerms[260], + "261": intNumberTerms[261], + "262": intNumberTerms[262], + "263": intNumberTerms[263], + "264": intNumberTerms[264], + "265": intNumberTerms[265], + "266": intNumberTerms[266], + "267": intNumberTerms[267], + "268": intNumberTerms[268], + "269": intNumberTerms[269], + "270": intNumberTerms[270], + "271": intNumberTerms[271], + "272": intNumberTerms[272], + "273": intNumberTerms[273], + "274": intNumberTerms[274], + "275": intNumberTerms[275], + "276": intNumberTerms[276], + "277": intNumberTerms[277], + "278": intNumberTerms[278], + "279": intNumberTerms[279], + "280": intNumberTerms[280], + "281": intNumberTerms[281], + "282": intNumberTerms[282], + "283": intNumberTerms[283], + "284": intNumberTerms[284], + "285": intNumberTerms[285], + "286": intNumberTerms[286], + "287": intNumberTerms[287], + "288": intNumberTerms[288], + "289": intNumberTerms[289], + "290": intNumberTerms[290], + "291": intNumberTerms[291], + "292": intNumberTerms[292], + "293": intNumberTerms[293], + "294": intNumberTerms[294], + "295": intNumberTerms[295], + "296": intNumberTerms[296], + "297": intNumberTerms[297], + "298": intNumberTerms[298], + "299": intNumberTerms[299], + "300": intNumberTerms[300], + "301": intNumberTerms[301], + "302": intNumberTerms[302], + "303": intNumberTerms[303], + "304": intNumberTerms[304], + "305": intNumberTerms[305], + "306": intNumberTerms[306], + "307": intNumberTerms[307], + "308": intNumberTerms[308], + "309": intNumberTerms[309], + "310": intNumberTerms[310], + "311": intNumberTerms[311], + "312": intNumberTerms[312], + "313": intNumberTerms[313], + "314": intNumberTerms[314], + "315": intNumberTerms[315], + "316": intNumberTerms[316], + "317": intNumberTerms[317], + "318": intNumberTerms[318], + "319": intNumberTerms[319], + "320": intNumberTerms[320], + "321": intNumberTerms[321], + "322": intNumberTerms[322], + "323": intNumberTerms[323], + "324": intNumberTerms[324], + "325": intNumberTerms[325], + "326": intNumberTerms[326], + "327": intNumberTerms[327], + "328": intNumberTerms[328], + "329": intNumberTerms[329], + "330": intNumberTerms[330], + "331": intNumberTerms[331], + "332": intNumberTerms[332], + "333": intNumberTerms[333], + "334": intNumberTerms[334], + "335": intNumberTerms[335], + "336": intNumberTerms[336], + "337": intNumberTerms[337], + "338": intNumberTerms[338], + "339": intNumberTerms[339], + "340": intNumberTerms[340], + "341": intNumberTerms[341], + "342": intNumberTerms[342], + "343": intNumberTerms[343], + "344": intNumberTerms[344], + "345": intNumberTerms[345], + "346": intNumberTerms[346], + "347": intNumberTerms[347], + "348": intNumberTerms[348], + "349": intNumberTerms[349], + "350": intNumberTerms[350], + "351": intNumberTerms[351], + "352": intNumberTerms[352], + "353": intNumberTerms[353], + "354": intNumberTerms[354], + "355": intNumberTerms[355], + "356": intNumberTerms[356], + "357": intNumberTerms[357], + "358": intNumberTerms[358], + "359": intNumberTerms[359], + "360": intNumberTerms[360], + "361": intNumberTerms[361], + "362": intNumberTerms[362], + "363": intNumberTerms[363], + "364": intNumberTerms[364], + "365": intNumberTerms[365], + "366": intNumberTerms[366], + "367": intNumberTerms[367], + "368": intNumberTerms[368], + "369": intNumberTerms[369], + "370": intNumberTerms[370], + "371": intNumberTerms[371], + "372": intNumberTerms[372], + "373": intNumberTerms[373], + "374": intNumberTerms[374], + "375": intNumberTerms[375], + "376": intNumberTerms[376], + "377": intNumberTerms[377], + "378": intNumberTerms[378], + "379": intNumberTerms[379], + "380": intNumberTerms[380], + "381": intNumberTerms[381], + "382": intNumberTerms[382], + "383": intNumberTerms[383], + "384": intNumberTerms[384], + "385": intNumberTerms[385], + "386": intNumberTerms[386], + "387": intNumberTerms[387], + "388": intNumberTerms[388], + "389": intNumberTerms[389], + "390": intNumberTerms[390], + "391": intNumberTerms[391], + "392": intNumberTerms[392], + "393": intNumberTerms[393], + "394": intNumberTerms[394], + "395": intNumberTerms[395], + "396": intNumberTerms[396], + "397": intNumberTerms[397], + "398": intNumberTerms[398], + "399": intNumberTerms[399], + "400": intNumberTerms[400], + "401": intNumberTerms[401], + "402": intNumberTerms[402], + "403": intNumberTerms[403], + "404": intNumberTerms[404], + "405": intNumberTerms[405], + "406": intNumberTerms[406], + "407": intNumberTerms[407], + "408": intNumberTerms[408], + "409": intNumberTerms[409], + "410": intNumberTerms[410], + "411": intNumberTerms[411], + "412": intNumberTerms[412], + "413": intNumberTerms[413], + "414": intNumberTerms[414], + "415": intNumberTerms[415], + "416": intNumberTerms[416], + "417": intNumberTerms[417], + "418": intNumberTerms[418], + "419": intNumberTerms[419], + "420": intNumberTerms[420], + "421": intNumberTerms[421], + "422": intNumberTerms[422], + "423": intNumberTerms[423], + "424": intNumberTerms[424], + "425": intNumberTerms[425], + "426": intNumberTerms[426], + "427": intNumberTerms[427], + "428": intNumberTerms[428], + "429": intNumberTerms[429], + "430": intNumberTerms[430], + "431": intNumberTerms[431], + "432": intNumberTerms[432], + "433": intNumberTerms[433], + "434": intNumberTerms[434], + "435": intNumberTerms[435], + "436": intNumberTerms[436], + "437": intNumberTerms[437], + "438": intNumberTerms[438], + "439": intNumberTerms[439], + "440": intNumberTerms[440], + "441": intNumberTerms[441], + "442": intNumberTerms[442], + "443": intNumberTerms[443], + "444": intNumberTerms[444], + "445": intNumberTerms[445], + "446": intNumberTerms[446], + "447": intNumberTerms[447], + "448": intNumberTerms[448], + "449": intNumberTerms[449], + "450": intNumberTerms[450], + "451": intNumberTerms[451], + "452": intNumberTerms[452], + "453": intNumberTerms[453], + "454": intNumberTerms[454], + "455": intNumberTerms[455], + "456": intNumberTerms[456], + "457": intNumberTerms[457], + "458": intNumberTerms[458], + "459": intNumberTerms[459], + "460": intNumberTerms[460], + "461": intNumberTerms[461], + "462": intNumberTerms[462], + "463": intNumberTerms[463], + "464": intNumberTerms[464], + "465": intNumberTerms[465], + "466": intNumberTerms[466], + "467": intNumberTerms[467], + "468": intNumberTerms[468], + "469": intNumberTerms[469], + "470": intNumberTerms[470], + "471": intNumberTerms[471], + "472": intNumberTerms[472], + "473": intNumberTerms[473], + "474": intNumberTerms[474], + "475": intNumberTerms[475], + "476": intNumberTerms[476], + "477": intNumberTerms[477], + "478": intNumberTerms[478], + "479": intNumberTerms[479], + "480": intNumberTerms[480], + "481": intNumberTerms[481], + "482": intNumberTerms[482], + "483": intNumberTerms[483], + "484": intNumberTerms[484], + "485": intNumberTerms[485], + "486": intNumberTerms[486], + "487": intNumberTerms[487], + "488": intNumberTerms[488], + "489": intNumberTerms[489], + "490": intNumberTerms[490], + "491": intNumberTerms[491], + "492": intNumberTerms[492], + "493": intNumberTerms[493], + "494": intNumberTerms[494], + "495": intNumberTerms[495], + "496": intNumberTerms[496], + "497": intNumberTerms[497], + "498": intNumberTerms[498], + "499": intNumberTerms[499], + "500": intNumberTerms[500], + "501": intNumberTerms[501], + "502": intNumberTerms[502], + "503": intNumberTerms[503], + "504": intNumberTerms[504], + "505": intNumberTerms[505], + "506": intNumberTerms[506], + "507": intNumberTerms[507], + "508": intNumberTerms[508], + "509": intNumberTerms[509], + "510": intNumberTerms[510], + "511": intNumberTerms[511], + "512": intNumberTerms[512], +} + +var intNumberTerms = [...]*Term{ + {Value: Number("0")}, + {Value: Number("1")}, + {Value: Number("2")}, + {Value: Number("3")}, + {Value: Number("4")}, + {Value: Number("5")}, + {Value: Number("6")}, + {Value: Number("7")}, + {Value: Number("8")}, + {Value: Number("9")}, + {Value: Number("10")}, + {Value: Number("11")}, + {Value: Number("12")}, + {Value: Number("13")}, + {Value: Number("14")}, + {Value: Number("15")}, + {Value: Number("16")}, + {Value: Number("17")}, + {Value: Number("18")}, + {Value: Number("19")}, + {Value: Number("20")}, + {Value: Number("21")}, + {Value: Number("22")}, + {Value: Number("23")}, + {Value: Number("24")}, + {Value: Number("25")}, + {Value: Number("26")}, + {Value: Number("27")}, + {Value: Number("28")}, + {Value: Number("29")}, + {Value: Number("30")}, + {Value: Number("31")}, + {Value: Number("32")}, + {Value: Number("33")}, + {Value: Number("34")}, + {Value: Number("35")}, + {Value: Number("36")}, + {Value: Number("37")}, + {Value: Number("38")}, + {Value: Number("39")}, + {Value: Number("40")}, + {Value: Number("41")}, + {Value: Number("42")}, + {Value: Number("43")}, + {Value: Number("44")}, + {Value: Number("45")}, + {Value: Number("46")}, + {Value: Number("47")}, + {Value: Number("48")}, + {Value: Number("49")}, + {Value: Number("50")}, + {Value: Number("51")}, + {Value: Number("52")}, + {Value: Number("53")}, + {Value: Number("54")}, + {Value: Number("55")}, + {Value: Number("56")}, + {Value: Number("57")}, + {Value: Number("58")}, + {Value: Number("59")}, + {Value: Number("60")}, + {Value: Number("61")}, + {Value: Number("62")}, + {Value: Number("63")}, + {Value: Number("64")}, + {Value: Number("65")}, + {Value: Number("66")}, + {Value: Number("67")}, + {Value: Number("68")}, + {Value: Number("69")}, + {Value: Number("70")}, + {Value: Number("71")}, + {Value: Number("72")}, + {Value: Number("73")}, + {Value: Number("74")}, + {Value: Number("75")}, + {Value: Number("76")}, + {Value: Number("77")}, + {Value: Number("78")}, + {Value: Number("79")}, + {Value: Number("80")}, + {Value: Number("81")}, + {Value: Number("82")}, + {Value: Number("83")}, + {Value: Number("84")}, + {Value: Number("85")}, + {Value: Number("86")}, + {Value: Number("87")}, + {Value: Number("88")}, + {Value: Number("89")}, + {Value: Number("90")}, + {Value: Number("91")}, + {Value: Number("92")}, + {Value: Number("93")}, + {Value: Number("94")}, + {Value: Number("95")}, + {Value: Number("96")}, + {Value: Number("97")}, + {Value: Number("98")}, + {Value: Number("99")}, + {Value: Number("100")}, + {Value: Number("101")}, + {Value: Number("102")}, + {Value: Number("103")}, + {Value: Number("104")}, + {Value: Number("105")}, + {Value: Number("106")}, + {Value: Number("107")}, + {Value: Number("108")}, + {Value: Number("109")}, + {Value: Number("110")}, + {Value: Number("111")}, + {Value: Number("112")}, + {Value: Number("113")}, + {Value: Number("114")}, + {Value: Number("115")}, + {Value: Number("116")}, + {Value: Number("117")}, + {Value: Number("118")}, + {Value: Number("119")}, + {Value: Number("120")}, + {Value: Number("121")}, + {Value: Number("122")}, + {Value: Number("123")}, + {Value: Number("124")}, + {Value: Number("125")}, + {Value: Number("126")}, + {Value: Number("127")}, + {Value: Number("128")}, + {Value: Number("129")}, + {Value: Number("130")}, + {Value: Number("131")}, + {Value: Number("132")}, + {Value: Number("133")}, + {Value: Number("134")}, + {Value: Number("135")}, + {Value: Number("136")}, + {Value: Number("137")}, + {Value: Number("138")}, + {Value: Number("139")}, + {Value: Number("140")}, + {Value: Number("141")}, + {Value: Number("142")}, + {Value: Number("143")}, + {Value: Number("144")}, + {Value: Number("145")}, + {Value: Number("146")}, + {Value: Number("147")}, + {Value: Number("148")}, + {Value: Number("149")}, + {Value: Number("150")}, + {Value: Number("151")}, + {Value: Number("152")}, + {Value: Number("153")}, + {Value: Number("154")}, + {Value: Number("155")}, + {Value: Number("156")}, + {Value: Number("157")}, + {Value: Number("158")}, + {Value: Number("159")}, + {Value: Number("160")}, + {Value: Number("161")}, + {Value: Number("162")}, + {Value: Number("163")}, + {Value: Number("164")}, + {Value: Number("165")}, + {Value: Number("166")}, + {Value: Number("167")}, + {Value: Number("168")}, + {Value: Number("169")}, + {Value: Number("170")}, + {Value: Number("171")}, + {Value: Number("172")}, + {Value: Number("173")}, + {Value: Number("174")}, + {Value: Number("175")}, + {Value: Number("176")}, + {Value: Number("177")}, + {Value: Number("178")}, + {Value: Number("179")}, + {Value: Number("180")}, + {Value: Number("181")}, + {Value: Number("182")}, + {Value: Number("183")}, + {Value: Number("184")}, + {Value: Number("185")}, + {Value: Number("186")}, + {Value: Number("187")}, + {Value: Number("188")}, + {Value: Number("189")}, + {Value: Number("190")}, + {Value: Number("191")}, + {Value: Number("192")}, + {Value: Number("193")}, + {Value: Number("194")}, + {Value: Number("195")}, + {Value: Number("196")}, + {Value: Number("197")}, + {Value: Number("198")}, + {Value: Number("199")}, + {Value: Number("200")}, + {Value: Number("201")}, + {Value: Number("202")}, + {Value: Number("203")}, + {Value: Number("204")}, + {Value: Number("205")}, + {Value: Number("206")}, + {Value: Number("207")}, + {Value: Number("208")}, + {Value: Number("209")}, + {Value: Number("210")}, + {Value: Number("211")}, + {Value: Number("212")}, + {Value: Number("213")}, + {Value: Number("214")}, + {Value: Number("215")}, + {Value: Number("216")}, + {Value: Number("217")}, + {Value: Number("218")}, + {Value: Number("219")}, + {Value: Number("220")}, + {Value: Number("221")}, + {Value: Number("222")}, + {Value: Number("223")}, + {Value: Number("224")}, + {Value: Number("225")}, + {Value: Number("226")}, + {Value: Number("227")}, + {Value: Number("228")}, + {Value: Number("229")}, + {Value: Number("230")}, + {Value: Number("231")}, + {Value: Number("232")}, + {Value: Number("233")}, + {Value: Number("234")}, + {Value: Number("235")}, + {Value: Number("236")}, + {Value: Number("237")}, + {Value: Number("238")}, + {Value: Number("239")}, + {Value: Number("240")}, + {Value: Number("241")}, + {Value: Number("242")}, + {Value: Number("243")}, + {Value: Number("244")}, + {Value: Number("245")}, + {Value: Number("246")}, + {Value: Number("247")}, + {Value: Number("248")}, + {Value: Number("249")}, + {Value: Number("250")}, + {Value: Number("251")}, + {Value: Number("252")}, + {Value: Number("253")}, + {Value: Number("254")}, + {Value: Number("255")}, + {Value: Number("256")}, + {Value: Number("257")}, + {Value: Number("258")}, + {Value: Number("259")}, + {Value: Number("260")}, + {Value: Number("261")}, + {Value: Number("262")}, + {Value: Number("263")}, + {Value: Number("264")}, + {Value: Number("265")}, + {Value: Number("266")}, + {Value: Number("267")}, + {Value: Number("268")}, + {Value: Number("269")}, + {Value: Number("270")}, + {Value: Number("271")}, + {Value: Number("272")}, + {Value: Number("273")}, + {Value: Number("274")}, + {Value: Number("275")}, + {Value: Number("276")}, + {Value: Number("277")}, + {Value: Number("278")}, + {Value: Number("279")}, + {Value: Number("280")}, + {Value: Number("281")}, + {Value: Number("282")}, + {Value: Number("283")}, + {Value: Number("284")}, + {Value: Number("285")}, + {Value: Number("286")}, + {Value: Number("287")}, + {Value: Number("288")}, + {Value: Number("289")}, + {Value: Number("290")}, + {Value: Number("291")}, + {Value: Number("292")}, + {Value: Number("293")}, + {Value: Number("294")}, + {Value: Number("295")}, + {Value: Number("296")}, + {Value: Number("297")}, + {Value: Number("298")}, + {Value: Number("299")}, + {Value: Number("300")}, + {Value: Number("301")}, + {Value: Number("302")}, + {Value: Number("303")}, + {Value: Number("304")}, + {Value: Number("305")}, + {Value: Number("306")}, + {Value: Number("307")}, + {Value: Number("308")}, + {Value: Number("309")}, + {Value: Number("310")}, + {Value: Number("311")}, + {Value: Number("312")}, + {Value: Number("313")}, + {Value: Number("314")}, + {Value: Number("315")}, + {Value: Number("316")}, + {Value: Number("317")}, + {Value: Number("318")}, + {Value: Number("319")}, + {Value: Number("320")}, + {Value: Number("321")}, + {Value: Number("322")}, + {Value: Number("323")}, + {Value: Number("324")}, + {Value: Number("325")}, + {Value: Number("326")}, + {Value: Number("327")}, + {Value: Number("328")}, + {Value: Number("329")}, + {Value: Number("330")}, + {Value: Number("331")}, + {Value: Number("332")}, + {Value: Number("333")}, + {Value: Number("334")}, + {Value: Number("335")}, + {Value: Number("336")}, + {Value: Number("337")}, + {Value: Number("338")}, + {Value: Number("339")}, + {Value: Number("340")}, + {Value: Number("341")}, + {Value: Number("342")}, + {Value: Number("343")}, + {Value: Number("344")}, + {Value: Number("345")}, + {Value: Number("346")}, + {Value: Number("347")}, + {Value: Number("348")}, + {Value: Number("349")}, + {Value: Number("350")}, + {Value: Number("351")}, + {Value: Number("352")}, + {Value: Number("353")}, + {Value: Number("354")}, + {Value: Number("355")}, + {Value: Number("356")}, + {Value: Number("357")}, + {Value: Number("358")}, + {Value: Number("359")}, + {Value: Number("360")}, + {Value: Number("361")}, + {Value: Number("362")}, + {Value: Number("363")}, + {Value: Number("364")}, + {Value: Number("365")}, + {Value: Number("366")}, + {Value: Number("367")}, + {Value: Number("368")}, + {Value: Number("369")}, + {Value: Number("370")}, + {Value: Number("371")}, + {Value: Number("372")}, + {Value: Number("373")}, + {Value: Number("374")}, + {Value: Number("375")}, + {Value: Number("376")}, + {Value: Number("377")}, + {Value: Number("378")}, + {Value: Number("379")}, + {Value: Number("380")}, + {Value: Number("381")}, + {Value: Number("382")}, + {Value: Number("383")}, + {Value: Number("384")}, + {Value: Number("385")}, + {Value: Number("386")}, + {Value: Number("387")}, + {Value: Number("388")}, + {Value: Number("389")}, + {Value: Number("390")}, + {Value: Number("391")}, + {Value: Number("392")}, + {Value: Number("393")}, + {Value: Number("394")}, + {Value: Number("395")}, + {Value: Number("396")}, + {Value: Number("397")}, + {Value: Number("398")}, + {Value: Number("399")}, + {Value: Number("400")}, + {Value: Number("401")}, + {Value: Number("402")}, + {Value: Number("403")}, + {Value: Number("404")}, + {Value: Number("405")}, + {Value: Number("406")}, + {Value: Number("407")}, + {Value: Number("408")}, + {Value: Number("409")}, + {Value: Number("410")}, + {Value: Number("411")}, + {Value: Number("412")}, + {Value: Number("413")}, + {Value: Number("414")}, + {Value: Number("415")}, + {Value: Number("416")}, + {Value: Number("417")}, + {Value: Number("418")}, + {Value: Number("419")}, + {Value: Number("420")}, + {Value: Number("421")}, + {Value: Number("422")}, + {Value: Number("423")}, + {Value: Number("424")}, + {Value: Number("425")}, + {Value: Number("426")}, + {Value: Number("427")}, + {Value: Number("428")}, + {Value: Number("429")}, + {Value: Number("430")}, + {Value: Number("431")}, + {Value: Number("432")}, + {Value: Number("433")}, + {Value: Number("434")}, + {Value: Number("435")}, + {Value: Number("436")}, + {Value: Number("437")}, + {Value: Number("438")}, + {Value: Number("439")}, + {Value: Number("440")}, + {Value: Number("441")}, + {Value: Number("442")}, + {Value: Number("443")}, + {Value: Number("444")}, + {Value: Number("445")}, + {Value: Number("446")}, + {Value: Number("447")}, + {Value: Number("448")}, + {Value: Number("449")}, + {Value: Number("450")}, + {Value: Number("451")}, + {Value: Number("452")}, + {Value: Number("453")}, + {Value: Number("454")}, + {Value: Number("455")}, + {Value: Number("456")}, + {Value: Number("457")}, + {Value: Number("458")}, + {Value: Number("459")}, + {Value: Number("460")}, + {Value: Number("461")}, + {Value: Number("462")}, + {Value: Number("463")}, + {Value: Number("464")}, + {Value: Number("465")}, + {Value: Number("466")}, + {Value: Number("467")}, + {Value: Number("468")}, + {Value: Number("469")}, + {Value: Number("470")}, + {Value: Number("471")}, + {Value: Number("472")}, + {Value: Number("473")}, + {Value: Number("474")}, + {Value: Number("475")}, + {Value: Number("476")}, + {Value: Number("477")}, + {Value: Number("478")}, + {Value: Number("479")}, + {Value: Number("480")}, + {Value: Number("481")}, + {Value: Number("482")}, + {Value: Number("483")}, + {Value: Number("484")}, + {Value: Number("485")}, + {Value: Number("486")}, + {Value: Number("487")}, + {Value: Number("488")}, + {Value: Number("489")}, + {Value: Number("490")}, + {Value: Number("491")}, + {Value: Number("492")}, + {Value: Number("493")}, + {Value: Number("494")}, + {Value: Number("495")}, + {Value: Number("496")}, + {Value: Number("497")}, + {Value: Number("498")}, + {Value: Number("499")}, + {Value: Number("500")}, + {Value: Number("501")}, + {Value: Number("502")}, + {Value: Number("503")}, + {Value: Number("504")}, + {Value: Number("505")}, + {Value: Number("506")}, + {Value: Number("507")}, + {Value: Number("508")}, + {Value: Number("509")}, + {Value: Number("510")}, + {Value: Number("511")}, + {Value: Number("512")}, +} + +var InternedEmptyString = StringTerm("") + +var InternedEmptyObject = ObjectTerm() diff --git a/vendor/github.com/open-policy-agent/opa/v1/ast/json/json.go b/vendor/github.com/open-policy-agent/opa/v1/ast/json/json.go new file mode 100644 index 0000000000..9081fe7039 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/json/json.go @@ -0,0 +1,106 @@ +// Copyright 2023 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// This package provides options for JSON marshalling of AST nodes, and location +// data in particular. Since location data occupies a significant portion of the +// AST when included, it is excluded by default. The options provided here allow +// changing that behavior — either for all nodes or for specific types. Since +// JSONMarshaller implementations have access only to the node being marshaled, +// our options are to either attach these settings to *all* nodes in the AST, or +// to provide them via global state. The former is perhaps a little more elegant, +// and is what we went with initially. The cost of attaching these settings to +// every node however turned out to be non-negligible, and given that the number +// of users who have an interest in AST serialization are likely to be few, we +// have since switched to using global state, as provided here. Note that this +// is mostly to provide an equivalent feature to what we had before, should +// anyone depend on that. Users who need fine-grained control over AST +// serialization are recommended to use external libraries for that purpose, +// such as `github.com/json-iterator/go`. +package json + +import "sync" + +// Options defines the options for JSON operations, +// currently only marshaling can be configured +type Options struct { + MarshalOptions MarshalOptions +} + +// MarshalOptions defines the options for JSON marshaling, +// currently only toggling the marshaling of location information is supported +type MarshalOptions struct { + // IncludeLocation toggles the marshaling of location information + IncludeLocation NodeToggle + // IncludeLocationText additionally/optionally includes the text of the location + IncludeLocationText bool + // ExcludeLocationFile additionally/optionally excludes the file of the location + // Note that this is inverted (i.e. not "include" as the default needs to remain false) + ExcludeLocationFile bool +} + +// NodeToggle is a generic struct to allow the toggling of +// settings for different ast node types +type NodeToggle struct { + Term bool + Package bool + Comment bool + Import bool + Rule bool + Head bool + Expr bool + SomeDecl bool + Every bool + With bool + Annotations bool + AnnotationsRef bool +} + +// configuredJSONOptions synchronizes access to the global JSON options +type configuredJSONOptions struct { + options Options + lock sync.RWMutex +} + +var options = &configuredJSONOptions{ + options: Defaults(), +} + +// SetOptions sets the global options for marshalling AST nodes to JSON +func SetOptions(opts Options) { + options.lock.Lock() + defer options.lock.Unlock() + options.options = opts +} + +// GetOptions returns (a copy of) the global options for marshalling AST nodes to JSON +func GetOptions() Options { + options.lock.RLock() + defer options.lock.RUnlock() + return options.options +} + +// Defaults returns the default JSON options, which is to exclude location +// information in serialized JSON AST. +func Defaults() Options { + return Options{ + MarshalOptions: MarshalOptions{ + IncludeLocation: NodeToggle{ + Term: false, + Package: false, + Comment: false, + Import: false, + Rule: false, + Head: false, + Expr: false, + SomeDecl: false, + Every: false, + With: false, + Annotations: false, + AnnotationsRef: false, + }, + IncludeLocationText: false, + ExcludeLocationFile: false, + }, + } +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/location/location.go b/vendor/github.com/open-policy-agent/opa/v1/ast/location/location.go similarity index 91% rename from vendor/github.com/open-policy-agent/opa/ast/location/location.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/location/location.go index 92226df3f0..716aad6930 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/location/location.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/location/location.go @@ -7,7 +7,7 @@ import ( "errors" "fmt" - astJSON "github.com/open-policy-agent/opa/ast/json" + astJSON "github.com/open-policy-agent/opa/v1/ast/json" ) // Location records a position in source code @@ -18,9 +18,6 @@ type Location struct { Col int `json:"col"` // The column in the row. Offset int `json:"-"` // The byte offset for the location in the source. - // JSONOptions specifies options for marshaling and unmarshalling of locations - JSONOptions astJSON.Options - Tabs []int `json:"-"` // The column offsets of tabs in the source. } @@ -98,7 +95,8 @@ func (loc *Location) Compare(other *Location) int { func (loc *Location) MarshalJSON() ([]byte, error) { // structs are used here to preserve the field ordering of the original Location struct - if loc.JSONOptions.MarshalOptions.ExcludeLocationFile { + jsonOptions := astJSON.GetOptions().MarshalOptions + if jsonOptions.ExcludeLocationFile { data := struct { Row int `json:"row"` Col int `json:"col"` @@ -108,7 +106,7 @@ func (loc *Location) MarshalJSON() ([]byte, error) { Col: loc.Col, } - if loc.JSONOptions.MarshalOptions.IncludeLocationText { + if jsonOptions.IncludeLocationText { data.Text = loc.Text } @@ -126,7 +124,7 @@ func (loc *Location) MarshalJSON() ([]byte, error) { File: loc.File, } - if loc.JSONOptions.MarshalOptions.IncludeLocationText { + if jsonOptions.IncludeLocationText { data.Text = loc.Text } diff --git a/vendor/github.com/open-policy-agent/opa/ast/map.go b/vendor/github.com/open-policy-agent/opa/v1/ast/map.go similarity index 96% rename from vendor/github.com/open-policy-agent/opa/ast/map.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/map.go index b0cc9eb60f..5a64f32505 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/map.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/map.go @@ -7,7 +7,7 @@ package ast import ( "encoding/json" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/util" ) // ValueMap represents a key/value map between AST term values. Any type of term @@ -31,7 +31,7 @@ func (vs *ValueMap) MarshalJSON() ([]byte, error) { vs.Iter(func(k Value, v Value) bool { tmp = append(tmp, map[string]interface{}{ "name": k.String(), - "type": TypeName(v), + "type": ValueName(v), "value": v, }) return false @@ -55,7 +55,7 @@ func (vs *ValueMap) Equal(other *ValueMap) bool { return other == nil || other.Len() == 0 } if other == nil { - return vs == nil || vs.Len() == 0 + return vs.Len() == 0 } return vs.hashMap.Equal(other.hashMap) } diff --git a/vendor/github.com/open-policy-agent/opa/ast/parser.go b/vendor/github.com/open-policy-agent/opa/v1/ast/parser.go similarity index 92% rename from vendor/github.com/open-policy-agent/opa/ast/parser.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/parser.go index 0ad15f631b..2054141d30 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/parser.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/parser.go @@ -17,12 +17,12 @@ import ( "strings" "unicode/utf8" - "gopkg.in/yaml.v2" + "gopkg.in/yaml.v3" - "github.com/open-policy-agent/opa/ast/internal/scanner" - "github.com/open-policy-agent/opa/ast/internal/tokens" - astJSON "github.com/open-policy-agent/opa/ast/json" - "github.com/open-policy-agent/opa/ast/location" + "github.com/open-policy-agent/opa/v1/ast/internal/scanner" + "github.com/open-policy-agent/opa/v1/ast/internal/tokens" + astJSON "github.com/open-policy-agent/opa/v1/ast/json" + "github.com/open-policy-agent/opa/v1/ast/location" ) var RegoV1CompatibleRef = Ref{VarTerm("rego"), StringTerm("v1")} @@ -30,9 +30,12 @@ var RegoV1CompatibleRef = Ref{VarTerm("rego"), StringTerm("v1")} // RegoVersion defines the Rego syntax requirements for a module. type RegoVersion int +const DefaultRegoVersion = RegoV1 + const ( + RegoUndefined RegoVersion = iota // RegoV0 is the default, original Rego syntax. - RegoV0 RegoVersion = iota + RegoV0 // RegoV0CompatV1 requires modules to comply with both the RegoV0 and RegoV1 syntax (as when 'rego.v1' is imported in a module). // Shortly, RegoV1 compatibility is required, but 'rego.v1' or 'future.keywords' must also be imported. RegoV0CompatV1 @@ -147,15 +150,16 @@ type ParserOptions struct { AllFutureKeywords bool FutureKeywords []string SkipRules bool - JSONOptions *astJSON.Options // RegoVersion is the version of Rego to parse for. RegoVersion RegoVersion unreleasedKeywords bool // TODO(sr): cleanup } // EffectiveRegoVersion returns the effective RegoVersion to use for parsing. -// Deprecated: Use RegoVersion instead. func (po *ParserOptions) EffectiveRegoVersion() RegoVersion { + if po.RegoVersion == RegoUndefined { + return DefaultRegoVersion + } return po.RegoVersion } @@ -232,10 +236,11 @@ func (p *Parser) WithSkipRules(skip bool) *Parser { return p } -// WithJSONOptions sets the Options which will be set on nodes to configure -// their JSON marshaling behavior. -func (p *Parser) WithJSONOptions(jsonOptions *astJSON.Options) *Parser { - p.po.JSONOptions = jsonOptions +// WithJSONOptions sets the JSON options on the parser (now a no-op). +// +// Deprecated: Use SetOptions in the json package instead, where a longer description +// of why this is deprecated also can be found. +func (p *Parser) WithJSONOptions(_ *astJSON.Options) *Parser { return p } @@ -278,7 +283,7 @@ func (p *Parser) parsedTermCachePush(t *Term, s0 *state) { func (p *Parser) futureParser() *Parser { q := *p q.s = p.save() - q.s.s = p.s.s.WithKeywords(futureKeywords) + q.s.s = p.s.s.WithKeywords(allFutureKeywords) q.cache = parsedTermCache{} return &q } @@ -296,7 +301,7 @@ func (p *Parser) presentParser() (*Parser, map[string]tokens.Token) { var cpy map[string]tokens.Token q := *p q.s = p.save() - q.s.s, cpy = p.s.s.WithoutKeywords(futureKeywords) + q.s.s, cpy = p.s.s.WithoutKeywords(allFutureKeywords) q.cache = parsedTermCache{} return &q, cpy } @@ -307,20 +312,60 @@ func (p *Parser) presentParser() (*Parser, map[string]tokens.Token) { func (p *Parser) Parse() ([]Statement, []*Comment, Errors) { if p.po.Capabilities == nil { - p.po.Capabilities = CapabilitiesForThisVersion() + p.po.Capabilities = CapabilitiesForThisVersion(CapabilitiesRegoVersion(p.po.RegoVersion)) } allowedFutureKeywords := map[string]tokens.Token{} - if p.po.RegoVersion == RegoV1 { - // RegoV1 includes all future keywords in the default language definition - for k, v := range futureKeywords { + if p.po.EffectiveRegoVersion() == RegoV1 { + if !p.po.Capabilities.ContainsFeature(FeatureRegoV1) { + return nil, nil, Errors{ + &Error{ + Code: ParseErr, + Message: "illegal capabilities: rego_v1 feature required for parsing v1 Rego", + Location: nil, + }, + } + } + + // rego-v1 includes all v0 future keywords in the default language definition + for k, v := range futureKeywordsV0 { allowedFutureKeywords[k] = v } + + for _, kw := range p.po.Capabilities.FutureKeywords { + if tok, ok := futureKeywords[kw]; ok { + allowedFutureKeywords[kw] = tok + } else { + // For sake of error reporting, we still need to check that keywords in capabilities are known in v0 + if _, ok := futureKeywordsV0[kw]; !ok { + return nil, nil, Errors{ + &Error{ + Code: ParseErr, + Message: fmt.Sprintf("illegal capabilities: unknown keyword: %v", kw), + Location: nil, + }, + } + } + } + } + + // Check that explicitly requested future keywords are known. + for _, kw := range p.po.FutureKeywords { + if _, ok := allowedFutureKeywords[kw]; !ok { + return nil, nil, Errors{ + &Error{ + Code: ParseErr, + Message: fmt.Sprintf("unknown future keyword: %v", kw), + Location: nil, + }, + } + } + } } else { for _, kw := range p.po.Capabilities.FutureKeywords { var ok bool - allowedFutureKeywords[kw], ok = futureKeywords[kw] + allowedFutureKeywords[kw], ok = allFutureKeywords[kw] if !ok { return nil, nil, Errors{ &Error{ @@ -331,6 +376,13 @@ func (p *Parser) Parse() ([]Statement, []*Comment, Errors) { } } } + + if p.po.Capabilities.ContainsFeature(FeatureRegoV1) { + // rego-v1 includes all v0 future keywords in the default language definition + for k, v := range futureKeywordsV0 { + allowedFutureKeywords[k] = v + } + } } var err error @@ -346,7 +398,7 @@ func (p *Parser) Parse() ([]Statement, []*Comment, Errors) { } selected := map[string]tokens.Token{} - if p.po.AllFutureKeywords || p.po.RegoVersion == RegoV1 { + if p.po.AllFutureKeywords || p.po.EffectiveRegoVersion() == RegoV1 { for kw, tok := range allowedFutureKeywords { selected[kw] = tok } @@ -367,7 +419,7 @@ func (p *Parser) Parse() ([]Statement, []*Comment, Errors) { } p.s.s = p.s.s.WithKeywords(selected) - if p.po.RegoVersion == RegoV1 { + if p.po.EffectiveRegoVersion() == RegoV1 { for kw, tok := range allowedFutureKeywords { p.s.s.AddKeyword(kw, tok) } @@ -442,19 +494,6 @@ func (p *Parser) Parse() ([]Statement, []*Comment, Errors) { stmts = p.parseAnnotations(stmts) } - if p.po.JSONOptions != nil { - for i := range stmts { - vis := NewGenericVisitor(func(x interface{}) bool { - if x, ok := x.(customJSON); ok { - x.setJSONOptions(*p.po.JSONOptions) - } - return false - }) - - vis.Walk(stmts[i]) - } - } - return stmts, p.s.comments, p.s.errors } @@ -539,7 +578,7 @@ func (p *Parser) parsePackage() *Package { pkg.Path[0] = DefaultRootDocument.Copy().SetLocation(v[0].Location) first, ok := v[0].Value.(Var) if !ok { - p.errorf(v[0].Location, "unexpected %v token: expecting var", TypeName(v[0].Value)) + p.errorf(v[0].Location, "unexpected %v token: expecting var", ValueName(v[0].Value)) return nil } pkg.Path[1] = StringTerm(string(first)).SetLocation(v[0].Location) @@ -548,7 +587,7 @@ func (p *Parser) parsePackage() *Package { case String: pkg.Path[i] = v[i-1] default: - p.errorf(v[i-1].Location, "unexpected %v token: expecting string", TypeName(v[i-1].Value)) + p.errorf(v[i-1].Location, "unexpected %v token: expecting string", ValueName(v[i-1].Value)) return nil } } @@ -591,7 +630,7 @@ func (p *Parser) parseImport() *Import { case Ref: for i := 1; i < len(v); i++ { if _, ok := v[i].Value.(String); !ok { - p.errorf(v[i].Location, "unexpected %v token: expecting string", TypeName(v[i].Value)) + p.errorf(v[i].Location, "unexpected %v token: expecting string", ValueName(v[i].Value)) return nil } } @@ -686,6 +725,10 @@ func (p *Parser) parseRules() []*Rule { // p[x] if ... becomes a single-value rule p[x] if hasIf && !usesContains && len(rule.Head.Ref()) == 2 { + if !rule.Head.Ref()[1].IsGround() && len(rule.Head.Args) == 0 { + rule.Head.Key = rule.Head.Ref()[1] + } + if rule.Head.Value == nil { rule.Head.generatedValue = true rule.Head.Value = BooleanTerm(true).SetLocation(rule.Head.Location) @@ -749,6 +792,8 @@ func (p *Parser) parseRules() []*Rule { case usesContains: rule.Body = NewBody(NewExpr(BooleanTerm(true).SetLocation(rule.Location)).SetLocation(rule.Location)) rule.generatedBody = true + rule.Location = rule.Head.Location + return []*Rule{&rule} default: @@ -913,9 +958,8 @@ func (p *Parser) parseHead(defaultRule bool) (*Head, bool) { switch x := ref.Value.(type) { case Var: - // Modify the code to add the location to the head ref - // and set the head ref's jsonOptions. - head = VarHead(x, ref.Location, p.po.JSONOptions) + // TODO + head = VarHead(x, ref.Location, nil) case Ref: head = RefHead(x) case Call: @@ -1320,6 +1364,11 @@ func (p *Parser) parseTermInfixCallInList() *Term { return p.parseTermIn(nil, false, p.s.loc.Offset) } +// use static references to avoid allocations, and +// copy them to the call term only when needed +var memberWithKeyRef = MemberWithKey.Ref() +var memberRef = Member.Ref() + func (p *Parser) parseTermIn(lhs *Term, keyVal bool, offset int) *Term { // NOTE(sr): `in` is a bit special: besides `lhs in rhs`, it also // supports `key, val in rhs`, so it can have an optional second lhs. @@ -1332,7 +1381,8 @@ func (p *Parser) parseTermIn(lhs *Term, keyVal bool, offset int) *Term { s := p.save() p.scan() if mhs := p.parseTermRelation(nil, offset); mhs != nil { - if op := p.parseTermOpName(MemberWithKey.Ref(), tokens.In); op != nil { + + if op := p.parseTermOpName(memberWithKeyRef, tokens.In); op != nil { if rhs := p.parseTermRelation(nil, p.s.loc.Offset); rhs != nil { call := p.setLoc(CallTerm(op, lhs, mhs, rhs), lhs.Location, offset, p.s.lastEnd) switch p.s.tok { @@ -1346,7 +1396,7 @@ func (p *Parser) parseTermIn(lhs *Term, keyVal bool, offset int) *Term { } p.restore(s) } - if op := p.parseTermOpName(Member.Ref(), tokens.In); op != nil { + if op := p.parseTermOpName(memberRef, tokens.In); op != nil { if rhs := p.parseTermRelation(nil, p.s.loc.Offset); rhs != nil { call := p.setLoc(CallTerm(op, lhs, rhs), lhs.Location, offset, p.s.lastEnd) switch p.s.tok { @@ -1583,8 +1633,7 @@ func (p *Parser) parseNumber() *Term { // Note: Use the original string, do *not* round trip from // the big.Float as it can cause precision loss. - r := NumberTerm(json.Number(s)).SetLocation(loc) - return r + return NumberTerm(json.Number(s)).SetLocation(loc) } func (p *Parser) parseString() *Term { @@ -1654,7 +1703,7 @@ func (p *Parser) parseRef(head *Term, offset int) (term *Term) { case Var, *Array, Object, Set, *ArrayComprehension, *ObjectComprehension, *SetComprehension, Call: // ok default: - p.errorf(loc, "illegal ref (head cannot be %v)", TypeName(h)) + p.errorf(loc, "illegal ref (head cannot be %v)", ValueName(h)) } ref := []*Term{head} @@ -2022,10 +2071,11 @@ func (p *Parser) parseTermOp(values ...tokens.Token) *Term { func (p *Parser) parseTermOpName(ref Ref, values ...tokens.Token) *Term { for i := range values { if p.s.tok == values[i] { - for _, r := range ref { + cp := ref.Copy() + for _, r := range cp { r.SetLocation(p.s.Loc()) } - t := RefTerm(ref...) + t := RefTerm(cp...) t.SetLocation(p.s.Loc()) p.scan() return t @@ -2055,7 +2105,7 @@ func (p *Parser) genwildcard() string { } func (p *Parser) error(loc *location.Location, reason string) { - p.errorf(loc, reason) + p.errorf(loc, reason) //nolint:govet } func (p *Parser) errorf(loc *location.Location, f string, a ...interface{}) { @@ -2103,8 +2153,7 @@ func (p *Parser) illegal(note string, a ...interface{}) { tokType := "token" if tokens.IsKeyword(p.s.tok) { tokType = "keyword" - } - if _, ok := futureKeywords[p.s.tok.String()]; ok { + } else if _, ok := allFutureKeywords[p.s.tok.String()]; ok { tokType = "keyword" } @@ -2255,7 +2304,7 @@ func (p *Parser) validateDefaultRuleArgs(rule *Rule) bool { switch v := x.Value.(type) { case Var: // do nothing default: - p.error(rule.Loc(), fmt.Sprintf("illegal default rule (arguments cannot contain %v)", TypeName(v))) + p.error(rule.Loc(), fmt.Sprintf("illegal default rule (arguments cannot contain %v)", ValueName(v))) valid = false return true } @@ -2278,12 +2327,10 @@ type rawAnnotation struct { Organizations []string `yaml:"organizations"` RelatedResources []interface{} `yaml:"related_resources"` Authors []interface{} `yaml:"authors"` - Schemas []rawSchemaAnnotation `yaml:"schemas"` + Schemas []map[string]any `yaml:"schemas"` Custom map[string]interface{} `yaml:"custom"` } -type rawSchemaAnnotation map[string]interface{} - type metadataParser struct { buf *bytes.Buffer comments []*Comment @@ -2314,9 +2361,8 @@ func (b *metadataParser) Parse() (*Annotations, error) { var comment *Comment match := yamlLineErrRegex.FindStringSubmatch(err.Error()) if len(match) == 2 { - n, err2 := strconv.Atoi(match[1]) + index, err2 := strconv.Atoi(match[1]) if err2 == nil { - index := n - 1 // line numbering is 1-based so subtract one from row if index >= len(b.comments) { comment = b.comments[len(b.comments)-1] } else { @@ -2366,7 +2412,7 @@ func (b *metadataParser) Parse() (*Annotations, error) { if err != nil { return nil, err } - case map[interface{}]interface{}: + case map[string]any: w, err := convertYAMLMapKeyTypes(v, nil) if err != nil { return nil, fmt.Errorf("invalid schema definition: %w", err) @@ -2415,8 +2461,9 @@ func (b *metadataParser) Parse() (*Annotations, error) { return &result, nil } -// augmentYamlError augments a YAML error with hints intended to help the user figure out the cause of an otherwise cryptic error. -// These are hints, instead of proper errors, because they are educated guesses, and aren't guaranteed to be correct. +// augmentYamlError augments a YAML error with hints intended to help the user figure out the cause of an otherwise +// cryptic error. These are hints, instead of proper errors, because they are educated guesses, and aren't guaranteed +// to be correct. func augmentYamlError(err error, comments []*Comment) error { // Adding hints for when key/value ':' separator isn't suffixed with a legal YAML space symbol for _, comment := range comments { @@ -2570,11 +2617,11 @@ func parseAuthorString(s string) (*AuthorAnnotation, error) { return &AuthorAnnotation{Name: name, Email: email}, nil } -func convertYAMLMapKeyTypes(x interface{}, path []string) (interface{}, error) { +func convertYAMLMapKeyTypes(x any, path []string) (any, error) { var err error switch x := x.(type) { - case map[interface{}]interface{}: - result := make(map[string]interface{}, len(x)) + case map[any]any: + result := make(map[string]any, len(x)) for k, v := range x { str, ok := k.(string) if !ok { @@ -2586,7 +2633,7 @@ func convertYAMLMapKeyTypes(x interface{}, path []string) (interface{}, error) { } } return result, nil - case []interface{}: + case []any: for i := range x { x[i], err = convertYAMLMapKeyTypes(x[i], append(path, fmt.Sprintf("%d", i))) if err != nil { @@ -2601,16 +2648,34 @@ func convertYAMLMapKeyTypes(x interface{}, path []string) (interface{}, error) { // futureKeywords is the source of truth for future keywords that will // eventually become standard keywords inside of Rego. -var futureKeywords = map[string]tokens.Token{ +var futureKeywords = map[string]tokens.Token{} + +// futureKeywordsV0 is the source of truth for future keywords that were +// not yet a standard part of Rego in v0, and required importing. +var futureKeywordsV0 = map[string]tokens.Token{ "in": tokens.In, "every": tokens.Every, "contains": tokens.Contains, "if": tokens.If, } +var allFutureKeywords map[string]tokens.Token + func IsFutureKeyword(s string) bool { - _, ok := futureKeywords[s] - return ok + return IsFutureKeywordForRegoVersion(s, RegoV1) +} + +func IsFutureKeywordForRegoVersion(s string, v RegoVersion) bool { + var yes bool + + switch v { + case RegoV0, RegoV0CompatV1: + _, yes = futureKeywordsV0[s] + case RegoV1: + _, yes = futureKeywords[s] + } + + return yes } func (p *Parser) futureImport(imp *Import, allowedFutureKeywords map[string]tokens.Token) { @@ -2626,11 +2691,6 @@ func (p *Parser) futureImport(imp *Import, allowedFutureKeywords map[string]toke return } - if p.s.s.RegoV1Compatible() { - p.errorf(imp.Path.Location, "the `%s` import implies `future.keywords`, these are therefore mutually exclusive", RegoV1CompatibleRef) - return - } - kwds := make([]string, 0, len(allowedFutureKeywords)) for k := range allowedFutureKeywords { kwds = append(kwds, k) @@ -2660,42 +2720,47 @@ func (p *Parser) futureImport(imp *Import, allowedFutureKeywords map[string]toke } func (p *Parser) regoV1Import(imp *Import) { - if !p.po.Capabilities.ContainsFeature(FeatureRegoV1Import) { + if !p.po.Capabilities.ContainsFeature(FeatureRegoV1Import) && !p.po.Capabilities.ContainsFeature(FeatureRegoV1) { p.errorf(imp.Path.Location, "invalid import, `%s` is not supported by current capabilities", RegoV1CompatibleRef) return } - if p.po.RegoVersion == RegoV1 { - // We're parsing for Rego v1, where the 'rego.v1' import is a no-op. - return - } - path := imp.Path.Value.(Ref) + // v1 is only valid option if len(path) == 1 || !path[1].Equal(RegoV1CompatibleRef[1]) || len(path) > 2 { p.errorf(imp.Path.Location, "invalid import `%s`, must be `%s`", path, RegoV1CompatibleRef) return } + if p.po.EffectiveRegoVersion() == RegoV1 { + // We're parsing for Rego v1, where the 'rego.v1' import is a no-op. + return + } + if imp.Alias != "" { p.errorf(imp.Path.Location, "`rego` imports cannot be aliased") return } // import all future keywords with the rego.v1 import - kwds := make([]string, 0, len(futureKeywords)) - for k := range futureKeywords { + kwds := make([]string, 0, len(futureKeywordsV0)) + for k := range futureKeywordsV0 { kwds = append(kwds, k) } - if p.s.s.HasKeyword(futureKeywords) && !p.s.s.RegoV1Compatible() { - // We have imported future keywords, but they didn't come from another `rego.v1` import. - p.errorf(imp.Path.Location, "the `%s` import implies `future.keywords`, these are therefore mutually exclusive", RegoV1CompatibleRef) - return - } - p.s.s.SetRegoV1Compatible() for _, kw := range kwds { - p.s.s.AddKeyword(kw, futureKeywords[kw]) + p.s.s.AddKeyword(kw, futureKeywordsV0[kw]) + } +} + +func init() { + allFutureKeywords = map[string]tokens.Token{} + for k, v := range futureKeywords { + allFutureKeywords[k] = v + } + for k, v := range futureKeywordsV0 { + allFutureKeywords[k] = v } } diff --git a/vendor/github.com/open-policy-agent/opa/ast/parser_ext.go b/vendor/github.com/open-policy-agent/opa/v1/ast/parser_ext.go similarity index 90% rename from vendor/github.com/open-policy-agent/opa/ast/parser_ext.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/parser_ext.go index afaa1d890c..9712cb611a 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/parser_ext.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/parser_ext.go @@ -17,8 +17,7 @@ import ( "strings" "unicode" - "github.com/open-policy-agent/opa/ast/internal/tokens" - astJSON "github.com/open-policy-agent/opa/ast/json" + "github.com/open-policy-agent/opa/v1/ast/internal/tokens" ) // MustParseBody returns a parsed body. @@ -103,6 +102,14 @@ func MustParseStatement(input string) Statement { return parsed } +func MustParseStatementWithOpts(input string, popts ParserOptions) Statement { + parsed, err := ParseStatementWithOpts(input, popts) + if err != nil { + panic(err) + } + return parsed +} + // MustParseRef returns a parsed reference. // If an error occurs during parsing, panic. func MustParseRef(input string) Ref { @@ -123,6 +130,16 @@ func MustParseRule(input string) *Rule { return parsed } +// MustParseRuleWithOpts returns a parsed rule. +// If an error occurs during parsing, panic. +func MustParseRuleWithOpts(input string, opts ParserOptions) *Rule { + parsed, err := ParseRuleWithOpts(input, opts) + if err != nil { + panic(err) + } + return parsed +} + // MustParseTerm returns a parsed term. // If an error occurs during parsing, panic. func MustParseTerm(input string) *Term { @@ -168,7 +185,7 @@ func ParseRuleFromExpr(module *Module, expr *Expr) (*Rule, error) { } return ParsePartialSetDocRuleFromTerm(module, term) default: - return nil, fmt.Errorf("%v cannot be used for rule name", TypeName(v)) + return nil, fmt.Errorf("%v cannot be used for rule name", ValueName(v)) } } @@ -248,8 +265,7 @@ func ParseCompleteDocRuleFromEqExpr(module *Module, lhs, rhs *Term) (*Rule, erro if v, ok := lhs.Value.(Var); ok { // Modify the code to add the location to the head ref - // and set the head ref's jsonOptions. - head = VarHead(v, lhs.Location, &lhs.jsonOptions) + head = VarHead(v, lhs.Location, nil) } else if r, ok := lhs.Value.(Ref); ok { // groundness ? if _, ok := r[0].Value.(Var); !ok { return nil, fmt.Errorf("invalid rule head: %v", r) @@ -259,28 +275,26 @@ func ParseCompleteDocRuleFromEqExpr(module *Module, lhs, rhs *Term) (*Rule, erro return nil, fmt.Errorf("ref not ground") } } else { - return nil, fmt.Errorf("%v cannot be used for rule name", TypeName(lhs.Value)) + return nil, fmt.Errorf("%v cannot be used for rule name", ValueName(lhs.Value)) } head.Value = rhs head.Location = lhs.Location - head.setJSONOptions(lhs.jsonOptions) body := NewBody(NewExpr(BooleanTerm(true).SetLocation(rhs.Location)).SetLocation(rhs.Location)) - setJSONOptions(body, &rhs.jsonOptions) return &Rule{ - Location: lhs.Location, - Head: head, - Body: body, - Module: module, - jsonOptions: lhs.jsonOptions, + Location: lhs.Location, + Head: head, + Body: body, + Module: module, + generatedBody: true, }, nil } func ParseCompleteDocRuleWithDotsFromTerm(module *Module, term *Term) (*Rule, error) { ref, ok := term.Value.(Ref) if !ok { - return nil, fmt.Errorf("%v cannot be used for rule name", TypeName(term.Value)) + return nil, fmt.Errorf("%v cannot be used for rule name", ValueName(term.Value)) } if _, ok := ref[0].Value.(Var); !ok { @@ -289,18 +303,14 @@ func ParseCompleteDocRuleWithDotsFromTerm(module *Module, term *Term) (*Rule, er head := RefHead(ref, BooleanTerm(true).SetLocation(term.Location)) head.generatedValue = true head.Location = term.Location - head.jsonOptions = term.jsonOptions body := NewBody(NewExpr(BooleanTerm(true).SetLocation(term.Location)).SetLocation(term.Location)) - setJSONOptions(body, &term.jsonOptions) return &Rule{ Location: term.Location, Head: head, Body: body, Module: module, - - jsonOptions: term.jsonOptions, }, nil } @@ -309,7 +319,7 @@ func ParseCompleteDocRuleWithDotsFromTerm(module *Module, term *Term) (*Rule, er func ParsePartialObjectDocRuleFromEqExpr(module *Module, lhs, rhs *Term) (*Rule, error) { ref, ok := lhs.Value.(Ref) if !ok { - return nil, fmt.Errorf("%v cannot be used as rule name", TypeName(lhs.Value)) + return nil, fmt.Errorf("%v cannot be used as rule name", ValueName(lhs.Value)) } if _, ok := ref[0].Value.(Var); !ok { @@ -322,17 +332,14 @@ func ParsePartialObjectDocRuleFromEqExpr(module *Module, lhs, rhs *Term) (*Rule, head.Key = ref[1] } head.Location = rhs.Location - head.jsonOptions = rhs.jsonOptions body := NewBody(NewExpr(BooleanTerm(true).SetLocation(rhs.Location)).SetLocation(rhs.Location)) - setJSONOptions(body, &rhs.jsonOptions) rule := &Rule{ - Location: rhs.Location, - Head: head, - Body: body, - Module: module, - jsonOptions: rhs.jsonOptions, + Location: rhs.Location, + Head: head, + Body: body, + Module: module, } return rule, nil @@ -344,7 +351,7 @@ func ParsePartialSetDocRuleFromTerm(module *Module, term *Term) (*Rule, error) { ref, ok := term.Value.(Ref) if !ok || len(ref) == 1 { - return nil, fmt.Errorf("%vs cannot be used for rule head", TypeName(term.Value)) + return nil, fmt.Errorf("%vs cannot be used for rule head", ValueName(term.Value)) } if _, ok := ref[0].Value.(Var); !ok { return nil, fmt.Errorf("invalid rule head: %v", ref) @@ -354,25 +361,21 @@ func ParsePartialSetDocRuleFromTerm(module *Module, term *Term) (*Rule, error) { if len(ref) == 2 { v, ok := ref[0].Value.(Var) if !ok { - return nil, fmt.Errorf("%vs cannot be used for rule head", TypeName(term.Value)) + return nil, fmt.Errorf("%vs cannot be used for rule head", ValueName(term.Value)) } // Modify the code to add the location to the head ref - // and set the head ref's jsonOptions. - head = VarHead(v, ref[0].Location, &ref[0].jsonOptions) + head = VarHead(v, ref[0].Location, nil) head.Key = ref[1] } head.Location = term.Location - head.jsonOptions = term.jsonOptions body := NewBody(NewExpr(BooleanTerm(true).SetLocation(term.Location)).SetLocation(term.Location)) - setJSONOptions(body, &term.jsonOptions) rule := &Rule{ - Location: term.Location, - Head: head, - Body: body, - Module: module, - jsonOptions: term.jsonOptions, + Location: term.Location, + Head: head, + Body: body, + Module: module, } return rule, nil @@ -389,7 +392,7 @@ func ParseRuleFromCallEqExpr(module *Module, lhs, rhs *Term) (*Rule, error) { ref, ok := call[0].Value.(Ref) if !ok { - return nil, fmt.Errorf("%vs cannot be used in function signature", TypeName(call[0].Value)) + return nil, fmt.Errorf("%vs cannot be used in function signature", ValueName(call[0].Value)) } if _, ok := ref[0].Value.(Var); !ok { return nil, fmt.Errorf("invalid rule head: %v", ref) @@ -398,17 +401,14 @@ func ParseRuleFromCallEqExpr(module *Module, lhs, rhs *Term) (*Rule, error) { head := RefHead(ref, rhs) head.Location = lhs.Location head.Args = Args(call[1:]) - head.jsonOptions = lhs.jsonOptions body := NewBody(NewExpr(BooleanTerm(true).SetLocation(rhs.Location)).SetLocation(rhs.Location)) - setJSONOptions(body, &rhs.jsonOptions) rule := &Rule{ - Location: lhs.Location, - Head: head, - Body: body, - Module: module, - jsonOptions: lhs.jsonOptions, + Location: lhs.Location, + Head: head, + Body: body, + Module: module, } return rule, nil @@ -430,17 +430,14 @@ func ParseRuleFromCallExpr(module *Module, terms []*Term) (*Rule, error) { head := RefHead(ref, BooleanTerm(true).SetLocation(loc)) head.Location = loc head.Args = terms[1:] - head.jsonOptions = terms[0].jsonOptions body := NewBody(NewExpr(BooleanTerm(true).SetLocation(loc)).SetLocation(loc)) - setJSONOptions(body, &terms[0].jsonOptions) rule := &Rule{ - Location: loc, - Head: head, - Module: module, - Body: body, - jsonOptions: terms[0].jsonOptions, + Location: loc, + Head: head, + Module: module, + Body: body, } return rule, nil } @@ -608,6 +605,17 @@ func ParseStatement(input string) (Statement, error) { return stmts[0], nil } +func ParseStatementWithOpts(input string, popts ParserOptions) (Statement, error) { + stmts, _, err := ParseStatementsWithOpts("", input, popts) + if err != nil { + return nil, err + } + if len(stmts) != 1 { + return nil, fmt.Errorf("expected exactly one statement") + } + return stmts[0], nil +} + // ParseStatements is deprecated. Use ParseStatementWithOpts instead. func ParseStatements(filename, input string) ([]Statement, []*Comment, error) { return ParseStatementsWithOpts(filename, input, ParserOptions{}) @@ -625,7 +633,6 @@ func ParseStatementsWithOpts(filename, input string, popts ParserOptions) ([]Sta WithAllFutureKeywords(popts.AllFutureKeywords). WithCapabilities(popts.Capabilities). WithSkipRules(popts.SkipRules). - WithJSONOptions(popts.JSONOptions). WithRegoVersion(popts.RegoVersion). withUnreleasedKeywords(popts.unreleasedKeywords) @@ -659,7 +666,12 @@ func parseModule(filename string, stmts []Statement, comments []*Comment, regoCo // The comments slice only holds comments that were not their own statements. mod.Comments = append(mod.Comments, comments...) - mod.regoVersion = regoCompatibilityMode + + if regoCompatibilityMode == RegoUndefined { + mod.regoVersion = DefaultRegoVersion + } else { + mod.regoVersion = regoCompatibilityMode + } for i, stmt := range stmts[1:] { switch stmt := stmt.(type) { @@ -674,7 +686,7 @@ func parseModule(filename string, stmts []Statement, comments []*Comment, regoCo case Body: rule, err := ParseRuleFromBody(mod, stmt) if err != nil { - errs = append(errs, NewError(ParseErr, stmt[0].Location, err.Error())) + errs = append(errs, NewError(ParseErr, stmt[0].Location, err.Error())) //nolint:govet continue } rule.generatedBody = true @@ -742,16 +754,6 @@ func setRuleModule(rule *Rule, module *Module) { } } -func setJSONOptions(x interface{}, jsonOptions *astJSON.Options) { - vis := NewGenericVisitor(func(x interface{}) bool { - if x, ok := x.(customJSON); ok { - x.setJSONOptions(*jsonOptions) - } - return false - }) - vis.Walk(x) -} - // ParserErrorDetail holds additional details for parser errors. type ParserErrorDetail struct { Line string `json:"line"` diff --git a/vendor/github.com/open-policy-agent/opa/ast/policy.go b/vendor/github.com/open-policy-agent/opa/v1/ast/policy.go similarity index 93% rename from vendor/github.com/open-policy-agent/opa/ast/policy.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/policy.go index f07cf7b376..94dc25244b 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/policy.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/policy.go @@ -12,9 +12,9 @@ import ( "strings" "time" - "github.com/open-policy-agent/opa/ast/internal/tokens" - astJSON "github.com/open-policy-agent/opa/ast/json" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/ast/internal/tokens" + astJSON "github.com/open-policy-agent/opa/v1/ast/json" + "github.com/open-policy-agent/opa/v1/util" ) // Initialize seed for term hashing. This is intentionally placed before the @@ -84,7 +84,7 @@ var RootDocumentRefs = NewSet( // SystemDocumentKey is the name of the top-level key that identifies the system // document. -var SystemDocumentKey = String("system") +const SystemDocumentKey = String("system") // ReservedVars is the set of names that refer to implicitly ground vars. var ReservedVars = NewVarSet( @@ -97,10 +97,10 @@ var Wildcard = &Term{Value: Var("_")} // WildcardPrefix is the special character that all wildcard variables are // prefixed with when the statement they are contained in is parsed. -var WildcardPrefix = "$" +const WildcardPrefix = "$" // Keywords contains strings that map to language keywords. -var Keywords = KeywordsV0 +var Keywords = KeywordsForRegoVersion(DefaultRegoVersion) var KeywordsV0 = [...]string{ "not", @@ -134,9 +134,23 @@ var KeywordsV1 = [...]string{ "every", } +func KeywordsForRegoVersion(v RegoVersion) []string { + switch v { + case RegoV0: + return KeywordsV0[:] + case RegoV1, RegoV0CompatV1: + return KeywordsV1[:] + } + return nil +} + // IsKeyword returns true if s is a language keyword. func IsKeyword(s string) bool { - for _, x := range Keywords { + return IsInKeywords(s, Keywords) +} + +func IsInKeywords(s string, keywords []string) bool { + for _, x := range keywords { if x == s { return true } @@ -199,8 +213,6 @@ type ( // TODO: these fields have inconsistent JSON keys with other structs in this package. Text []byte Location *Location - - jsonOptions astJSON.Options } // Package represents the namespace of the documents produced @@ -208,8 +220,6 @@ type ( Package struct { Path Ref `json:"path"` Location *Location `json:"location,omitempty"` - - jsonOptions astJSON.Options } // Import represents a dependency on a document outside of the policy @@ -218,8 +228,6 @@ type ( Path *Term `json:"path"` Alias Var `json:"alias,omitempty"` Location *Location `json:"location,omitempty"` - - jsonOptions astJSON.Options } // Rule represents a rule as defined in the language. Rules define the @@ -239,7 +247,6 @@ type ( Module *Module `json:"-"` generatedBody bool - jsonOptions astJSON.Options } // Head represents the head of a rule. @@ -254,7 +261,6 @@ type ( keywords []tokens.Token generatedValue bool - jsonOptions astJSON.Options } // Args represents zero or more arguments to a rule. @@ -273,7 +279,6 @@ type ( Negated bool `json:"negated,omitempty"` Location *Location `json:"location,omitempty"` - jsonOptions astJSON.Options generatedFrom *Expr generates []*Expr } @@ -282,8 +287,6 @@ type ( SomeDecl struct { Symbols []*Term `json:"symbols"` Location *Location `json:"location,omitempty"` - - jsonOptions astJSON.Options } Every struct { @@ -292,8 +295,6 @@ type ( Domain *Term `json:"domain"` Body Body `json:"body"` Location *Location `json:"location,omitempty"` - - jsonOptions astJSON.Options } // With represents a modifier on an expression. @@ -301,11 +302,14 @@ type ( Target *Term `json:"target"` Value *Term `json:"value"` Location *Location `json:"location,omitempty"` - - jsonOptions astJSON.Options } ) +// SetModuleRegoVersion sets the RegoVersion for the Module. +func SetModuleRegoVersion(mod *Module, v RegoVersion) { + mod.regoVersion = v +} + // Compare returns an integer indicating whether mod is less than, equal to, // or greater than other. func (mod *Module) Compare(other *Module) int { @@ -405,7 +409,7 @@ func (mod *Module) String() string { buf = append(buf, "") for _, rule := range mod.Rules { buf = appendAnnotationStrings(buf, rule) - buf = append(buf, rule.String()) + buf = append(buf, rule.stringWithOpts(toStringOpts{regoVersion: mod.regoVersion})) } } return strings.Join(buf, "\n") @@ -495,15 +499,6 @@ func (c *Comment) Equal(other *Comment) bool { return c.Location.Equal(other.Location) && bytes.Equal(c.Text, other.Text) } -func (c *Comment) setJSONOptions(opts astJSON.Options) { - // Note: this is not used for location since Comments use default JSON marshaling - // behavior with struct field names in JSON. - c.jsonOptions = opts - if c.Location != nil { - c.Location.JSONOptions = opts - } -} - // Compare returns an integer indicating whether pkg is less than, equal to, // or greater than other. func (pkg *Package) Compare(other *Package) int { @@ -548,19 +543,12 @@ func (pkg *Package) String() string { return fmt.Sprintf("package %v", path) } -func (pkg *Package) setJSONOptions(opts astJSON.Options) { - pkg.jsonOptions = opts - if pkg.Location != nil { - pkg.Location.JSONOptions = opts - } -} - func (pkg *Package) MarshalJSON() ([]byte, error) { data := map[string]interface{}{ "path": pkg.Path, } - if pkg.jsonOptions.MarshalOptions.IncludeLocation.Package { + if astJSON.GetOptions().MarshalOptions.IncludeLocation.Package { if pkg.Location != nil { data["location"] = pkg.Location } @@ -661,13 +649,6 @@ func (imp *Import) String() string { return strings.Join(buf, " ") } -func (imp *Import) setJSONOptions(opts astJSON.Options) { - imp.jsonOptions = opts - if imp.Location != nil { - imp.Location.JSONOptions = opts - } -} - func (imp *Import) MarshalJSON() ([]byte, error) { data := map[string]interface{}{ "path": imp.Path, @@ -677,7 +658,7 @@ func (imp *Import) MarshalJSON() ([]byte, error) { data["alias"] = imp.Alias } - if imp.jsonOptions.MarshalOptions.IncludeLocation.Import { + if astJSON.GetOptions().MarshalOptions.IncludeLocation.Import { if imp.Location != nil { data["location"] = imp.Location } @@ -770,18 +751,41 @@ func (rule *Rule) Ref() Ref { } func (rule *Rule) String() string { + regoVersion := DefaultRegoVersion + if rule.Module != nil { + regoVersion = rule.Module.RegoVersion() + } + return rule.stringWithOpts(toStringOpts{regoVersion: regoVersion}) +} + +type toStringOpts struct { + regoVersion RegoVersion +} + +func (o toStringOpts) RegoVersion() RegoVersion { + if o.regoVersion == RegoUndefined { + return DefaultRegoVersion + } + return o.regoVersion +} + +func (rule *Rule) stringWithOpts(opts toStringOpts) string { buf := []string{} if rule.Default { buf = append(buf, "default") } - buf = append(buf, rule.Head.String()) + buf = append(buf, rule.Head.stringWithOpts(opts)) if !rule.Default { + switch opts.RegoVersion() { + case RegoV1, RegoV0CompatV1: + buf = append(buf, "if") + } buf = append(buf, "{") buf = append(buf, rule.Body.String()) buf = append(buf, "}") } if rule.Else != nil { - buf = append(buf, rule.Else.elseString()) + buf = append(buf, rule.Else.elseString(opts)) } return strings.Join(buf, " ") } @@ -790,13 +794,6 @@ func (rule *Rule) isFunction() bool { return len(rule.Head.Args) > 0 } -func (rule *Rule) setJSONOptions(opts astJSON.Options) { - rule.jsonOptions = opts - if rule.Location != nil { - rule.Location.JSONOptions = opts - } -} - func (rule *Rule) MarshalJSON() ([]byte, error) { data := map[string]interface{}{ "head": rule.Head, @@ -811,7 +808,7 @@ func (rule *Rule) MarshalJSON() ([]byte, error) { data["else"] = rule.Else } - if rule.jsonOptions.MarshalOptions.IncludeLocation.Rule { + if astJSON.GetOptions().MarshalOptions.IncludeLocation.Rule { if rule.Location != nil { data["location"] = rule.Location } @@ -824,7 +821,7 @@ func (rule *Rule) MarshalJSON() ([]byte, error) { return json.Marshal(data) } -func (rule *Rule) elseString() string { +func (rule *Rule) elseString(opts toStringOpts) string { var buf []string buf = append(buf, "else") @@ -835,12 +832,17 @@ func (rule *Rule) elseString() string { buf = append(buf, value.String()) } + switch opts.RegoVersion() { + case RegoV1, RegoV0CompatV1: + buf = append(buf, "if") + } + buf = append(buf, "{") buf = append(buf, rule.Body.String()) buf = append(buf, "}") if rule.Else != nil { - buf = append(buf, rule.Else.elseString()) + buf = append(buf, rule.Else.elseString(opts)) } return strings.Join(buf, " ") @@ -867,14 +869,11 @@ func NewHead(name Var, args ...*Term) *Head { return head } -// VarHead creates a head object, initializes its Name, Location, and Options, -// and returns the new head. -func VarHead(name Var, location *Location, jsonOpts *astJSON.Options) *Head { +// VarHead creates a head object, initializes its Name and Location and returns the new head. +// NOTE: The JSON options argument is no longer used, and kept only for backwards compatibility. +func VarHead(name Var, location *Location, _ *astJSON.Options) *Head { h := NewHead(name) h.Reference[0].Location = location - if jsonOpts != nil { - h.Reference[0].setJSONOptions(*jsonOpts) - } return h } @@ -1000,16 +999,28 @@ func (head *Head) Equal(other *Head) bool { } func (head *Head) String() string { + return head.stringWithOpts(toStringOpts{}) +} + +func (head *Head) stringWithOpts(opts toStringOpts) string { buf := strings.Builder{} buf.WriteString(head.Ref().String()) + containsAdded := false switch { case len(head.Args) != 0: buf.WriteString(head.Args.String()) case len(head.Reference) == 1 && head.Key != nil: - buf.WriteRune('[') - buf.WriteString(head.Key.String()) - buf.WriteRune(']') + switch opts.RegoVersion() { + case RegoV0: + buf.WriteRune('[') + buf.WriteString(head.Key.String()) + buf.WriteRune(']') + default: + containsAdded = true + buf.WriteString(" contains ") + buf.WriteString(head.Key.String()) + } } if head.Value != nil { if head.Assign { @@ -1018,33 +1029,17 @@ func (head *Head) String() string { buf.WriteString(" = ") } buf.WriteString(head.Value.String()) - } else if head.Name == "" && head.Key != nil { + } else if !containsAdded && head.Name == "" && head.Key != nil { buf.WriteString(" contains ") buf.WriteString(head.Key.String()) } return buf.String() } -func (head *Head) setJSONOptions(opts astJSON.Options) { - head.jsonOptions = opts - if head.Location != nil { - head.Location.JSONOptions = opts - } -} - func (head *Head) MarshalJSON() ([]byte, error) { var loc *Location - includeLoc := head.jsonOptions.MarshalOptions.IncludeLocation - if includeLoc.Head { - if head.Location != nil { - loc = head.Location - } - - for _, term := range head.Reference { - if term.Location != nil { - term.jsonOptions.MarshalOptions.IncludeLocation.Term = includeLoc.Term - } - } + if astJSON.GetOptions().MarshalOptions.IncludeLocation.Head && head.Location != nil { + loc = head.Location } // NOTE(sr): we do this to override the rendering of `head.Reference`. @@ -1292,6 +1287,16 @@ func (expr *Expr) Complement() *Expr { return &cpy } +// ComplementNoWith returns a copy of this expression with the negation flag flipped +// and the with modifier removed. This is the same as calling .Complement().NoWith() +// but without making an intermediate copy. +func (expr *Expr) ComplementNoWith() *Expr { + cpy := *expr + cpy.Negated = !cpy.Negated + cpy.With = nil + return &cpy +} + // Equal returns true if this Expr equals the other Expr. func (expr *Expr) Equal(other *Expr) bool { return expr.Compare(other) == 0 @@ -1382,9 +1387,11 @@ func (expr *Expr) sortOrder() int { func (expr *Expr) CopyWithoutTerms() *Expr { cpy := *expr - cpy.With = make([]*With, len(expr.With)) - for i := range expr.With { - cpy.With[i] = expr.With[i].Copy() + if expr.With != nil { + cpy.With = make([]*With, len(expr.With)) + for i := range expr.With { + cpy.With[i] = expr.With[i].Copy() + } } return &cpy @@ -1584,13 +1591,6 @@ func (expr *Expr) String() string { return strings.Join(buf, " ") } -func (expr *Expr) setJSONOptions(opts astJSON.Options) { - expr.jsonOptions = opts - if expr.Location != nil { - expr.Location.JSONOptions = opts - } -} - func (expr *Expr) MarshalJSON() ([]byte, error) { data := map[string]interface{}{ "terms": expr.Terms, @@ -1609,7 +1609,7 @@ func (expr *Expr) MarshalJSON() ([]byte, error) { data["negated"] = true } - if expr.jsonOptions.MarshalOptions.IncludeLocation.Expr { + if astJSON.GetOptions().MarshalOptions.IncludeLocation.Expr { if expr.Location != nil { data["location"] = expr.Location } @@ -1723,19 +1723,12 @@ func (d *SomeDecl) Hash() int { return termSliceHash(d.Symbols) } -func (d *SomeDecl) setJSONOptions(opts astJSON.Options) { - d.jsonOptions = opts - if d.Location != nil { - d.Location.JSONOptions = opts - } -} - func (d *SomeDecl) MarshalJSON() ([]byte, error) { data := map[string]interface{}{ "symbols": d.Symbols, } - if d.jsonOptions.MarshalOptions.IncludeLocation.SomeDecl { + if astJSON.GetOptions().MarshalOptions.IncludeLocation.SomeDecl { if d.Location != nil { data["location"] = d.Location } @@ -1800,13 +1793,6 @@ func (q *Every) KeyValueVars() VarSet { return vis.vars } -func (q *Every) setJSONOptions(opts astJSON.Options) { - q.jsonOptions = opts - if q.Location != nil { - q.Location.JSONOptions = opts - } -} - func (q *Every) MarshalJSON() ([]byte, error) { data := map[string]interface{}{ "key": q.Key, @@ -1815,7 +1801,7 @@ func (q *Every) MarshalJSON() ([]byte, error) { "body": q.Body, } - if q.jsonOptions.MarshalOptions.IncludeLocation.Every { + if astJSON.GetOptions().MarshalOptions.IncludeLocation.Every { if q.Location != nil { data["location"] = q.Location } @@ -1882,20 +1868,13 @@ func (w *With) SetLoc(loc *Location) { w.Location = loc } -func (w *With) setJSONOptions(opts astJSON.Options) { - w.jsonOptions = opts - if w.Location != nil { - w.Location.JSONOptions = opts - } -} - func (w *With) MarshalJSON() ([]byte, error) { data := map[string]interface{}{ "target": w.Target, "value": w.Value, } - if w.jsonOptions.MarshalOptions.IncludeLocation.With { + if astJSON.GetOptions().MarshalOptions.IncludeLocation.With { if w.Location != nil { data["location"] = w.Location } diff --git a/vendor/github.com/open-policy-agent/opa/ast/pretty.go b/vendor/github.com/open-policy-agent/opa/v1/ast/pretty.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/ast/pretty.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/pretty.go diff --git a/vendor/github.com/open-policy-agent/opa/ast/rego_v1.go b/vendor/github.com/open-policy-agent/opa/v1/ast/rego_v1.go similarity index 90% rename from vendor/github.com/open-policy-agent/opa/ast/rego_v1.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/rego_v1.go index 9fa1c6f9b4..8b757ecc3c 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/rego_v1.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/rego_v1.go @@ -3,7 +3,7 @@ package ast import ( "fmt" - "github.com/open-policy-agent/opa/ast/internal/tokens" + "github.com/open-policy-agent/opa/v1/ast/internal/tokens" ) func checkDuplicateImports(modules []*Module) (errors Errors) { @@ -50,9 +50,12 @@ func checkRootDocumentOverrides(node interface{}) Errors { WalkExprs(node, func(expr *Expr) bool { if expr.IsAssignment() { - name := expr.Operand(0).String() - if RootDocumentRefs.Contains(RefTerm(VarTerm(name))) { - errors = append(errors, NewError(CompileErr, expr.Location, "variables must not shadow %v (use a different variable name)", name)) + // assign() can be called directly, so we need to assert its given first operand exists before checking its name. + if nameOp := expr.Operand(0); nameOp != nil { + name := nameOp.String() + if RootDocumentRefs.Contains(RefTerm(VarTerm(name))) { + errors = append(errors, NewError(CompileErr, expr.Location, "variables must not shadow %v (use a different variable name)", name)) + } } } return false @@ -189,7 +192,7 @@ func checkRegoV1Rule(rule *Rule, opts RegoCheckOptions) Errors { var errs Errors if opts.NoKeywordsAsRuleNames && IsKeywordInRegoVersion(rule.Head.Name.String(), RegoV1) { - errs = append(errs, NewError(ParseErr, rule.Location, fmt.Sprintf("%s keyword cannot be used for rule name", rule.Head.Name.String()))) + errs = append(errs, NewError(ParseErr, rule.Location, "%s keyword cannot be used for rule name", rule.Head.Name.String())) } if opts.RequireRuleBodyOrValue && rule.generatedBody && rule.Head.generatedValue { errs = append(errs, NewError(ParseErr, rule.Location, "%s must have value assignment and/or body declaration", t)) diff --git a/vendor/github.com/open-policy-agent/opa/ast/schema.go b/vendor/github.com/open-policy-agent/opa/v1/ast/schema.go similarity index 93% rename from vendor/github.com/open-policy-agent/opa/ast/schema.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/schema.go index 8c96ac624e..e84a147a4a 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/schema.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/schema.go @@ -7,8 +7,8 @@ package ast import ( "fmt" - "github.com/open-policy-agent/opa/types" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/types" + "github.com/open-policy-agent/opa/v1/util" ) // SchemaSet holds a map from a path to a schema. diff --git a/vendor/github.com/open-policy-agent/opa/v1/ast/strings.go b/vendor/github.com/open-policy-agent/opa/v1/ast/strings.go new file mode 100644 index 0000000000..40d66753f5 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/strings.go @@ -0,0 +1,54 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + "reflect" + "strings" +) + +// TypeName returns a human readable name for the AST element type. +func TypeName(x interface{}) string { + if _, ok := x.(*lazyObj); ok { + return "object" + } + return strings.ToLower(reflect.Indirect(reflect.ValueOf(x)).Type().Name()) +} + +// ValueName returns a human readable name for the AST Value type. +// This is preferrable over calling TypeName when the argument is known to be +// a Value, as this doesn't require reflection (= heap allocations). +func ValueName(x Value) string { + switch x.(type) { + case String: + return "string" + case Boolean: + return "boolean" + case Number: + return "number" + case Null: + return "null" + case Var: + return "var" + case Object: + return "object" + case Set: + return "set" + case Ref: + return "ref" + case Call: + return "call" + case *Array: + return "array" + case *ArrayComprehension: + return "arraycomprehension" + case *ObjectComprehension: + return "objectcomprehension" + case *SetComprehension: + return "setcomprehension" + } + + return TypeName(x) +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/term.go b/vendor/github.com/open-policy-agent/opa/v1/ast/term.go similarity index 88% rename from vendor/github.com/open-policy-agent/opa/ast/term.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/term.go index 4664bc5dac..9abc29346a 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/term.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/term.go @@ -8,23 +8,22 @@ package ast import ( "bytes" "encoding/json" - "errors" "fmt" "io" "math" "math/big" "net/url" "regexp" - "sort" + "slices" "strconv" "strings" "sync" "github.com/OneOfOne/xxhash" - astJSON "github.com/open-policy-agent/opa/ast/json" - "github.com/open-policy-agent/opa/ast/location" - "github.com/open-policy-agent/opa/util" + astJSON "github.com/open-policy-agent/opa/v1/ast/json" + "github.com/open-policy-agent/opa/v1/ast/location" + "github.com/open-policy-agent/opa/v1/util" ) var errFindNotFound = fmt.Errorf("find: not found") @@ -57,10 +56,16 @@ type Value interface { func InterfaceToValue(x interface{}) (Value, error) { switch x := x.(type) { case nil: - return Null{}, nil + return NullValue, nil case bool: - return Boolean(x), nil + if x { + return InternedBooleanTerm(true).Value, nil + } + return InternedBooleanTerm(false).Value, nil case json.Number: + if interned := InternedIntNumberTermFromString(string(x)); interned != nil { + return interned.Value, nil + } return Number(x), nil case int64: return int64Number(x), nil @@ -72,42 +77,37 @@ func InterfaceToValue(x interface{}) (Value, error) { return intNumber(x), nil case string: return String(x), nil - case []interface{}: - r := make([]*Term, len(x)) + case []any: + r := util.NewPtrSlice[Term](len(x)) for i, e := range x { e, err := InterfaceToValue(e) if err != nil { return nil, err } - r[i] = &Term{Value: e} + r[i].Value = e } return NewArray(r...), nil - case map[string]interface{}: - r := newobject(len(x)) + case map[string]any: + kvs := util.NewPtrSlice[Term](len(x) * 2) + idx := 0 for k, v := range x { - k, err := InterfaceToValue(k) - if err != nil { - return nil, err - } + kvs[idx].Value = String(k) v, err := InterfaceToValue(v) if err != nil { return nil, err } - r.Insert(NewTerm(k), NewTerm(v)) + kvs[idx+1].Value = v + idx += 2 } - return r, nil + tuples := make([][2]*Term, len(kvs)/2) + for i := 0; i < len(kvs); i += 2 { + tuples[i/2] = *(*[2]*Term)(kvs[i : i+2]) + } + return NewObject(tuples...), nil case map[string]string: r := newobject(len(x)) for k, v := range x { - k, err := InterfaceToValue(k) - if err != nil { - return nil, err - } - v, err := InterfaceToValue(v) - if err != nil { - return nil, err - } - r.Insert(NewTerm(k), NewTerm(v)) + r.Insert(StringTerm(k), StringTerm(v)) } return r, nil default: @@ -130,7 +130,7 @@ func ValueFromReader(r io.Reader) (Value, error) { // As converts v into a Go native type referred to by x. func As(v Value, x interface{}) error { - return util.NewJSONDecoder(bytes.NewBufferString(v.String())).Decode(x) + return util.NewJSONDecoder(strings.NewReader(v.String())).Decode(x) } // Resolver defines the interface for resolving references to native Go values. @@ -294,8 +294,6 @@ func MustInterfaceToValue(x interface{}) Value { type Term struct { Value Value `json:"value"` // the value of the Term as represented in Go Location *Location `json:"location,omitempty"` // the location of the Term in the source - - jsonOptions astJSON.Options } // NewTerm returns a new Term object. @@ -326,7 +324,6 @@ func (term *Term) SetLoc(loc *Location) { // Copy returns a deep copy of term. func (term *Term) Copy() *Term { - if term == nil { return nil } @@ -358,7 +355,7 @@ func (term *Term) Copy() *Term { } // Equal returns true if this term equals the other term. Equality is -// defined for each kind of term. +// defined for each kind of term, and does not compare the Location. func (term *Term) Equal(other *Term) bool { if term == nil && other != nil { return false @@ -370,24 +367,7 @@ func (term *Term) Equal(other *Term) bool { return true } - // TODO(tsandall): This early-exit avoids allocations for types that have - // Equal() functions that just use == underneath. We should revisit the - // other types and implement Equal() functions that do not require - // allocations. - switch v := term.Value.(type) { - case Null: - return v.Equal(other.Value) - case Boolean: - return v.Equal(other.Value) - case Number: - return v.Equal(other.Value) - case String: - return v.Equal(other.Value) - case Var: - return v.Equal(other.Value) - } - - return term.Value.Compare(other.Value) == 0 + return ValueEqual(term.Value, other.Value) } // Get returns a value referred to by name from the term. @@ -420,22 +400,16 @@ func (term *Term) IsGround() bool { return term.Value.IsGround() } -func (term *Term) setJSONOptions(opts astJSON.Options) { - term.jsonOptions = opts - if term.Location != nil { - term.Location.JSONOptions = opts - } -} - // MarshalJSON returns the JSON encoding of the term. // // Specialized marshalling logic is required to include a type hint for Value. func (term *Term) MarshalJSON() ([]byte, error) { d := map[string]interface{}{ - "type": TypeName(term.Value), + "type": ValueName(term.Value), "value": term.Value, } - if term.jsonOptions.MarshalOptions.IncludeLocation.Term { + jsonOptions := astJSON.GetOptions().MarshalOptions + if jsonOptions.IncludeLocation.Term { if term.Location != nil { d["location"] = term.Location } @@ -544,13 +518,7 @@ func ContainsClosures(v interface{}) bool { // IsScalar returns true if the AST value is a scalar. func IsScalar(v Value) bool { switch v.(type) { - case String: - return true - case Number: - return true - case Boolean: - return true - case Null: + case String, Number, Boolean, Null: return true } return false @@ -559,9 +527,11 @@ func IsScalar(v Value) bool { // Null represents the null value defined by JSON. type Null struct{} +var NullValue Value = Null{} + // NullTerm creates a new Term with a Null value. func NullTerm() *Term { - return &Term{Value: Null{}} + return &Term{Value: NullValue} } // Equal returns true if the other term Value is also Null. @@ -577,13 +547,16 @@ func (null Null) Equal(other Value) bool { // Compare compares null to other, return <0, 0, or >0 if it is less than, equal to, // or greater than other. func (null Null) Compare(other Value) int { - return Compare(null, other) + if _, ok := other.(Null); ok { + return 0 + } + return -1 } // Find returns the current value or a not found error. func (null Null) Find(path Ref) (Value, error) { if len(path) == 0 { - return null, nil + return NullValue, nil } return nil, errFindNotFound } @@ -607,7 +580,10 @@ type Boolean bool // BooleanTerm creates a new Term with a Boolean value. func BooleanTerm(b bool) *Term { - return &Term{Value: Boolean(b)} + if b { + return &Term{Value: InternedBooleanTerm(true).Value} + } + return &Term{Value: InternedBooleanTerm(false).Value} } // Equal returns true if the other Value is a Boolean and is equal. @@ -623,13 +599,29 @@ func (bol Boolean) Equal(other Value) bool { // Compare compares bol to other, return <0, 0, or >0 if it is less than, equal to, // or greater than other. func (bol Boolean) Compare(other Value) int { - return Compare(bol, other) + switch other := other.(type) { + case Boolean: + if bol == other { + return 0 + } + if !bol { + return -1 + } + return 1 + case Null: + return 1 + } + + return -1 } // Find returns the current value or a not found error. func (bol Boolean) Find(path Ref) (Value, error) { if len(path) == 0 { - return bol, nil + if bol { + return InternedBooleanTerm(true).Value, nil + } + return InternedBooleanTerm(false).Value, nil } return nil, errFindNotFound } @@ -679,7 +671,14 @@ func FloatNumberTerm(f float64) *Term { func (num Number) Equal(other Value) bool { switch other := other.(type) { case Number: - return Compare(num, other) == 0 + if n1, ok1 := num.Int64(); ok1 { + n2, ok2 := other.Int64() + if ok1 && ok2 && n1 == n2 { + return true + } + } + + return num.Compare(other) == 0 default: return false } @@ -688,6 +687,21 @@ func (num Number) Equal(other Value) bool { // Compare compares num to other, return <0, 0, or >0 if it is less than, equal to, // or greater than other. func (num Number) Compare(other Value) int { + // Optimize for the common case, as calling Compare allocates on heap. + if otherNum, yes := other.(Number); yes { + if ai, ok := num.Int64(); ok { + if bi, ok := otherNum.Int64(); ok { + if ai == bi { + return 0 + } + if ai < bi { + return -1 + } + return 1 + } + } + } + return Compare(num, other) } @@ -785,6 +799,19 @@ func (str String) Equal(other Value) bool { // Compare compares str to other, return <0, 0, or >0 if it is less than, equal to, // or greater than other. func (str String) Compare(other Value) int { + // Optimize for the common case of one string being compared to another by + // using a direct comparison of values. This avoids the allocation performed + // when calling Compare and its interface{} argument conversion. + if otherStr, ok := other.(String); ok { + if str == otherStr { + return 0 + } + if str < otherStr { + return -1 + } + return 1 + } + return Compare(str, other) } @@ -833,6 +860,9 @@ func (v Var) Equal(other Value) bool { // Compare compares v to other, return <0, 0, or >0 if it is less than, equal to, // or greater than other. func (v Var) Compare(other Value) int { + if otherVar, ok := other.(Var); ok { + return strings.Compare(string(v), string(otherVar)) + } return Compare(v, other) } @@ -986,12 +1016,29 @@ func (ref Ref) Copy() Ref { // Equal returns true if ref is equal to other. func (ref Ref) Equal(other Value) bool { - return Compare(ref, other) == 0 + switch o := other.(type) { + case Ref: + if len(ref) == len(o) { + for i := range ref { + if !ref[i].Equal(o[i]) { + return false + } + } + + return true + } + } + + return false } // Compare compares ref to other, return <0, 0, or >0 if it is less than, equal to, // or greater than other. func (ref Ref) Compare(other Value) int { + if o, ok := other.(Ref); ok { + return termSliceCompare(ref, o) + } + return Compare(ref, other) } @@ -1023,32 +1070,32 @@ func (ref Ref) HasPrefix(other Ref) bool { // ConstantPrefix returns the constant portion of the ref starting from the head. func (ref Ref) ConstantPrefix() Ref { - ref = ref.Copy() - i := ref.Dynamic() if i < 0 { - return ref + return ref.Copy() } - return ref[:i] + return ref[:i].Copy() } func (ref Ref) StringPrefix() Ref { - r := ref.Copy() - for i := 1; i < len(ref); i++ { - switch r[i].Value.(type) { + switch ref[i].Value.(type) { case String: // pass default: // cut off - return r[:i] + return ref[:i].Copy() } } - return r + return ref.Copy() } // GroundPrefix returns the ground portion of the ref starting from the head. By // definition, the head of the reference is always ground. func (ref Ref) GroundPrefix() Ref { + if ref.IsGround() { + return ref + } + prefix := make(Ref, 0, len(ref)) for i, x := range ref { @@ -1108,26 +1155,46 @@ func IsVarCompatibleString(s string) bool { return varRegexp.MatchString(s) } +var sbPool = sync.Pool{ + New: func() any { + return &strings.Builder{} + }, +} + func (ref Ref) String() string { if len(ref) == 0 { return "" } - buf := []string{ref[0].Value.String()} - path := ref[1:] - for _, p := range path { + + sb := sbPool.Get().(*strings.Builder) + sb.Reset() + + defer sbPool.Put(sb) + + sb.Grow(10 * len(ref)) + + sb.WriteString(ref[0].Value.String()) + + for _, p := range ref[1:] { switch p := p.Value.(type) { case String: str := string(p) - if varRegexp.MatchString(str) && len(buf) > 0 && !IsKeyword(str) { - buf = append(buf, "."+str) + if varRegexp.MatchString(str) && !IsKeyword(str) { + sb.WriteByte('.') + sb.WriteString(str) } else { - buf = append(buf, "["+p.String()+"]") + sb.WriteString(`["`) + sb.WriteString(str) + sb.WriteString(`"]`) } default: - buf = append(buf, "["+p.String()+"]") + sb.WriteByte('[') + sb.WriteString(p.String()) + sb.WriteByte(']') } } - return strings.Join(buf, "") + + return sb.String() } // OutputVars returns a VarSet containing variables that would be bound by evaluating @@ -1193,12 +1260,38 @@ func (arr *Array) Copy() *Array { // Equal returns true if arr is equal to other. func (arr *Array) Equal(other Value) bool { - return Compare(arr, other) == 0 + if arr == other { + return true + } + + if other, ok := other.(*Array); ok && len(arr.elems) == len(other.elems) { + for i := range arr.elems { + if !arr.elems[i].Equal(other.elems[i]) { + return false + } + } + return true + } + + return false } // Compare compares arr to other, return <0, 0, or >0 if it is less than, equal to, // or greater than other. func (arr *Array) Compare(other Value) int { + if b, ok := other.(*Array); ok { + return termSliceCompare(arr.elems, b.elems) + } + + sortA := sortOrder(arr) + sortB := sortOrder(other) + + if sortA < sortB { + return -1 + } else if sortB < sortA { + return 1 + } + return Compare(arr, other) } @@ -1246,7 +1339,9 @@ func (arr *Array) Sorted() *Array { for i := range cpy { cpy[i] = arr.elems[i] } - sort.Sort(termSlice(cpy)) + + slices.SortFunc(cpy, TermValueCompare) + a := NewArray(cpy...) a.hashs = arr.hashs return a @@ -1271,16 +1366,22 @@ func (arr *Array) MarshalJSON() ([]byte, error) { } func (arr *Array) String() string { - var b strings.Builder - b.WriteRune('[') + sb := sbPool.Get().(*strings.Builder) + sb.Reset() + sb.Grow(len(arr.elems) * 16) + + defer sbPool.Put(sb) + + sb.WriteRune('[') for i, e := range arr.elems { if i > 0 { - b.WriteString(", ") + sb.WriteString(", ") } - b.WriteString(e.String()) + sb.WriteString(e.String()) } - b.WriteRune(']') - return b.String() + sb.WriteRune(']') + + return sb.String() } // Len returns the number of elements in the array. @@ -1293,6 +1394,11 @@ func (arr *Array) Elem(i int) *Term { return arr.elems[i] } +// Set sets the element i of arr. +func (arr *Array) Set(i int, v *Term) { + arr.set(i, v) +} + // rehash updates the cached hash of arr. func (arr *Array) rehash() { arr.hash = 0 @@ -1306,6 +1412,7 @@ func (arr *Array) set(i int, v *Term) { arr.ground = arr.ground && v.IsGround() arr.elems[i] = v arr.hashs[i] = v.Value.Hash() + arr.rehash() } // Slice returns a slice of arr starting from i index to j. -1 @@ -1344,21 +1451,19 @@ func (arr *Array) Iter(f func(*Term) error) error { // Until calls f on each element in arr. If f returns true, iteration stops. func (arr *Array) Until(f func(*Term) bool) bool { - err := arr.Iter(func(t *Term) error { - if f(t) { - return errStop + for _, term := range arr.elems { + if f(term) { + return true } - return nil - }) - return err != nil + } + return false } // Foreach calls f on each element in arr. func (arr *Array) Foreach(f func(*Term)) { - _ = arr.Iter(func(t *Term) error { - f(t) - return nil - }) // ignore error + for _, term := range arr.elems { + f(term) + } } // Append appends a term to arr, returning the appended array. @@ -1393,8 +1498,8 @@ type Set interface { // NewSet returns a new Set containing t. func NewSet(t ...*Term) Set { s := newset(len(t)) - for i := range t { - s.Add(t[i]) + for _, term := range t { + s.insert(term, false) } return s } @@ -1409,7 +1514,7 @@ func newset(n int) *set { keys: keys, hash: 0, ground: true, - sortGuard: new(sync.Once), + sortGuard: sync.Once{}, } } @@ -1422,19 +1527,24 @@ func SetTerm(t ...*Term) *Term { } type set struct { - elems map[int]*Term - keys []*Term - hash int - ground bool - sortGuard *sync.Once // Prevents race condition around sorting. + elems map[int]*Term + keys []*Term + hash int + ground bool + // Prevents race condition around sorting. + // We can avoid (the allocation cost of) using a pointer here as all + // methods of `set` use a pointer receiver, and the `sync.Once` value + // is never copied. + sortGuard sync.Once } // Copy returns a deep copy of s. func (s *set) Copy() Set { - cpy := newset(s.Len()) - s.Foreach(func(x *Term) { - cpy.Add(x.Copy()) - }) + terms := make([]*Term, len(s.keys)) + for i := range s.keys { + terms[i] = s.keys[i].Copy() + } + cpy := NewSet(terms...).(*set) cpy.hash = s.hash cpy.ground = s.ground return cpy @@ -1454,21 +1564,28 @@ func (s *set) String() string { if s.Len() == 0 { return "set()" } - var b strings.Builder - b.WriteRune('{') + + sb := sbPool.Get().(*strings.Builder) + sb.Reset() + sb.Grow(s.Len() * 16) + + defer sbPool.Put(sb) + + sb.WriteRune('{') for i := range s.sortedKeys() { if i > 0 { - b.WriteString(", ") + sb.WriteString(", ") } - b.WriteString(s.keys[i].Value.String()) + sb.WriteString(s.keys[i].Value.String()) } - b.WriteRune('}') - return b.String() + sb.WriteRune('}') + + return sb.String() } func (s *set) sortedKeys() []*Term { s.sortGuard.Do(func() { - sort.Sort(termSlice(s.keys)) + slices.SortFunc(s.keys, TermValueCompare) }) return s.keys } @@ -1500,13 +1617,14 @@ func (s *set) Find(path Ref) (Value, error) { // Diff returns elements in s that are not in other. func (s *set) Diff(other Set) Set { - r := NewSet() - s.Foreach(func(x *Term) { - if !other.Contains(x) { - r.Add(x) + terms := make([]*Term, 0, len(s.keys)) + for _, term := range s.sortedKeys() { + if !other.Contains(term) { + terms = append(terms, term) } - }) - return r + } + + return NewSet(terms...) } // Intersect returns the set containing elements in both s and other. @@ -1521,79 +1639,68 @@ func (s *set) Intersect(other Set) Set { n = m } - r := newset(n) - ss.Foreach(func(x *Term) { - if so.Contains(x) { - r.Add(x) + terms := make([]*Term, 0, n) + for _, term := range ss.sortedKeys() { + if so.Contains(term) { + terms = append(terms, term) } - }) - return r + } + + return NewSet(terms...) } // Union returns the set containing all elements of s and other. func (s *set) Union(other Set) Set { r := NewSet() - s.Foreach(func(x *Term) { - r.Add(x) - }) - other.Foreach(func(x *Term) { - r.Add(x) - }) + s.Foreach(r.Add) + other.Foreach(r.Add) return r } // Add updates s to include t. func (s *set) Add(t *Term) { - s.insert(t) + s.insert(t, true) } // Iter calls f on each element in s. If f returns an error, iteration stops // and the return value is the error. func (s *set) Iter(f func(*Term) error) error { - for i := range s.sortedKeys() { - if err := f(s.keys[i]); err != nil { + for _, term := range s.sortedKeys() { + if err := f(term); err != nil { return err } } return nil } -var errStop = errors.New("stop") - // Until calls f on each element in s. If f returns true, iteration stops. func (s *set) Until(f func(*Term) bool) bool { - err := s.Iter(func(t *Term) error { - if f(t) { - return errStop + for _, term := range s.sortedKeys() { + if f(term) { + return true } - return nil - }) - return err != nil + } + return false } // Foreach calls f on each element in s. func (s *set) Foreach(f func(*Term)) { - _ = s.Iter(func(t *Term) error { - f(t) - return nil - }) // ignore error + for _, term := range s.sortedKeys() { + f(term) + } } // Map returns a new Set obtained by applying f to each value in s. func (s *set) Map(f func(*Term) (*Term, error)) (Set, error) { - set := NewSet() - err := s.Iter(func(x *Term) error { + mapped := make([]*Term, 0, len(s.keys)) + for _, x := range s.sortedKeys() { term, err := f(x) if err != nil { - return err + return nil, err } - set.Add(term) - return nil - }) - if err != nil { - return nil, err + mapped = append(mapped, term) } - return set, nil + return NewSet(mapped...), nil } // Reduce returns a Term produced by applying f to each value in s. The first @@ -1641,9 +1748,23 @@ func (s *set) Slice() []*Term { return s.sortedKeys() } +// Internal method to use for cases where a set may be reused in favor +// of creating a new one (with the associated allocations). +func (s *set) clear() { + clear(s.elems) + s.keys = s.keys[:0] + s.hash = 0 + s.ground = true + s.sortGuard = sync.Once{} +} + +func (s *set) insertNoGuard(x *Term) { + s.insert(x, false) +} + // NOTE(philipc): We assume a many-readers, single-writer model here. // This method should NOT be used concurrently, or else we risk data races. -func (s *set) insert(x *Term) { +func (s *set) insert(x *Term, resetSortGuard bool) { hash := x.Hash() insertHash := hash // This `equal` utility is duplicated and manually inlined a number of @@ -1735,9 +1856,15 @@ func (s *set) insert(x *Term) { s.elems[insertHash] = x // O(1) insertion, but we'll have to re-sort the keys later. s.keys = append(s.keys, x) - // Reset the sync.Once instance. - // See https://github.com/golang/go/issues/25955 for why we do it this way. - s.sortGuard = new(sync.Once) + + if resetSortGuard { + // Reset the sync.Once instance. + // See https://github.com/golang/go/issues/25955 for why we do it this way. + // Note that this will always be the case when external code calls insert via + // Add, or otherwise. Internal code may however benefit from not having to + // re-create this pointer when it's known not to be needed. + s.sortGuard = sync.Once{} + } s.hash += hash s.ground = s.ground && x.IsGround() @@ -1859,7 +1986,7 @@ type Object interface { func NewObject(t ...[2]*Term) Object { obj := newobject(len(t)) for i := range t { - obj.Insert(t[i][0], t[i][1]) + obj.insert(t[i][0], t[i][1], false) } return obj } @@ -2005,7 +2132,8 @@ func (l *lazyObj) Keys() []*Term { for k := range l.native { ret = append(ret, StringTerm(k)) } - sort.Sort(termSlice(ret)) + slices.SortFunc(ret, TermValueCompare) + return ret } @@ -2059,7 +2187,7 @@ type object struct { ground int // number of key and value grounds. Counting is // required to support insert's key-value replace. hash int - sortGuard *sync.Once // Prevents race condition around sorting. + sortGuard sync.Once // Prevents race condition around sorting. } func newobject(n int) *object { @@ -2072,7 +2200,7 @@ func newobject(n int) *object { keys: keys, ground: 0, hash: 0, - sortGuard: new(sync.Once), + sortGuard: sync.Once{}, } } @@ -2096,7 +2224,9 @@ func Item(key, value *Term) [2]*Term { func (obj *object) sortedKeys() objectElemSlice { obj.sortGuard.Do(func() { - sort.Sort(obj.keys) + slices.SortFunc(obj.keys, func(a, b *objectElem) int { + return a.key.Value.Compare(b.key.Value) + }) }) return obj.keys } @@ -2160,7 +2290,7 @@ func (obj *object) Find(path Ref) (Value, error) { } func (obj *object) Insert(k, v *Term) { - obj.insert(k, v) + obj.insert(k, v, true) } // Get returns the value of k in obj if k exists, otherwise nil. @@ -2192,12 +2322,12 @@ func (obj *object) Copy() Object { // Diff returns a new Object that contains only the key/value pairs that exist in obj. func (obj *object) Diff(other Object) Object { - r := NewObject() - obj.Foreach(func(k, v *Term) { - if other.Get(k) == nil { - r.Insert(k, v) + r := newobject(obj.Len()) + for _, node := range obj.sortedKeys() { + if other.Get(node.key) == nil { + r.insert(node.key, node.value, false) } - }) + } return r } @@ -2229,38 +2359,31 @@ func (obj *object) Iter(f func(*Term, *Term) error) error { // true, iteration stops and Until returns true. Otherwise, return // false. func (obj *object) Until(f func(*Term, *Term) bool) bool { - err := obj.Iter(func(k, v *Term) error { - if f(k, v) { - return errStop + for _, node := range obj.sortedKeys() { + if f(node.key, node.value) { + return true } - return nil - }) - return err != nil + } + return false } // Foreach calls f for each key-value pair in the object. func (obj *object) Foreach(f func(*Term, *Term)) { - _ = obj.Iter(func(k, v *Term) error { - f(k, v) - return nil - }) // ignore error + for _, node := range obj.sortedKeys() { + f(node.key, node.value) + } } // Map returns a new Object constructed by mapping each element in the object // using the function f. func (obj *object) Map(f func(*Term, *Term) (*Term, *Term, error)) (Object, error) { cpy := newobject(obj.Len()) - err := obj.Iter(func(k, v *Term) error { - var err error - k, v, err = f(k, v) + for _, node := range obj.sortedKeys() { + k, v, err := f(node.key, node.value) if err != nil { - return err + return nil, err } - cpy.insert(k, v) - return nil - }) - if err != nil { - return nil, err + cpy.insert(k, v, false) } return cpy, nil } @@ -2294,7 +2417,7 @@ func (obj *object) MarshalJSON() ([]byte, error) { // overlapping keys between obj and other, the values of associated with the keys are merged. Only // objects can be merged with other objects. If the values cannot be merged, the second turn value // will be false. -func (obj object) Merge(other Object) (Object, bool) { +func (obj *object) Merge(other Object) (Object, bool) { return obj.MergeWith(other, func(v1, v2 *Term) (*Term, bool) { obj1, ok1 := v1.Value.(Object) obj2, ok2 := v2.Value.(Object) @@ -2313,7 +2436,7 @@ func (obj object) Merge(other Object) (Object, bool) { // If there are overlapping keys between obj and other, the conflictResolver // is called. The conflictResolver can return a merged value and a boolean // indicating if the merge has failed and should stop. -func (obj object) MergeWith(other Object, conflictResolver func(v1, v2 *Term) (*Term, bool)) (Object, bool) { +func (obj *object) MergeWith(other Object, conflictResolver func(v1, v2 *Term) (*Term, bool)) (Object, bool) { result := NewObject() stop := obj.Until(func(k, v *Term) bool { v2 := other.Get(k) @@ -2356,24 +2479,30 @@ func (obj *object) Filter(filter Object) (Object, error) { } // Len returns the number of elements in the object. -func (obj object) Len() int { +func (obj *object) Len() int { return len(obj.keys) } -func (obj object) String() string { - var b strings.Builder - b.WriteRune('{') +func (obj *object) String() string { + sb := sbPool.Get().(*strings.Builder) + sb.Reset() + sb.Grow(obj.Len() * 32) + + defer sbPool.Put(sb) + + sb.WriteRune('{') for i, elem := range obj.sortedKeys() { if i > 0 { - b.WriteString(", ") + sb.WriteString(", ") } - b.WriteString(elem.key.String()) - b.WriteString(": ") - b.WriteString(elem.value.String()) + sb.WriteString(elem.key.String()) + sb.WriteString(": ") + sb.WriteString(elem.value.String()) } - b.WriteRune('}') - return b.String() + sb.WriteRune('}') + + return sb.String() } func (obj *object) get(k *Term) *objectElem { @@ -2389,10 +2518,10 @@ func (obj *object) get(k *Term) *objectElem { case Null, Boolean, String, Var: equal = func(y Value) bool { return x == y } case Number: - if xi, err := json.Number(x).Int64(); err == nil { + if xi, ok := x.Int64(); ok { equal = func(y Value) bool { if y, ok := y.(Number); ok { - if yi, err := json.Number(y).Int64(); err == nil { + if yi, ok := y.Int64(); ok { return xi == yi } } @@ -2466,7 +2595,7 @@ func (obj *object) get(k *Term) *objectElem { // NOTE(philipc): We assume a many-readers, single-writer model here. // This method should NOT be used concurrently, or else we risk data races. -func (obj *object) insert(k, v *Term) { +func (obj *object) insert(k, v *Term, resetSortGuard bool) { hash := k.Hash() head := obj.elems[hash] // This `equal` utility is duplicated and manually inlined a number of @@ -2560,6 +2689,8 @@ func (obj *object) insert(k, v *Term) { } curr.value = v + + obj.rehash() return } } @@ -2571,9 +2702,16 @@ func (obj *object) insert(k, v *Term) { obj.elems[hash] = elem // O(1) insertion, but we'll have to re-sort the keys later. obj.keys = append(obj.keys, elem) - // Reset the sync.Once instance. - // See https://github.com/golang/go/issues/25955 for why we do it this way. - obj.sortGuard = new(sync.Once) + + if resetSortGuard { + // Reset the sync.Once instance. + // See https://github.com/golang/go/issues/25955 for why we do it this way. + // Note that this will always be the case when external code calls insert via + // Add, or otherwise. Internal code may however benefit from not having to + // re-create this when it's known not to be needed. + obj.sortGuard = sync.Once{} + } + obj.hash += hash + v.Hash() if k.IsGround() { @@ -2584,8 +2722,21 @@ func (obj *object) insert(k, v *Term) { } } +func (obj *object) rehash() { + // obj.keys is considered truth, from which obj.hash and obj.elems are recalculated. + + obj.hash = 0 + obj.elems = make(map[int]*objectElem, len(obj.keys)) + + for _, elem := range obj.keys { + hash := elem.key.Hash() + obj.hash += hash + elem.value.Hash() + obj.elems[hash] = elem + } +} + func filterObject(o Value, filter Value) (Value, error) { - if filter.Compare(Null{}) == 0 { + if (Null{}).Equal(filter) { return o, nil } @@ -2611,18 +2762,17 @@ func filterObject(o Value, filter Value) (Value, error) { } return values, nil case Set: - values := NewSet() - err := v.Iter(func(t *Term) error { + terms := make([]*Term, 0, v.Len()) + for _, t := range v.Slice() { if filteredObj.Get(t) != nil { filteredValue, err := filterObject(t.Value, filteredObj.Get(t).Value) if err != nil { - return err + return nil, err } - values.Add(NewTerm(filteredValue)) + terms = append(terms, NewTerm(filteredValue)) } - return nil - }) - return values, err + } + return NewSet(terms...), nil case *object: values := NewObject() @@ -2904,12 +3054,16 @@ func (c Call) String() string { func termSliceCopy(a []*Term) []*Term { cpy := make([]*Term, len(a)) - for i := range a { - cpy[i] = a[i].Copy() - } + termSliceCopyTo(a, cpy) return cpy } +func termSliceCopyTo(src, dst []*Term) { + for i := range src { + dst[i] = src[i].Copy() + } +} + func termSliceEqual(a, b []*Term) bool { if len(a) == len(b) { for i := range a { @@ -3134,7 +3288,7 @@ func unmarshalValue(d map[string]interface{}) (Value, error) { v := d["value"] switch d["type"] { case "null": - return Null{}, nil + return NullValue, nil case "boolean": if b, ok := v.(bool); ok { return Boolean(b), nil @@ -3161,11 +3315,7 @@ func unmarshalValue(d map[string]interface{}) (Value, error) { } case "set": if s, err := unmarshalTermSliceValue(d); err == nil { - set := NewSet() - for _, x := range s { - set.Add(x) - } - return set, nil + return NewSet(s...), nil } case "object": if s, ok := v.([]interface{}); ok { diff --git a/vendor/github.com/open-policy-agent/opa/ast/transform.go b/vendor/github.com/open-policy-agent/opa/v1/ast/transform.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/ast/transform.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/transform.go diff --git a/vendor/github.com/open-policy-agent/opa/ast/unify.go b/vendor/github.com/open-policy-agent/opa/v1/ast/unify.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/ast/unify.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/unify.go diff --git a/vendor/github.com/open-policy-agent/opa/ast/varset.go b/vendor/github.com/open-policy-agent/opa/v1/ast/varset.go similarity index 88% rename from vendor/github.com/open-policy-agent/opa/ast/varset.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/varset.go index 14f531494b..d51abbdae6 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/varset.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/varset.go @@ -6,7 +6,9 @@ package ast import ( "fmt" - "sort" + "slices" + + "github.com/open-policy-agent/opa/v1/util" ) // VarSet represents a set of variables. @@ -77,9 +79,7 @@ func (s VarSet) Sorted() []Var { for v := range s { sorted = append(sorted, v) } - sort.Slice(sorted, func(i, j int) bool { - return sorted[i].Compare(sorted[j]) < 0 - }) + slices.SortFunc(sorted, VarCompare) return sorted } @@ -91,10 +91,5 @@ func (s VarSet) Update(vs VarSet) { } func (s VarSet) String() string { - tmp := make([]string, 0, len(s)) - for v := range s { - tmp = append(tmp, string(v)) - } - sort.Strings(tmp) - return fmt.Sprintf("%v", tmp) + return fmt.Sprintf("%v", util.KeysSorted(s)) } diff --git a/vendor/github.com/open-policy-agent/opa/ast/version_index.json b/vendor/github.com/open-policy-agent/opa/v1/ast/version_index.json similarity index 99% rename from vendor/github.com/open-policy-agent/opa/ast/version_index.json rename to vendor/github.com/open-policy-agent/opa/v1/ast/version_index.json index 718df220f9..b888b3e028 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/version_index.json +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/version_index.json @@ -1395,6 +1395,13 @@ } }, "features": { + "rego_v1": { + "Major": 1, + "Minor": 0, + "Patch": 0, + "PreRelease": "", + "Metadata": "" + }, "rego_v1_import": { "Major": 0, "Minor": 59, diff --git a/vendor/github.com/open-policy-agent/opa/ast/visit.go b/vendor/github.com/open-policy-agent/opa/v1/ast/visit.go similarity index 99% rename from vendor/github.com/open-policy-agent/opa/ast/visit.go rename to vendor/github.com/open-policy-agent/opa/v1/ast/visit.go index d83c31149e..91cfa208e2 100644 --- a/vendor/github.com/open-policy-agent/opa/ast/visit.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ast/visit.go @@ -357,14 +357,14 @@ func (vis *GenericVisitor) Walk(x interface{}) { vis.Walk(x.Get(k)) }) case Object: - x.Foreach(func(k, _ *Term) { + for _, k := range x.Keys() { vis.Walk(k) vis.Walk(x.Get(k)) - }) + } case *Array: - x.Foreach(func(t *Term) { - vis.Walk(t) - }) + for i := 0; i < x.Len(); i++ { + vis.Walk(x.Elem(i)) + } case Set: xSlice := x.Slice() for i := range xSlice { diff --git a/vendor/github.com/open-policy-agent/opa/bundle/bundle.go b/vendor/github.com/open-policy-agent/opa/v1/bundle/bundle.go similarity index 96% rename from vendor/github.com/open-policy-agent/opa/bundle/bundle.go rename to vendor/github.com/open-policy-agent/opa/v1/bundle/bundle.go index 816f5535fc..12f8bfb32c 100644 --- a/vendor/github.com/open-policy-agent/opa/bundle/bundle.go +++ b/vendor/github.com/open-policy-agent/opa/v1/bundle/bundle.go @@ -22,13 +22,13 @@ import ( "strings" "github.com/gobwas/glob" - "github.com/open-policy-agent/opa/ast" - astJSON "github.com/open-policy-agent/opa/ast/json" - "github.com/open-policy-agent/opa/format" "github.com/open-policy-agent/opa/internal/file/archive" "github.com/open-policy-agent/opa/internal/merge" - "github.com/open-policy-agent/opa/metrics" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/ast" + astJSON "github.com/open-policy-agent/opa/v1/ast/json" + "github.com/open-policy-agent/opa/v1/format" + "github.com/open-policy-agent/opa/v1/metrics" + "github.com/open-policy-agent/opa/v1/util" ) // Common file extensions and file names. @@ -67,8 +67,9 @@ type Bundle struct { // Raw contains raw bytes representing the bundle's content type Raw struct { - Path string - Value []byte + Path string + Value []byte + module *ModuleFile } // Patch contains an array of objects wherein each object represents the patch operation to be @@ -200,7 +201,10 @@ func (m Manifest) Equal(other Manifest) bool { if m.RegoVersion != nil && other.RegoVersion != nil && *m.RegoVersion != *other.RegoVersion { return false } - if !reflect.DeepEqual(m.FileRegoVersions, other.FileRegoVersions) { + + // If both are nil, or both are empty, we consider them equal. + if !(len(m.FileRegoVersions) == 0 && len(other.FileRegoVersions) == 0) && + !reflect.DeepEqual(m.FileRegoVersions, other.FileRegoVersions) { return false } @@ -441,7 +445,6 @@ type Reader struct { verificationConfig *VerificationConfig skipVerify bool processAnnotations bool - jsonOptions *astJSON.Options capabilities *ast.Capabilities files map[string]FileInfo // files in the bundle signature payload sizeLimitBytes int64 @@ -514,9 +517,11 @@ func (r *Reader) WithCapabilities(caps *ast.Capabilities) *Reader { return r } -// WithJSONOptions sets the JSONOptions to use when parsing policy files -func (r *Reader) WithJSONOptions(opts *astJSON.Options) *Reader { - r.jsonOptions = opts +// WithJSONOptions sets the JSON options on the parser (now a no-op). +// +// Deprecated: Use SetOptions in the json package instead, where a longer description +// of why this is deprecated also can be found. +func (r *Reader) WithJSONOptions(*astJSON.Options) *Reader { return r } @@ -568,7 +573,6 @@ func (r *Reader) ParserOptions() ast.ParserOptions { return ast.ParserOptions{ ProcessAnnotation: r.processAnnotations, Capabilities: r.capabilities, - JSONOptions: r.jsonOptions, RegoVersion: r.regoVersion, } } @@ -630,15 +634,6 @@ func (r *Reader) Read() (Bundle, error) { fullPath := r.fullPath(path) bs := buf.Bytes() - if r.lazyLoadingMode { - p := fullPath - if r.name != "" { - p = modulePathWithPrefix(r.name, fullPath) - } - - raw = append(raw, Raw{Path: p, Value: bs}) - } - // Modules are parsed after we've had a chance to read the manifest mf := ModuleFile{ URL: f.URL(), @@ -647,6 +642,15 @@ func (r *Reader) Read() (Bundle, error) { Raw: bs, } modules = append(modules, mf) + + if r.lazyLoadingMode { + p := fullPath + if r.name != "" { + p = modulePathWithPrefix(r.name, fullPath) + } + + raw = append(raw, Raw{Path: p, Value: bs, module: &mf}) + } } else if filepath.Base(path) == WasmFile { bundle.WasmModules = append(bundle.WasmModules, WasmModuleFile{ URL: f.URL(), @@ -708,10 +712,10 @@ func (r *Reader) Read() (Bundle, error) { // Parse modules popts := r.ParserOptions() - popts.RegoVersion = bundle.RegoVersion(popts.RegoVersion) + popts.RegoVersion = bundle.RegoVersion(popts.EffectiveRegoVersion()) for _, mf := range modules { modulePopts := popts - if modulePopts.RegoVersion, err = bundle.RegoVersionForFile(mf.RelativePath, popts.RegoVersion); err != nil { + if modulePopts.RegoVersion, err = bundle.RegoVersionForFile(mf.RelativePath, popts.EffectiveRegoVersion()); err != nil { return bundle, err } r.metrics.Timer(metrics.RegoModuleParse).Start() @@ -1079,9 +1083,9 @@ func hashBundleFiles(hash SignatureHasher, b *Bundle) ([]FileInfo, error) { } // FormatModules formats Rego modules -// Modules will be formatted to comply with rego-v0, but Rego compatibility of individual parsed modules will be respected (e.g. if 'rego.v1' is imported). +// Modules will be formatted to comply with [ast.DefaultRegoVersion], but Rego compatibility of individual parsed modules will be respected (e.g. if 'rego.v1' is imported). func (b *Bundle) FormatModules(useModulePath bool) error { - return b.FormatModulesForRegoVersion(ast.RegoV0, true, useModulePath) + return b.FormatModulesForRegoVersion(ast.DefaultRegoVersion, true, useModulePath) } // FormatModulesForRegoVersion formats Rego modules to comply with a given Rego version @@ -1092,6 +1096,9 @@ func (b *Bundle) FormatModulesForRegoVersion(version ast.RegoVersion, preserveMo opts := format.Opts{} if preserveModuleRegoVersion { opts.RegoVersion = module.Parsed.RegoVersion() + opts.ParserOptions = &ast.ParserOptions{ + RegoVersion: opts.RegoVersion, + } } else { opts.RegoVersion = version } @@ -1197,6 +1204,10 @@ func (b *Bundle) SetRegoVersion(v ast.RegoVersion) { // If there is no defined version for the given path, the default version def is returned. // If the version does not correspond to ast.RegoV0 or ast.RegoV1, an error is returned. func (b *Bundle) RegoVersionForFile(path string, def ast.RegoVersion) (ast.RegoVersion, error) { + if def == ast.RegoUndefined { + def = ast.DefaultRegoVersion + } + version, err := b.Manifest.numericRegoVersionForFile(path) if err != nil { return def, err @@ -1210,6 +1221,19 @@ func (b *Bundle) RegoVersionForFile(path string, def ast.RegoVersion) (ast.RegoV return def, fmt.Errorf("unknown bundle rego-version %d for file '%s'", *version, path) } +func (m *Manifest) RegoVersionForFile(path string) (ast.RegoVersion, error) { + v, err := m.numericRegoVersionForFile(path) + if err != nil { + return ast.RegoUndefined, err + } + + if v == nil { + return ast.RegoUndefined, nil + } + + return ast.RegoVersionFromInt(*v), nil +} + func (m *Manifest) numericRegoVersionForFile(path string) (*int, error) { var version *int @@ -1387,7 +1411,7 @@ func mktree(path []string, value interface{}) (map[string]interface{}, error) { // will have an empty revision except in the special case where a single bundle is provided // (and in that case the bundle is just returned unmodified.) func Merge(bundles []*Bundle) (*Bundle, error) { - return MergeWithRegoVersion(bundles, ast.RegoV0, false) + return MergeWithRegoVersion(bundles, ast.DefaultRegoVersion, false) } // MergeWithRegoVersion creates a merged bundle from the provided bundles, similar to Merge. @@ -1404,6 +1428,10 @@ func MergeWithRegoVersion(bundles []*Bundle, regoVersion ast.RegoVersion, usePat return nil, errors.New("expected at least one bundle") } + if regoVersion == ast.RegoUndefined { + regoVersion = ast.DefaultRegoVersion + } + if len(bundles) == 1 { result := bundles[0] // We respect the bundle rego-version, defaulting to the provided rego version if not set. diff --git a/vendor/github.com/open-policy-agent/opa/bundle/file.go b/vendor/github.com/open-policy-agent/opa/v1/bundle/file.go similarity index 95% rename from vendor/github.com/open-policy-agent/opa/bundle/file.go rename to vendor/github.com/open-policy-agent/opa/v1/bundle/file.go index 80b1a87eb1..12e159254c 100644 --- a/vendor/github.com/open-policy-agent/opa/bundle/file.go +++ b/vendor/github.com/open-policy-agent/opa/v1/bundle/file.go @@ -13,9 +13,9 @@ import ( "strings" "sync" - "github.com/open-policy-agent/opa/loader/filter" + "github.com/open-policy-agent/opa/v1/loader/filter" - "github.com/open-policy-agent/opa/storage" + "github.com/open-policy-agent/opa/v1/storage" ) const maxSizeLimitBytesErrMsg = "bundle file %s size (%d bytes) exceeds configured size_limit_bytes (%d bytes)" @@ -438,15 +438,11 @@ func (it *iterator) Next() (*storage.Update, error) { for _, item := range it.raw { f := file{name: item.Path} - fpath := strings.TrimLeft(normalizePath(filepath.Dir(f.name)), "/.") - if strings.HasSuffix(f.name, RegoExt) { - fpath = strings.Trim(normalizePath(f.name), "/") + p, err := getFileStoragePath(f.name) + if err != nil { + return nil, err } - p, ok := storage.ParsePathEscaped("/" + fpath) - if !ok { - return nil, fmt.Errorf("storage path invalid: %v", f.name) - } f.path = p f.raw = item.Value @@ -506,3 +502,16 @@ func getdepth(path string, isDir bool) int { basePath := strings.Trim(filepath.Dir(filepath.ToSlash(path)), "/") return len(strings.Split(basePath, "/")) } + +func getFileStoragePath(path string) (storage.Path, error) { + fpath := strings.TrimLeft(normalizePath(filepath.Dir(path)), "/.") + if strings.HasSuffix(path, RegoExt) { + fpath = strings.Trim(normalizePath(path), "/") + } + + p, ok := storage.ParsePathEscaped("/" + fpath) + if !ok { + return nil, fmt.Errorf("storage path invalid: %v", path) + } + return p, nil +} diff --git a/vendor/github.com/open-policy-agent/opa/bundle/filefs.go b/vendor/github.com/open-policy-agent/opa/v1/bundle/filefs.go similarity index 98% rename from vendor/github.com/open-policy-agent/opa/bundle/filefs.go rename to vendor/github.com/open-policy-agent/opa/v1/bundle/filefs.go index a3a0dbf204..7ab3de989c 100644 --- a/vendor/github.com/open-policy-agent/opa/bundle/filefs.go +++ b/vendor/github.com/open-policy-agent/opa/v1/bundle/filefs.go @@ -10,7 +10,7 @@ import ( "path/filepath" "sync" - "github.com/open-policy-agent/opa/loader/filter" + "github.com/open-policy-agent/opa/v1/loader/filter" ) const ( diff --git a/vendor/github.com/open-policy-agent/opa/bundle/hash.go b/vendor/github.com/open-policy-agent/opa/v1/bundle/hash.go similarity index 96% rename from vendor/github.com/open-policy-agent/opa/bundle/hash.go rename to vendor/github.com/open-policy-agent/opa/v1/bundle/hash.go index 021801bb0a..ab6fcd0f38 100644 --- a/vendor/github.com/open-policy-agent/opa/bundle/hash.go +++ b/vendor/github.com/open-policy-agent/opa/v1/bundle/hash.go @@ -14,8 +14,9 @@ import ( "fmt" "hash" "io" - "sort" "strings" + + "github.com/open-policy-agent/opa/v1/util" ) // HashingAlgorithm represents a subset of hashing algorithms implemented in Go @@ -97,13 +98,7 @@ func walk(v interface{}, h io.Writer) { case map[string]interface{}: _, _ = h.Write([]byte("{")) - var keys []string - for k := range x { - keys = append(keys, k) - } - sort.Strings(keys) - - for i, key := range keys { + for i, key := range util.KeysSorted(x) { if i > 0 { _, _ = h.Write([]byte(",")) } diff --git a/vendor/github.com/open-policy-agent/opa/bundle/keys.go b/vendor/github.com/open-policy-agent/opa/v1/bundle/keys.go similarity index 97% rename from vendor/github.com/open-policy-agent/opa/bundle/keys.go rename to vendor/github.com/open-policy-agent/opa/v1/bundle/keys.go index 810bee4b72..aad30a675a 100644 --- a/vendor/github.com/open-policy-agent/opa/bundle/keys.go +++ b/vendor/github.com/open-policy-agent/opa/v1/bundle/keys.go @@ -12,9 +12,9 @@ import ( "github.com/open-policy-agent/opa/internal/jwx/jwa" "github.com/open-policy-agent/opa/internal/jwx/jws/sign" - "github.com/open-policy-agent/opa/keys" + "github.com/open-policy-agent/opa/v1/keys" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/util" ) const ( diff --git a/vendor/github.com/open-policy-agent/opa/bundle/sign.go b/vendor/github.com/open-policy-agent/opa/v1/bundle/sign.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/bundle/sign.go rename to vendor/github.com/open-policy-agent/opa/v1/bundle/sign.go diff --git a/vendor/github.com/open-policy-agent/opa/bundle/store.go b/vendor/github.com/open-policy-agent/opa/v1/bundle/store.go similarity index 83% rename from vendor/github.com/open-policy-agent/opa/bundle/store.go rename to vendor/github.com/open-policy-agent/opa/v1/bundle/store.go index 45bcf6e559..e77c052d9b 100644 --- a/vendor/github.com/open-policy-agent/opa/bundle/store.go +++ b/vendor/github.com/open-policy-agent/opa/v1/bundle/store.go @@ -12,17 +12,19 @@ import ( "path/filepath" "strings" - "github.com/open-policy-agent/opa/ast" iCompiler "github.com/open-policy-agent/opa/internal/compiler" "github.com/open-policy-agent/opa/internal/json/patch" - "github.com/open-policy-agent/opa/metrics" - "github.com/open-policy-agent/opa/storage" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/metrics" + "github.com/open-policy-agent/opa/v1/storage" + "github.com/open-policy-agent/opa/v1/util" ) // BundlesBasePath is the storage path used for storing bundle metadata var BundlesBasePath = storage.MustParsePath("/system/bundles") +var ModulesInfoBasePath = storage.MustParsePath("/system/modules") + // Note: As needed these helpers could be memoized. // ManifestStoragePath is the storage path used for the given named bundle manifest. @@ -59,9 +61,33 @@ func metadataPath(name string) storage.Path { return append(BundlesBasePath, name, "manifest", "metadata") } +func moduleRegoVersionPath(id string) storage.Path { + return append(ModulesInfoBasePath, strings.Trim(id, "/"), "rego_version") +} + +func moduleInfoPath(id string) storage.Path { + return append(ModulesInfoBasePath, strings.Trim(id, "/")) +} + +func read(ctx context.Context, store storage.Store, txn storage.Transaction, path storage.Path) (interface{}, error) { + value, err := store.Read(ctx, txn, path) + if err != nil { + return nil, err + } + + if astValue, ok := value.(ast.Value); ok { + value, err = ast.JSON(astValue) + if err != nil { + return nil, err + } + } + + return value, nil +} + // ReadBundleNamesFromStore will return a list of bundle names which have had their metadata stored. func ReadBundleNamesFromStore(ctx context.Context, store storage.Store, txn storage.Transaction) ([]string, error) { - value, err := store.Read(ctx, txn, BundlesBasePath) + value, err := read(ctx, store, txn, BundlesBasePath) if err != nil { return nil, err } @@ -150,10 +176,20 @@ func eraseWasmModulesFromStore(ctx context.Context, store storage.Store, txn sto return suppressNotFound(err) } +func eraseModuleRegoVersionsFromStore(ctx context.Context, store storage.Store, txn storage.Transaction, modules []string) error { + for _, module := range modules { + err := store.Write(ctx, txn, storage.RemoveOp, moduleInfoPath(module), nil) + if err := suppressNotFound(err); err != nil { + return err + } + } + return nil +} + // ReadWasmMetadataFromStore will read Wasm module resolver metadata from the store. func ReadWasmMetadataFromStore(ctx context.Context, store storage.Store, txn storage.Transaction, name string) ([]WasmResolver, error) { path := wasmEntrypointsPath(name) - value, err := store.Read(ctx, txn, path) + value, err := read(ctx, store, txn, path) if err != nil { return nil, err } @@ -176,7 +212,7 @@ func ReadWasmMetadataFromStore(ctx context.Context, store storage.Store, txn sto // ReadWasmModulesFromStore will write Wasm module resolver metadata from the store. func ReadWasmModulesFromStore(ctx context.Context, store storage.Store, txn storage.Transaction, name string) (map[string][]byte, error) { path := wasmModulePath(name) - value, err := store.Read(ctx, txn, path) + value, err := read(ctx, store, txn, path) if err != nil { return nil, err } @@ -205,7 +241,7 @@ func ReadWasmModulesFromStore(ctx context.Context, store storage.Store, txn stor // If the bundle is not activated, this function will return // storage NotFound error. func ReadBundleRootsFromStore(ctx context.Context, store storage.Store, txn storage.Transaction, name string) ([]string, error) { - value, err := store.Read(ctx, txn, rootsPath(name)) + value, err := read(ctx, store, txn, rootsPath(name)) if err != nil { return nil, err } @@ -235,7 +271,7 @@ func ReadBundleRevisionFromStore(ctx context.Context, store storage.Store, txn s } func readRevisionFromStore(ctx context.Context, store storage.Store, txn storage.Transaction, path storage.Path) (string, error) { - value, err := store.Read(ctx, txn, path) + value, err := read(ctx, store, txn, path) if err != nil { return "", err } @@ -256,7 +292,7 @@ func ReadBundleMetadataFromStore(ctx context.Context, store storage.Store, txn s } func readMetadataFromStore(ctx context.Context, store storage.Store, txn storage.Transaction, path storage.Path) (map[string]interface{}, error) { - value, err := store.Read(ctx, txn, path) + value, err := read(ctx, store, txn, path) if err != nil { return nil, suppressNotFound(err) } @@ -277,7 +313,7 @@ func ReadBundleEtagFromStore(ctx context.Context, store storage.Store, txn stora } func readEtagFromStore(ctx context.Context, store storage.Store, txn storage.Transaction, path storage.Path) (string, error) { - value, err := store.Read(ctx, txn, path) + value, err := read(ctx, store, txn, path) if err != nil { return "", err } @@ -459,7 +495,7 @@ func activateBundles(opts *ActivateOpts) error { return err } - if err := writeDataAndModules(opts.Ctx, opts.Store, opts.Txn, opts.TxnCtx, snapshotBundles, opts.legacy); err != nil { + if err := writeDataAndModules(opts.Ctx, opts.Store, opts.Txn, opts.TxnCtx, snapshotBundles, opts.legacy, opts.ParserOptions.RegoVersion); err != nil { return err } @@ -544,14 +580,7 @@ func activateDeltaBundles(opts *ActivateOpts, bundles map[string]*Bundle) error return err } - bs, err := json.Marshal(value) - if err != nil { - return fmt.Errorf("corrupt manifest data: %w", err) - } - - var manifest Manifest - - err = util.UnmarshalJSON(bs, &manifest) + manifest, err := valueToManifest(value) if err != nil { return fmt.Errorf("corrupt manifest data: %w", err) } @@ -585,6 +614,30 @@ func activateDeltaBundles(opts *ActivateOpts, bundles map[string]*Bundle) error return nil } +func valueToManifest(v interface{}) (Manifest, error) { + if astV, ok := v.(ast.Value); ok { + var err error + v, err = ast.JSON(astV) + if err != nil { + return Manifest{}, err + } + } + + var manifest Manifest + + bs, err := json.Marshal(v) + if err != nil { + return Manifest{}, err + } + + err = util.UnmarshalJSON(bs, &manifest) + if err != nil { + return Manifest{}, err + } + + return manifest, nil +} + // erase bundles by name and roots. This will clear all policies and data at its roots and remove its // manifest from storage. func eraseBundles(ctx context.Context, store storage.Store, txn storage.Transaction, parserOpts ast.ParserOptions, names map[string]struct{}, roots map[string]struct{}) (map[string]*ast.Module, error) { @@ -593,7 +646,7 @@ func eraseBundles(ctx context.Context, store storage.Store, txn storage.Transact return nil, err } - remaining, err := erasePolicies(ctx, store, txn, parserOpts, roots) + remaining, removed, err := erasePolicies(ctx, store, txn, parserOpts, roots) if err != nil { return nil, err } @@ -616,6 +669,11 @@ func eraseBundles(ctx context.Context, store storage.Store, txn storage.Transact } } + err = eraseModuleRegoVersionsFromStore(ctx, store, txn, removed) + if err != nil { + return nil, err + } + return remaining, nil } @@ -635,44 +693,103 @@ func eraseData(ctx context.Context, store storage.Store, txn storage.Transaction return nil } -func erasePolicies(ctx context.Context, store storage.Store, txn storage.Transaction, parserOpts ast.ParserOptions, roots map[string]struct{}) (map[string]*ast.Module, error) { +type moduleInfo struct { + RegoVersion ast.RegoVersion `json:"rego_version"` +} + +func readModuleInfoFromStore(ctx context.Context, store storage.Store, txn storage.Transaction) (map[string]moduleInfo, error) { + value, err := read(ctx, store, txn, ModulesInfoBasePath) + if suppressNotFound(err) != nil { + return nil, err + } + + if value == nil { + return nil, nil + } + + if m, ok := value.(map[string]any); ok { + versions := make(map[string]moduleInfo, len(m)) + + for k, v := range m { + if m0, ok := v.(map[string]any); ok { + if ver, ok := m0["rego_version"]; ok { + if vs, ok := ver.(json.Number); ok { + i, err := vs.Int64() + if err != nil { + return nil, fmt.Errorf("corrupt rego version") + } + versions[k] = moduleInfo{RegoVersion: ast.RegoVersionFromInt(int(i))} + } + } + } + } + return versions, nil + } + + return nil, fmt.Errorf("corrupt rego version") +} + +func erasePolicies(ctx context.Context, store storage.Store, txn storage.Transaction, parserOpts ast.ParserOptions, roots map[string]struct{}) (map[string]*ast.Module, []string, error) { ids, err := store.ListPolicies(ctx, txn) if err != nil { - return nil, err + return nil, nil, err + } + + modulesInfo, err := readModuleInfoFromStore(ctx, store, txn) + if err != nil { + return nil, nil, fmt.Errorf("failed to read module info from store: %w", err) + } + + getRegoVersion := func(modId string) (ast.RegoVersion, bool) { + info, ok := modulesInfo[modId] + if !ok { + return ast.RegoUndefined, false + } + return info.RegoVersion, true } remaining := map[string]*ast.Module{} + var removed []string for _, id := range ids { bs, err := store.GetPolicy(ctx, txn, id) if err != nil { - return nil, err + return nil, nil, err + } + + parserOptsCpy := parserOpts + if regoVersion, ok := getRegoVersion(id); ok { + parserOptsCpy.RegoVersion = regoVersion } - module, err := ast.ParseModuleWithOpts(id, string(bs), parserOpts) + + module, err := ast.ParseModuleWithOpts(id, string(bs), parserOptsCpy) if err != nil { - return nil, err + return nil, nil, err } path, err := module.Package.Path.Ptr() if err != nil { - return nil, err + return nil, nil, err } deleted := false for root := range roots { if RootPathsContain([]string{root}, path) { if err := store.DeletePolicy(ctx, txn, id); err != nil { - return nil, err + return nil, nil, err } deleted = true break } } - if !deleted { + + if deleted { + removed = append(removed, id) + } else { remaining[id] = module } } - return remaining, nil + return remaining, removed, nil } func writeManifestToStore(opts *ActivateOpts, name string, manifest Manifest) error { @@ -699,7 +816,31 @@ func writeEtagToStore(opts *ActivateOpts, name, etag string) error { return nil } -func writeDataAndModules(ctx context.Context, store storage.Store, txn storage.Transaction, txnCtx *storage.Context, bundles map[string]*Bundle, legacy bool) error { +func writeModuleRegoVersionToStore(ctx context.Context, store storage.Store, txn storage.Transaction, b *Bundle, + mf ModuleFile, storagePath string, runtimeRegoVersion ast.RegoVersion) error { + + var regoVersion ast.RegoVersion + if mf.Parsed != nil { + regoVersion = mf.Parsed.RegoVersion() + } + + if regoVersion == ast.RegoUndefined { + var err error + regoVersion, err = b.RegoVersionForFile(mf.Path, ast.RegoUndefined) + if err != nil { + return fmt.Errorf("failed to get rego version for module '%s' in bundle: %w", mf.Path, err) + } + } + + if regoVersion != ast.RegoUndefined && regoVersion != runtimeRegoVersion { + if err := write(ctx, store, txn, moduleRegoVersionPath(storagePath), regoVersion.Int()); err != nil { + return fmt.Errorf("failed to write rego version for module '%s': %w", storagePath, err) + } + } + return nil +} + +func writeDataAndModules(ctx context.Context, store storage.Store, txn storage.Transaction, txnCtx *storage.Context, bundles map[string]*Bundle, legacy bool, runtimeRegoVersion ast.RegoVersion) error { params := storage.WriteParams params.Context = txnCtx @@ -725,6 +866,10 @@ func writeDataAndModules(ctx context.Context, store storage.Store, txn storage.T if err := store.UpsertPolicy(ctx, txn, path, mf.Raw); err != nil { return err } + + if err := writeModuleRegoVersionToStore(ctx, store, txn, b, mf, path, runtimeRegoVersion); err != nil { + return err + } } } else { params.BasePaths = *b.Manifest.Roots @@ -733,6 +878,23 @@ func writeDataAndModules(ctx context.Context, store storage.Store, txn storage.T if err != nil { return fmt.Errorf("store truncate failed for bundle '%s': %v", name, err) } + + for _, f := range b.Raw { + if strings.HasSuffix(f.Path, RegoExt) { + p, err := getFileStoragePath(f.Path) + if err != nil { + return fmt.Errorf("failed get storage path for module '%s' in bundle '%s': %w", f.Path, name, err) + } + + if m := f.module; m != nil { + // 'f.module.Path' contains the module's path as it relates to the bundle root, and can be used for looking up the rego-version. + // 'f.Path' can differ, based on how the bundle reader was initialized. + if err := writeModuleRegoVersionToStore(ctx, store, txn, b, *m, p.String(), runtimeRegoVersion); err != nil { + return err + } + } + } + } } } diff --git a/vendor/github.com/open-policy-agent/opa/bundle/verify.go b/vendor/github.com/open-policy-agent/opa/v1/bundle/verify.go similarity index 99% rename from vendor/github.com/open-policy-agent/opa/bundle/verify.go rename to vendor/github.com/open-policy-agent/opa/v1/bundle/verify.go index e85be835be..2a4bb02c05 100644 --- a/vendor/github.com/open-policy-agent/opa/bundle/verify.go +++ b/vendor/github.com/open-policy-agent/opa/v1/bundle/verify.go @@ -15,7 +15,7 @@ import ( "github.com/open-policy-agent/opa/internal/jwx/jwa" "github.com/open-policy-agent/opa/internal/jwx/jws" "github.com/open-policy-agent/opa/internal/jwx/jws/verify" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/util" ) const defaultVerifierID = "_default" diff --git a/vendor/github.com/open-policy-agent/opa/v1/capabilities/capabilities.go b/vendor/github.com/open-policy-agent/opa/v1/capabilities/capabilities.go new file mode 100644 index 0000000000..5b0bb1ea52 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/v1/capabilities/capabilities.go @@ -0,0 +1,18 @@ +// Copyright 2021 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +//go:build go1.16 +// +build go1.16 + +package capabilities + +import ( + v0 "github.com/open-policy-agent/opa/capabilities" +) + +// FS contains the embedded capabilities/ directory of the built version, +// which has all the capabilities of previous versions: +// "v0.18.0.json" contains the capabilities JSON of version v0.18.0, etc + +var FS = v0.FS diff --git a/vendor/github.com/open-policy-agent/opa/config/config.go b/vendor/github.com/open-policy-agent/opa/v1/config/config.go similarity index 98% rename from vendor/github.com/open-policy-agent/opa/config/config.go rename to vendor/github.com/open-policy-agent/opa/v1/config/config.go index 87ab109113..09adb556f8 100644 --- a/vendor/github.com/open-policy-agent/opa/config/config.go +++ b/vendor/github.com/open-policy-agent/opa/v1/config/config.go @@ -14,10 +14,10 @@ import ( "sort" "strings" - "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/internal/ref" - "github.com/open-policy-agent/opa/util" - "github.com/open-policy-agent/opa/version" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/util" + "github.com/open-policy-agent/opa/v1/version" ) // Config represents the configuration file that OPA can be started with. diff --git a/vendor/github.com/open-policy-agent/opa/format/format.go b/vendor/github.com/open-policy-agent/opa/v1/format/format.go similarity index 86% rename from vendor/github.com/open-policy-agent/opa/format/format.go rename to vendor/github.com/open-policy-agent/opa/v1/format/format.go index e4c9afaeb7..e86964d1b4 100644 --- a/vendor/github.com/open-policy-agent/opa/format/format.go +++ b/vendor/github.com/open-policy-agent/opa/v1/format/format.go @@ -13,9 +13,9 @@ import ( "strings" "unicode" - "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/internal/future" - "github.com/open-policy-agent/opa/types" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/types" ) // Opts lets you control the code formatting via `AstWithOpts()`. @@ -31,6 +31,17 @@ type Opts struct { // ParserOptions is the parser options used when parsing the module to be formatted. ParserOptions *ast.ParserOptions + + // DropV0Imports instructs the formatter to drop all v0 imports from the module; i.e. 'rego.v1' and 'future.keywords' imports. + // Imports are only removed if [Opts.RegoVersion] makes them redundant. + DropV0Imports bool +} + +func (o Opts) effectiveRegoVersion() ast.RegoVersion { + if o.RegoVersion == ast.RegoUndefined { + return ast.DefaultRegoVersion + } + return o.RegoVersion } // defaultLocationFile is the file name used in `Ast()` for terms @@ -46,23 +57,29 @@ func Source(filename string, src []byte) ([]byte, error) { } func SourceWithOpts(filename string, src []byte, opts Opts) ([]byte, error) { + regoVersion := opts.effectiveRegoVersion() + var parserOpts ast.ParserOptions if opts.ParserOptions != nil { parserOpts = *opts.ParserOptions } else { - if opts.RegoVersion == ast.RegoV1 { + if regoVersion == ast.RegoV1 { // If the rego version is V1, we need to parse it as such, to allow for future keywords not being imported. - // Otherwise, we'll default to RegoV0 + // Otherwise, we'll default to the default rego-version. parserOpts.RegoVersion = ast.RegoV1 } } + if parserOpts.RegoVersion == ast.RegoUndefined { + parserOpts.RegoVersion = ast.DefaultRegoVersion + } + module, err := ast.ParseModuleWithOpts(filename, string(src), parserOpts) if err != nil { return nil, err } - if opts.RegoVersion == ast.RegoV0CompatV1 || opts.RegoVersion == ast.RegoV1 { + if regoVersion == ast.RegoV0CompatV1 || regoVersion == ast.RegoV1 { checkOpts := ast.NewRegoCheckOptions() // The module is parsed as v0, so we need to disable checks that will be automatically amended by the AstWithOpts call anyways. checkOpts.RequireIfKeyword = false @@ -92,6 +109,16 @@ func MustAst(x interface{}) []byte { return bs } +// MustAstWithOpts is a helper function to format a Rego AST element. If any errors +// occurs this function will panic. This is mostly used for test +func MustAstWithOpts(x interface{}, opts Opts) []byte { + bs, err := AstWithOpts(x, opts) + if err != nil { + panic(err) + } + return bs +} + // Ast formats a Rego AST element. If the passed value is not a valid AST // element, Ast returns nil and an error. If AST nodes are missing locations // an arbitrary location will be used. @@ -116,7 +143,17 @@ type fmtOpts struct { // than if they don't. refHeads bool - regoV1 bool + regoV1 bool + regoV1Imported bool + futureKeywords []string +} + +func (o fmtOpts) keywords() []string { + if o.regoV1 { + return ast.KeywordsV1[:] + } + kws := ast.KeywordsV0[:] + return append(kws, o.futureKeywords...) } func AstWithOpts(x interface{}, opts Opts) ([]byte, error) { @@ -135,7 +172,8 @@ func AstWithOpts(x interface{}, opts Opts) ([]byte, error) { o := fmtOpts{} - if opts.RegoVersion == ast.RegoV0CompatV1 || opts.RegoVersion == ast.RegoV1 { + regoVersion := opts.effectiveRegoVersion() + if regoVersion == ast.RegoV0CompatV1 || regoVersion == ast.RegoV1 { o.regoV1 = true o.ifs = true o.contains = true @@ -161,8 +199,13 @@ func AstWithOpts(x interface{}, opts Opts) ([]byte, error) { } case *ast.Import: + if kw, ok := future.WhichFutureKeyword(n); ok { + o.futureKeywords = append(o.futureKeywords, kw) + } + switch { case isRegoV1Compatible(n): + o.regoV1Imported = true o.contains = true o.ifs = true case future.IsAllFutureKeywords(n): @@ -190,37 +233,44 @@ func AstWithOpts(x interface{}, opts Opts) ([]byte, error) { }) w := &writer{ - indent: "\t", - errs: make([]*ast.Error, 0), + indent: "\t", + errs: make([]*ast.Error, 0), + fmtOpts: o, } switch x := x.(type) { case *ast.Module: - if opts.RegoVersion == ast.RegoV1 { + if regoVersion == ast.RegoV1 && opts.DropV0Imports { x.Imports = filterRegoV1Import(x.Imports) - } else if opts.RegoVersion == ast.RegoV0CompatV1 { + } else if regoVersion == ast.RegoV0CompatV1 { x.Imports = ensureRegoV1Import(x.Imports) } - if opts.RegoVersion == ast.RegoV0CompatV1 || opts.RegoVersion == ast.RegoV1 || moduleIsRegoV1Compatible(x) { - x.Imports = future.FilterFutureImports(x.Imports) + regoV1Imported := moduleIsRegoV1Compatible(x) + if regoVersion == ast.RegoV0CompatV1 || regoVersion == ast.RegoV1 || regoV1Imported { + if !opts.DropV0Imports && !regoV1Imported { + for _, kw := range o.futureKeywords { + x.Imports = ensureFutureKeywordImport(x.Imports, kw) + } + } else { + x.Imports = future.FilterFutureImports(x.Imports) + } } else { for kw := range extraFutureKeywordImports { x.Imports = ensureFutureKeywordImport(x.Imports, kw) } } - w.writeModule(x, o) + w.writeModule(x) case *ast.Package: w.writePackage(x, nil) case *ast.Import: w.writeImports([]*ast.Import{x}, nil) case *ast.Rule: - w.writeRule(x, false /* isElse */, o, nil) + w.writeRule(x, false /* isElse */, nil) case *ast.Head: w.writeHead(x, false, // isDefault false, // isExpandedConst - o, nil) case ast.Body: w.writeBody(x, nil) @@ -292,9 +342,10 @@ type writer struct { beforeEnd *ast.Comment delay bool errs ast.Errors + fmtOpts fmtOpts } -func (w *writer) writeModule(module *ast.Module, o fmtOpts) { +func (w *writer) writeModule(module *ast.Module) { var pkg *ast.Package var others []interface{} var comments []*ast.Comment @@ -332,7 +383,7 @@ func (w *writer) writeModule(module *ast.Module, o fmtOpts) { imports, others = gatherImports(others) comments = w.writeImports(imports, comments) rules, others = gatherRules(others) - comments = w.writeRules(rules, o, comments) + comments = w.writeRules(rules, comments) } for i, c := range comments { @@ -355,7 +406,15 @@ func (w *writer) writePackage(pkg *ast.Package, comments []*ast.Comment) []*ast. comments = w.insertComments(comments, pkg.Location) w.startLine() - w.write(pkg.String()) + + // Omit head as all packages have the DefaultRootDocument prepended at parse time. + path := make(ast.Ref, len(pkg.Path)-1) + path[0] = ast.VarTerm(string(pkg.Path[1].Value.(ast.String))) + copy(path[1:], pkg.Path[2:]) + + w.write("package ") + w.writeRef(path, nil) + w.blankLine() return comments @@ -370,16 +429,16 @@ func (w *writer) writeComments(comments []*ast.Comment) { } } -func (w *writer) writeRules(rules []*ast.Rule, o fmtOpts, comments []*ast.Comment) []*ast.Comment { +func (w *writer) writeRules(rules []*ast.Rule, comments []*ast.Comment) []*ast.Comment { for _, rule := range rules { comments = w.insertComments(comments, rule.Location) - comments = w.writeRule(rule, false, o, comments) + comments = w.writeRule(rule, false, comments) w.blankLine() } return comments } -func (w *writer) writeRule(rule *ast.Rule, isElse bool, o fmtOpts, comments []*ast.Comment) []*ast.Comment { +func (w *writer) writeRule(rule *ast.Rule, isElse bool, comments []*ast.Comment) []*ast.Comment { if rule == nil { return comments } @@ -398,17 +457,17 @@ func (w *writer) writeRule(rule *ast.Rule, isElse bool, o fmtOpts, comments []*a // pretend that the rule has no body in this case. isExpandedConst := rule.Body.Equal(ast.NewBody(ast.NewExpr(ast.BooleanTerm(true)))) && rule.Else == nil - comments = w.writeHead(rule.Head, rule.Default, isExpandedConst, o, comments) + comments = w.writeHead(rule.Head, rule.Default, isExpandedConst, comments) // this excludes partial sets UNLESS `contains` is used - partialSetException := o.contains || rule.Head.Value != nil + partialSetException := w.fmtOpts.contains || rule.Head.Value != nil if len(rule.Body) == 0 || isExpandedConst { w.endLine() return comments } - if (o.regoV1 || o.ifs) && partialSetException { + if (w.fmtOpts.regoV1 || w.fmtOpts.ifs) && partialSetException { w.write(" if") if len(rule.Body) == 1 { if rule.Body[0].Location.Row == rule.Head.Location.Row { @@ -416,7 +475,7 @@ func (w *writer) writeRule(rule *ast.Rule, isElse bool, o fmtOpts, comments []*a comments = w.writeExpr(rule.Body[0], comments) w.endLine() if rule.Else != nil { - comments = w.writeElse(rule, o, comments) + comments = w.writeElse(rule, comments) } return comments } @@ -444,12 +503,12 @@ func (w *writer) writeRule(rule *ast.Rule, isElse bool, o fmtOpts, comments []*a w.startLine() w.write("}") if rule.Else != nil { - comments = w.writeElse(rule, o, comments) + comments = w.writeElse(rule, comments) } return comments } -func (w *writer) writeElse(rule *ast.Rule, o fmtOpts, comments []*ast.Comment) []*ast.Comment { +func (w *writer) writeElse(rule *ast.Rule, comments []*ast.Comment) []*ast.Comment { // If there was nothing else on the line before the "else" starts // then preserve this style of else block, otherwise it will be // started as an "inline" else eg: @@ -494,7 +553,11 @@ func (w *writer) writeElse(rule *ast.Rule, o fmtOpts, comments []*ast.Comment) [ } rule.Else.Head.Name = "else" // NOTE(sr): whaaat - rule.Else.Head.Reference = ast.Ref{ast.VarTerm("else")} + + elseHeadReference := ast.VarTerm("else") // construct a reference for the term + elseHeadReference.Location = rule.Else.Head.Location // and set the location to match the rule location + + rule.Else.Head.Reference = ast.Ref{elseHeadReference} rule.Else.Head.Args = nil comments = w.insertComments(comments, rule.Else.Head.Location) @@ -511,16 +574,16 @@ func (w *writer) writeElse(rule *ast.Rule, o fmtOpts, comments []*ast.Comment) [ rule.Else.Head.Value.Location = rule.Else.Head.Location } - return w.writeRule(rule.Else, true, o, comments) + return w.writeRule(rule.Else, true, comments) } -func (w *writer) writeHead(head *ast.Head, isDefault, isExpandedConst bool, o fmtOpts, comments []*ast.Comment) []*ast.Comment { +func (w *writer) writeHead(head *ast.Head, isDefault, isExpandedConst bool, comments []*ast.Comment) []*ast.Comment { ref := head.Ref() if head.Key != nil && head.Value == nil && !head.HasDynamicRef() { ref = ref.GroundPrefix() } - if o.refHeads || len(ref) == 1 { - w.write(ref.String()) + if w.fmtOpts.refHeads || len(ref) == 1 { + w.writeRef(ref, comments) } else { w.write(ref[0].String()) w.write("[") @@ -538,7 +601,7 @@ func (w *writer) writeHead(head *ast.Head, isDefault, isExpandedConst bool, o fm w.write(")") } if head.Key != nil { - if o.contains && head.Value == nil { + if w.fmtOpts.contains && head.Value == nil { w.write(" contains ") comments = w.writeTerm(head.Key, comments) } else if head.Value == nil { // no `if` for p[x] notation @@ -556,10 +619,9 @@ func (w *writer) writeHead(head *ast.Head, isDefault, isExpandedConst bool, o fm // * a.b -> a contains "b" // * a.b.c -> a.b.c := true // * a.b.c.d -> a.b.c.d := true - isRegoV1RefConst := o.regoV1 && isExpandedConst && head.Key == nil && len(head.Args) == 0 + isRegoV1RefConst := w.fmtOpts.regoV1 && isExpandedConst && head.Key == nil && len(head.Args) == 0 - if len(head.Args) > 0 && - head.Location == head.Value.Location && + if head.Location == head.Value.Location && head.Name != "else" && ast.Compare(head.Value, ast.BooleanTerm(true)) == 0 && !isRegoV1RefConst { @@ -569,7 +631,7 @@ func (w *writer) writeHead(head *ast.Head, isDefault, isExpandedConst bool, o fm return comments } - if head.Assign || o.regoV1 { + if head.Assign || w.fmtOpts.regoV1 { // preserve assignment operator, and enforce it if formatting for Rego v1 w.write(" := ") } else { @@ -723,7 +785,7 @@ func (w *writer) writeFunctionCall(expr *ast.Expr, comments []*ast.Comment) []*a return w.writeFunctionCallPlain(terms, comments) } - numDeclArgs := len(bi.Decl.Args()) + numDeclArgs := bi.Decl.Arity() numCallArgs := len(terms) - 1 switch numCallArgs { @@ -780,7 +842,7 @@ func (w *writer) writeTermParens(parens bool, term *ast.Term, comments []*ast.Co switch x := term.Value.(type) { case ast.Ref: - w.writeRef(x) + comments = w.writeRef(x, comments) case ast.Object: comments = w.writeObject(x, term.Location, comments) case *ast.Array: @@ -815,14 +877,14 @@ func (w *writer) writeTermParens(parens bool, term *ast.Term, comments []*ast.Co return comments } -func (w *writer) writeRef(x ast.Ref) { +func (w *writer) writeRef(x ast.Ref, comments []*ast.Comment) []*ast.Comment { if len(x) > 0 { parens := false _, ok := x[0].Value.(ast.Call) if ok { parens = x[0].Location.Text[0] == 40 // Starts with "(" } - w.writeTermParens(parens, x[0], nil) + comments = w.writeTermParens(parens, x[0], comments) path := x[1:] for _, t := range path { switch p := t.Value.(type) { @@ -832,11 +894,13 @@ func (w *writer) writeRef(x ast.Ref) { w.writeBracketed(w.formatVar(p)) default: w.write("[") - w.writeTerm(t, nil) + comments = w.writeTerm(t, comments) w.write("]") } } } + + return comments } func (w *writer) writeBracketed(str string) { @@ -847,7 +911,7 @@ var varRegexp = regexp.MustCompile("^[[:alpha:]_][[:alpha:][:digit:]_]*$") func (w *writer) writeRefStringPath(s ast.String) { str := string(s) - if varRegexp.MatchString(str) && !ast.IsKeyword(str) { + if varRegexp.MatchString(str) && !ast.IsInKeywords(str, w.fmtOpts.keywords()) { w.write("." + str) } else { w.writeBracketed(s.String()) @@ -881,7 +945,7 @@ func (w *writer) writeCall(parens bool, x ast.Call, loc *ast.Location, comments // NOTE(Trolloldem): writeCall is only invoked when the function call is a term // of another function. The only valid arity is the one of the // built-in function - if len(bi.Decl.Args()) != len(x)-1 { + if bi.Decl.Arity() != len(x)-1 { w.errs = append(w.errs, ArityFormatMismatchError(x[1:], x[0].String(), loc, bi.Decl)) return comments } @@ -898,10 +962,10 @@ func (w *writer) writeCall(parens bool, x ast.Call, loc *ast.Location, comments func (w *writer) writeInOperator(parens bool, operands []*ast.Term, comments []*ast.Comment, loc *ast.Location, f *types.Function) []*ast.Comment { - if len(operands) != len(f.Args()) { + if len(operands) != f.Arity() { // The number of operands does not math the arity of the `in` operator operator := ast.Member.Name - if len(f.Args()) == 3 { + if f.Arity() == 3 { operator = ast.MemberWithKey.Name } w.errs = append(w.errs, ArityFormatMismatchError(operands, operator, loc, f)) @@ -999,7 +1063,7 @@ func (w *writer) writeObjectComprehension(object *ast.ObjectComprehension, loc * return w.writeComprehension('{', '}', object.Value, object.Body, loc, comments) } -func (w *writer) writeComprehension(open, close byte, term *ast.Term, body ast.Body, loc *ast.Location, comments []*ast.Comment) []*ast.Comment { +func (w *writer) writeComprehension(openChar, closeChar byte, term *ast.Term, body ast.Body, loc *ast.Location, comments []*ast.Comment) []*ast.Comment { if term.Location.Row-loc.Row >= 1 { w.endLine() w.startLine() @@ -1013,10 +1077,10 @@ func (w *writer) writeComprehension(open, close byte, term *ast.Term, body ast.B comments = w.writeTermParens(parens, term, comments) w.write(" |") - return w.writeComprehensionBody(open, close, body, term.Location, loc, comments) + return w.writeComprehensionBody(openChar, closeChar, body, term.Location, loc, comments) } -func (w *writer) writeComprehensionBody(open, close byte, body ast.Body, term, compr *ast.Location, comments []*ast.Comment) []*ast.Comment { +func (w *writer) writeComprehensionBody(openChar, closeChar byte, body ast.Body, term, compr *ast.Location, comments []*ast.Comment) []*ast.Comment { exprs := make([]interface{}, 0, len(body)) for _, expr := range body { exprs = append(exprs, expr) @@ -1040,7 +1104,7 @@ func (w *writer) writeComprehensionBody(open, close byte, body ast.Body, term, c comments = w.writeExpr(body[i], comments) } - return w.insertComments(comments, closingLoc(0, 0, open, close, compr)) + return w.insertComments(comments, closingLoc(0, 0, openChar, closeChar, compr)) } func (w *writer) writeImports(imports []*ast.Import, comments []*ast.Comment) []*ast.Comment { @@ -1058,7 +1122,7 @@ func (w *writer) writeImports(imports []*ast.Import, comments []*ast.Comment) [] }) for _, i := range group { w.startLine() - w.write(i.String()) + w.writeImport(i) if c, ok := m[i]; ok { w.write(" " + c.String()) } @@ -1070,6 +1134,28 @@ func (w *writer) writeImports(imports []*ast.Import, comments []*ast.Comment) [] return comments } +func (w *writer) writeImport(imp *ast.Import) { + path := imp.Path.Value.(ast.Ref) + + buf := []string{"import"} + + if _, ok := future.WhichFutureKeyword(imp); ok { + // We don't want to wrap future.keywords imports in parens, so we create a new writer that doesn't + w2 := writer{ + buf: bytes.Buffer{}, + } + w2.writeRef(path, nil) + buf = append(buf, w2.buf.String()) + } else { + buf = append(buf, path.String()) + } + + if len(imp.Alias) > 0 { + buf = append(buf, "as "+imp.Alias.String()) + } + w.write(strings.Join(buf, " ")) +} + type entryWriter func(interface{}, []*ast.Comment) []*ast.Comment func (w *writer) writeIterable(elements []interface{}, last *ast.Location, close *ast.Location, comments []*ast.Comment, fn entryWriter) []*ast.Comment { @@ -1344,7 +1430,7 @@ func getLoc(x interface{}) *ast.Location { } } -func closingLoc(skipOpen, skipClose, open, close byte, loc *ast.Location) *ast.Location { +func closingLoc(skipOpen, skipClose, openChar, closeChar byte, loc *ast.Location) *ast.Location { i, offset := 0, 0 // Skip past parens/brackets/braces in rule heads. @@ -1353,7 +1439,7 @@ func closingLoc(skipOpen, skipClose, open, close byte, loc *ast.Location) *ast.L } for ; i < len(loc.Text); i++ { - if loc.Text[i] == open { + if loc.Text[i] == openChar { break } } @@ -1370,9 +1456,9 @@ func closingLoc(skipOpen, skipClose, open, close byte, loc *ast.Location) *ast.L } switch loc.Text[i] { - case open: + case openChar: state++ - case close: + case closeChar: state-- case '\n': offset++ @@ -1382,10 +1468,10 @@ func closingLoc(skipOpen, skipClose, open, close byte, loc *ast.Location) *ast.L return &ast.Location{Row: loc.Row + offset} } -func skipPast(open, close byte, loc *ast.Location) (int, int) { +func skipPast(openChar, closeChar byte, loc *ast.Location) (int, int) { i := 0 for ; i < len(loc.Text); i++ { - if loc.Text[i] == open { + if loc.Text[i] == openChar { break } } @@ -1399,9 +1485,9 @@ func skipPast(open, close byte, loc *ast.Location) (int, int) { } switch loc.Text[i] { - case open: + case openChar: state++ - case close: + case closeChar: state-- case '\n': offset++ @@ -1496,7 +1582,12 @@ func ensureFutureKeywordImport(imps []*ast.Import, kw string) []*ast.Import { } } imp := &ast.Import{ - Path: ast.MustParseTerm("future.keywords." + kw), + // NOTE: This is a hack to not error on the ref containing a keyword already present in v1. + // A cleaner solution would be to instead allow refs to contain keyword terms. + // E.g. in v1, `import future.keywords["in"]` is valid, but `import future.keywords.in` is not + // as it contains a reserved keyword. + Path: ast.MustParseTerm("future.keywords[\"" + kw + "\"]"), + //Path: ast.MustParseTerm("future.keywords." + kw), } imp.Location = defaultLocation(imp) return append(imps, imp) @@ -1539,14 +1630,14 @@ type ArityFormatErrDetail struct { // arityMismatchError but for `fmt` checks since the compiler has not run yet. func ArityFormatMismatchError(operands []*ast.Term, operator string, loc *ast.Location, f *types.Function) *ast.Error { - want := make([]string, len(f.Args())) - for i := range f.Args() { - want[i] = types.Sprint(f.Args()[i]) + want := make([]string, f.Arity()) + for i, arg := range f.Args() { + want[i] = types.Sprint(arg) } have := make([]string, len(operands)) for i := 0; i < len(operands); i++ { - have[i] = ast.TypeName(operands[i].Value) + have[i] = ast.ValueName(operands[i].Value) } err := ast.NewError(ast.TypeErr, loc, "%s: %s", operator, "arity mismatch") err.Details = &ArityFormatErrDetail{ diff --git a/vendor/github.com/open-policy-agent/opa/hooks/hooks.go b/vendor/github.com/open-policy-agent/opa/v1/hooks/hooks.go similarity index 98% rename from vendor/github.com/open-policy-agent/opa/hooks/hooks.go rename to vendor/github.com/open-policy-agent/opa/v1/hooks/hooks.go index 9659d7b499..caf69b1242 100644 --- a/vendor/github.com/open-policy-agent/opa/hooks/hooks.go +++ b/vendor/github.com/open-policy-agent/opa/v1/hooks/hooks.go @@ -8,7 +8,7 @@ import ( "context" "fmt" - "github.com/open-policy-agent/opa/config" + "github.com/open-policy-agent/opa/v1/config" ) // Hook is a hook to be called in some select places in OPA's operation. diff --git a/vendor/github.com/open-policy-agent/opa/ir/ir.go b/vendor/github.com/open-policy-agent/opa/v1/ir/ir.go similarity index 99% rename from vendor/github.com/open-policy-agent/opa/ir/ir.go rename to vendor/github.com/open-policy-agent/opa/v1/ir/ir.go index c07670704e..4f6961605d 100644 --- a/vendor/github.com/open-policy-agent/opa/ir/ir.go +++ b/vendor/github.com/open-policy-agent/opa/v1/ir/ir.go @@ -11,7 +11,7 @@ package ir import ( "fmt" - "github.com/open-policy-agent/opa/types" + "github.com/open-policy-agent/opa/v1/types" ) type ( diff --git a/vendor/github.com/open-policy-agent/opa/ir/marshal.go b/vendor/github.com/open-policy-agent/opa/v1/ir/marshal.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/ir/marshal.go rename to vendor/github.com/open-policy-agent/opa/v1/ir/marshal.go diff --git a/vendor/github.com/open-policy-agent/opa/ir/pretty.go b/vendor/github.com/open-policy-agent/opa/v1/ir/pretty.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/ir/pretty.go rename to vendor/github.com/open-policy-agent/opa/v1/ir/pretty.go diff --git a/vendor/github.com/open-policy-agent/opa/ir/walk.go b/vendor/github.com/open-policy-agent/opa/v1/ir/walk.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/ir/walk.go rename to vendor/github.com/open-policy-agent/opa/v1/ir/walk.go diff --git a/vendor/github.com/open-policy-agent/opa/keys/keys.go b/vendor/github.com/open-policy-agent/opa/v1/keys/keys.go similarity index 98% rename from vendor/github.com/open-policy-agent/opa/keys/keys.go rename to vendor/github.com/open-policy-agent/opa/v1/keys/keys.go index de03496943..fba7a9c939 100644 --- a/vendor/github.com/open-policy-agent/opa/keys/keys.go +++ b/vendor/github.com/open-policy-agent/opa/v1/keys/keys.go @@ -5,7 +5,7 @@ import ( "fmt" "os" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/util" ) const defaultSigningAlgorithm = "RS256" diff --git a/vendor/github.com/open-policy-agent/opa/loader/errors.go b/vendor/github.com/open-policy-agent/opa/v1/loader/errors.go similarity index 96% rename from vendor/github.com/open-policy-agent/opa/loader/errors.go rename to vendor/github.com/open-policy-agent/opa/v1/loader/errors.go index b8aafb1421..55b8e7dc44 100644 --- a/vendor/github.com/open-policy-agent/opa/loader/errors.go +++ b/vendor/github.com/open-policy-agent/opa/v1/loader/errors.go @@ -8,7 +8,7 @@ import ( "fmt" "strings" - "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/v1/ast" ) // Errors is a wrapper for multiple loader errors. diff --git a/vendor/github.com/open-policy-agent/opa/loader/extension/extension.go b/vendor/github.com/open-policy-agent/opa/v1/loader/extension/extension.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/loader/extension/extension.go rename to vendor/github.com/open-policy-agent/opa/v1/loader/extension/extension.go diff --git a/vendor/github.com/open-policy-agent/opa/loader/filter/filter.go b/vendor/github.com/open-policy-agent/opa/v1/loader/filter/filter.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/loader/filter/filter.go rename to vendor/github.com/open-policy-agent/opa/v1/loader/filter/filter.go diff --git a/vendor/github.com/open-policy-agent/opa/loader/loader.go b/vendor/github.com/open-policy-agent/opa/v1/loader/loader.go similarity index 96% rename from vendor/github.com/open-policy-agent/opa/loader/loader.go rename to vendor/github.com/open-policy-agent/opa/v1/loader/loader.go index 461639ed19..5e2217473a 100644 --- a/vendor/github.com/open-policy-agent/opa/loader/loader.go +++ b/vendor/github.com/open-policy-agent/opa/v1/loader/loader.go @@ -12,21 +12,20 @@ import ( "io/fs" "os" "path/filepath" - "sort" "strings" "sigs.k8s.io/yaml" - "github.com/open-policy-agent/opa/ast" - astJSON "github.com/open-policy-agent/opa/ast/json" - "github.com/open-policy-agent/opa/bundle" fileurl "github.com/open-policy-agent/opa/internal/file/url" "github.com/open-policy-agent/opa/internal/merge" - "github.com/open-policy-agent/opa/loader/filter" - "github.com/open-policy-agent/opa/metrics" - "github.com/open-policy-agent/opa/storage" - "github.com/open-policy-agent/opa/storage/inmem" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/ast" + astJSON "github.com/open-policy-agent/opa/v1/ast/json" + "github.com/open-policy-agent/opa/v1/bundle" + "github.com/open-policy-agent/opa/v1/loader/filter" + "github.com/open-policy-agent/opa/v1/metrics" + "github.com/open-policy-agent/opa/v1/storage" + "github.com/open-policy-agent/opa/v1/storage/inmem" + "github.com/open-policy-agent/opa/v1/util" ) // Result represents the result of successfully loading zero or more files. @@ -101,6 +100,8 @@ type FileLoader interface { WithSkipBundleVerification(bool) FileLoader WithProcessAnnotation(bool) FileLoader WithCapabilities(*ast.Capabilities) FileLoader + // Deprecated: Use SetOptions in the json package instead, where a longer description + // of why this is deprecated also can be found. WithJSONOptions(*astJSON.Options) FileLoader WithRegoVersion(ast.RegoVersion) FileLoader WithFollowSymlinks(bool) FileLoader @@ -178,9 +179,11 @@ func (fl *fileLoader) WithCapabilities(caps *ast.Capabilities) FileLoader { return fl } -// WithJSONOptions sets the JSONOptions for use when parsing files -func (fl *fileLoader) WithJSONOptions(opts *astJSON.Options) FileLoader { - fl.opts.JSONOptions = opts +// WithJSONOptions sets the JSON options on the parser (now a no-op). +// +// Deprecated: Use SetOptions in the json package instead, where a longer description +// of why this is deprecated also can be found. +func (fl *fileLoader) WithJSONOptions(*astJSON.Options) FileLoader { return fl } @@ -270,7 +273,6 @@ func (fl fileLoader) AsBundle(path string) (*bundle.Bundle, error) { WithSkipBundleVerification(fl.skipVerify). WithProcessAnnotations(fl.opts.ProcessAnnotation). WithCapabilities(fl.opts.Capabilities). - WithJSONOptions(fl.opts.JSONOptions). WithFollowSymlinks(fl.followSymlinks). WithRegoVersion(fl.opts.RegoVersion) @@ -564,12 +566,7 @@ func Dirs(paths []string) []string { unique[dir] = struct{}{} } - u := make([]string, 0, len(unique)) - for k := range unique { - u = append(u, k) - } - sort.Strings(u) - return u + return util.KeysSorted(unique) } // SplitPrefix returns a tuple specifying the document prefix and the file @@ -762,7 +759,7 @@ func loadBundleFile(path string, bs []byte, m metrics.Metrics, opts ast.ParserOp tl := bundle.NewTarballLoaderWithBaseURL(bytes.NewBuffer(bs), path) br := bundle.NewCustomReader(tl). WithRegoVersion(opts.RegoVersion). - WithJSONOptions(opts.JSONOptions). + WithCapabilities(opts.Capabilities). WithProcessAnnotations(opts.ProcessAnnotation). WithMetrics(m). WithSkipBundleVerification(true). diff --git a/vendor/github.com/open-policy-agent/opa/logging/logging.go b/vendor/github.com/open-policy-agent/opa/v1/logging/logging.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/logging/logging.go rename to vendor/github.com/open-policy-agent/opa/v1/logging/logging.go diff --git a/vendor/github.com/open-policy-agent/opa/metrics/metrics.go b/vendor/github.com/open-policy-agent/opa/v1/metrics/metrics.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/metrics/metrics.go rename to vendor/github.com/open-policy-agent/opa/v1/metrics/metrics.go diff --git a/vendor/github.com/open-policy-agent/opa/plugins/plugins.go b/vendor/github.com/open-policy-agent/opa/v1/plugins/plugins.go similarity index 96% rename from vendor/github.com/open-policy-agent/opa/plugins/plugins.go rename to vendor/github.com/open-policy-agent/opa/v1/plugins/plugins.go index bacdd15076..c9b99ab28b 100644 --- a/vendor/github.com/open-policy-agent/opa/plugins/plugins.go +++ b/vendor/github.com/open-policy-agent/opa/v1/plugins/plugins.go @@ -19,22 +19,22 @@ import ( "github.com/gorilla/mux" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/bundle" - "github.com/open-policy-agent/opa/config" - "github.com/open-policy-agent/opa/hooks" bundleUtils "github.com/open-policy-agent/opa/internal/bundle" cfg "github.com/open-policy-agent/opa/internal/config" initload "github.com/open-policy-agent/opa/internal/runtime/init" - "github.com/open-policy-agent/opa/keys" - "github.com/open-policy-agent/opa/loader" - "github.com/open-policy-agent/opa/logging" - "github.com/open-policy-agent/opa/plugins/rest" - "github.com/open-policy-agent/opa/resolver/wasm" - "github.com/open-policy-agent/opa/storage" - "github.com/open-policy-agent/opa/topdown/cache" - "github.com/open-policy-agent/opa/topdown/print" - "github.com/open-policy-agent/opa/tracing" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/bundle" + "github.com/open-policy-agent/opa/v1/config" + "github.com/open-policy-agent/opa/v1/hooks" + "github.com/open-policy-agent/opa/v1/keys" + "github.com/open-policy-agent/opa/v1/loader" + "github.com/open-policy-agent/opa/v1/logging" + "github.com/open-policy-agent/opa/v1/plugins/rest" + "github.com/open-policy-agent/opa/v1/resolver/wasm" + "github.com/open-policy-agent/opa/v1/storage" + "github.com/open-policy-agent/opa/v1/topdown/cache" + "github.com/open-policy-agent/opa/v1/topdown/print" + "github.com/open-policy-agent/opa/v1/tracing" ) // Factory defines the interface OPA uses to instantiate your plugin. @@ -163,6 +163,14 @@ func (s *Status) String() string { return fmt.Sprintf("{%v %q}", s.State, s.Message) } +func (s *Status) Equal(other *Status) bool { + if s == nil || other == nil { + return s == nil && other == nil + } + + return s.State == other.State && s.Message == other.Message +} + // StatusListener defines a handler to register for status updates. type StatusListener func(status map[string]*Status) @@ -537,6 +545,7 @@ func (m *Manager) Init(ctx context.Context) error { Bundles: m.initBundles, MaxErrors: m.maxErrors, EnablePrintStatements: m.enablePrintStatements, + ParserOptions: m.parserOptions, }) if err != nil { @@ -576,7 +585,7 @@ func (m *Manager) Labels() map[string]string { return m.Config.Labels } -// InterQueryBuiltinCacheConfig returns the configuration for the inter-query cache. +// InterQueryBuiltinCacheConfig returns the configuration for the inter-query caches. func (m *Manager) InterQueryBuiltinCacheConfig() *cache.Config { m.mtx.Lock() defer m.mtx.Unlock() @@ -939,7 +948,13 @@ func loadCompilerFromStore(ctx context.Context, store storage.Store, txn storage modules[policy] = module } - compiler := ast.NewCompiler().WithEnablePrintStatements(enablePrintStatements) + compiler := ast.NewCompiler(). + WithEnablePrintStatements(enablePrintStatements) + + if popts.RegoVersion != ast.RegoUndefined { + compiler = compiler.WithDefaultRegoVersion(popts.RegoVersion) + } + compiler.Compile(modules) return compiler, nil } diff --git a/vendor/github.com/open-policy-agent/opa/plugins/rest/auth.go b/vendor/github.com/open-policy-agent/opa/v1/plugins/rest/auth.go similarity index 99% rename from vendor/github.com/open-policy-agent/opa/plugins/rest/auth.go rename to vendor/github.com/open-policy-agent/opa/v1/plugins/rest/auth.go index 11e72001a2..964630fa2f 100644 --- a/vendor/github.com/open-policy-agent/opa/plugins/rest/auth.go +++ b/vendor/github.com/open-policy-agent/opa/v1/plugins/rest/auth.go @@ -33,8 +33,8 @@ import ( "github.com/open-policy-agent/opa/internal/jwx/jws/sign" "github.com/open-policy-agent/opa/internal/providers/aws" "github.com/open-policy-agent/opa/internal/uuid" - "github.com/open-policy-agent/opa/keys" - "github.com/open-policy-agent/opa/logging" + "github.com/open-policy-agent/opa/v1/keys" + "github.com/open-policy-agent/opa/v1/logging" ) const ( diff --git a/vendor/github.com/open-policy-agent/opa/plugins/rest/aws.go b/vendor/github.com/open-policy-agent/opa/v1/plugins/rest/aws.go similarity index 95% rename from vendor/github.com/open-policy-agent/opa/plugins/rest/aws.go rename to vendor/github.com/open-policy-agent/opa/v1/plugins/rest/aws.go index 349441c838..133df80996 100644 --- a/vendor/github.com/open-policy-agent/opa/plugins/rest/aws.go +++ b/vendor/github.com/open-policy-agent/opa/v1/plugins/rest/aws.go @@ -19,7 +19,7 @@ import ( "github.com/go-ini/ini" "github.com/open-policy-agent/opa/internal/providers/aws" - "github.com/open-policy-agent/opa/logging" + "github.com/open-policy-agent/opa/v1/logging" ) const ( @@ -30,10 +30,11 @@ const ( ec2DefaultTokenPath = "http://169.254.169.254/latest/api/token" // ref. https://docs.aws.amazon.com/AmazonECS/latest/userguide/task-iam-roles.html - ecsDefaultCredServicePath = "http://169.254.170.2" - ecsRelativePathEnvVar = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" - ecsFullPathEnvVar = "AWS_CONTAINER_CREDENTIALS_FULL_URI" - ecsAuthorizationTokenEnvVar = "AWS_CONTAINER_AUTHORIZATION_TOKEN" + ecsDefaultCredServicePath = "http://169.254.170.2" + ecsRelativePathEnvVar = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" + ecsFullPathEnvVar = "AWS_CONTAINER_CREDENTIALS_FULL_URI" + ecsAuthorizationTokenEnvVar = "AWS_CONTAINER_AUTHORIZATION_TOKEN" + ecsAuthorizationTokenFileEnvVar = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE" // ref. https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html stsDefaultDomain = "amazonaws.com" @@ -277,9 +278,22 @@ func (cs *awsMetadataCredentialService) refreshFromService(ctx context.Context) // if using the AWS_CONTAINER_CREDENTIALS_FULL_URI variable, we need to associate the token // to the request if _, useFullPath := os.LookupEnv(ecsFullPathEnvVar); useFullPath { - token, tokenExists := os.LookupEnv(ecsAuthorizationTokenEnvVar) - if !tokenExists { - return errors.New("unable to get ECS metadata authorization token") + var token string + tokenFilePath, tokenFilePathExists := os.LookupEnv(ecsAuthorizationTokenFileEnvVar) + + if tokenFilePathExists { + tokenBytes, err := os.ReadFile(tokenFilePath) + if err != nil { + return errors.New("failed to read ECS metadata authorization token from file: " + err.Error()) + } + token = string(tokenBytes) + // If token doesn't exist as a file check if it exists as an environment variable + } else { + var tokenExists bool + token, tokenExists = os.LookupEnv(ecsAuthorizationTokenEnvVar) + if !tokenExists { + return errors.New("unable to get ECS metadata authorization token") + } } req.Header.Set("Authorization", token) } diff --git a/vendor/github.com/open-policy-agent/opa/plugins/rest/azure.go b/vendor/github.com/open-policy-agent/opa/v1/plugins/rest/azure.go similarity index 72% rename from vendor/github.com/open-policy-agent/opa/plugins/rest/azure.go rename to vendor/github.com/open-policy-agent/opa/v1/plugins/rest/azure.go index 6a85dea681..ae00d48a7c 100644 --- a/vendor/github.com/open-policy-agent/opa/plugins/rest/azure.go +++ b/vendor/github.com/open-policy-agent/opa/v1/plugins/rest/azure.go @@ -7,14 +7,16 @@ import ( "io" "net/http" "net/url" + "os" "time" ) var ( - azureIMDSEndpoint = "http://169.254.169.254/metadata/identity/oauth2/token" - defaultAPIVersion = "2018-02-01" - defaultResource = "https://storage.azure.com/" - timeout = 5 * time.Second + azureIMDSEndpoint = "http://169.254.169.254/metadata/identity/oauth2/token" + defaultAPIVersion = "2018-02-01" + defaultResource = "https://storage.azure.com/" + timeout = 5 * time.Second + defaultAPIVersionForAppServiceMsi = "2019-08-01" ) // azureManagedIdentitiesToken holds a token for managed identities for Azure resources @@ -41,12 +43,13 @@ func (e *azureManagedIdentitiesError) Error() string { // azureManagedIdentitiesAuthPlugin uses an azureManagedIdentitiesToken.AccessToken for bearer authorization type azureManagedIdentitiesAuthPlugin struct { - Endpoint string `json:"endpoint"` - APIVersion string `json:"api_version"` - Resource string `json:"resource"` - ObjectID string `json:"object_id"` - ClientID string `json:"client_id"` - MiResID string `json:"mi_res_id"` + Endpoint string `json:"endpoint"` + APIVersion string `json:"api_version"` + Resource string `json:"resource"` + ObjectID string `json:"object_id"` + ClientID string `json:"client_id"` + MiResID string `json:"mi_res_id"` + UseAppServiceMsi bool `json:"use_app_service_msi,omitempty"` } func (ap *azureManagedIdentitiesAuthPlugin) NewClient(c Config) (*http.Client, error) { @@ -55,7 +58,13 @@ func (ap *azureManagedIdentitiesAuthPlugin) NewClient(c Config) (*http.Client, e } if ap.Endpoint == "" { - ap.Endpoint = azureIMDSEndpoint + identityEndpoint := os.Getenv("IDENTITY_ENDPOINT") + if identityEndpoint != "" { + ap.UseAppServiceMsi = true + ap.Endpoint = identityEndpoint + } else { + ap.Endpoint = azureIMDSEndpoint + } } if ap.Resource == "" { @@ -63,7 +72,11 @@ func (ap *azureManagedIdentitiesAuthPlugin) NewClient(c Config) (*http.Client, e } if ap.APIVersion == "" { - ap.APIVersion = defaultAPIVersion + if ap.UseAppServiceMsi { + ap.APIVersion = defaultAPIVersionForAppServiceMsi + } else { + ap.APIVersion = defaultAPIVersion + } } t, err := DefaultTLSConfig(c) @@ -78,6 +91,7 @@ func (ap *azureManagedIdentitiesAuthPlugin) Prepare(req *http.Request) error { token, err := azureManagedIdentitiesTokenRequest( ap.Endpoint, ap.APIVersion, ap.Resource, ap.ObjectID, ap.ClientID, ap.MiResID, + ap.UseAppServiceMsi, ) if err != nil { return err @@ -90,6 +104,7 @@ func (ap *azureManagedIdentitiesAuthPlugin) Prepare(req *http.Request) error { // azureManagedIdentitiesTokenRequest fetches an azureManagedIdentitiesToken func azureManagedIdentitiesTokenRequest( endpoint, apiVersion, resource, objectID, clientID, miResID string, + useAppServiceMsi bool, ) (azureManagedIdentitiesToken, error) { var token azureManagedIdentitiesToken e := buildAzureManagedIdentitiesRequestPath(endpoint, apiVersion, resource, objectID, clientID, miResID) @@ -98,7 +113,15 @@ func azureManagedIdentitiesTokenRequest( if err != nil { return token, err } - request.Header.Add("Metadata", "true") + if useAppServiceMsi { + identityHeader := os.Getenv("IDENTITY_HEADER") + if identityHeader == "" { + return token, errors.New("azure managed identities auth: IDENTITY_HEADER env var not found") + } + request.Header.Add("x-identity-header", identityHeader) + } else { + request.Header.Add("Metadata", "true") + } httpClient := http.Client{Timeout: timeout} response, err := httpClient.Do(request) diff --git a/vendor/github.com/open-policy-agent/opa/plugins/rest/gcp.go b/vendor/github.com/open-policy-agent/opa/v1/plugins/rest/gcp.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/plugins/rest/gcp.go rename to vendor/github.com/open-policy-agent/opa/v1/plugins/rest/gcp.go diff --git a/vendor/github.com/open-policy-agent/opa/plugins/rest/rest.go b/vendor/github.com/open-policy-agent/opa/v1/plugins/rest/rest.go similarity index 98% rename from vendor/github.com/open-policy-agent/opa/plugins/rest/rest.go rename to vendor/github.com/open-policy-agent/opa/v1/plugins/rest/rest.go index fd59058ca1..fea351557b 100644 --- a/vendor/github.com/open-policy-agent/opa/plugins/rest/rest.go +++ b/vendor/github.com/open-policy-agent/opa/v1/plugins/rest/rest.go @@ -18,10 +18,10 @@ import ( "strings" "github.com/open-policy-agent/opa/internal/version" - "github.com/open-policy-agent/opa/keys" - "github.com/open-policy-agent/opa/logging" - "github.com/open-policy-agent/opa/tracing" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/keys" + "github.com/open-policy-agent/opa/v1/logging" + "github.com/open-policy-agent/opa/v1/tracing" + "github.com/open-policy-agent/opa/v1/util" ) const ( diff --git a/vendor/github.com/open-policy-agent/opa/rego/errors.go b/vendor/github.com/open-policy-agent/opa/v1/rego/errors.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/rego/errors.go rename to vendor/github.com/open-policy-agent/opa/v1/rego/errors.go diff --git a/vendor/github.com/open-policy-agent/opa/rego/plugins.go b/vendor/github.com/open-policy-agent/opa/v1/rego/plugins.go similarity index 91% rename from vendor/github.com/open-policy-agent/opa/rego/plugins.go rename to vendor/github.com/open-policy-agent/opa/v1/rego/plugins.go index abaa910341..88f23480b4 100644 --- a/vendor/github.com/open-policy-agent/opa/rego/plugins.go +++ b/vendor/github.com/open-policy-agent/opa/v1/rego/plugins.go @@ -8,8 +8,8 @@ import ( "context" "sync" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/ir" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/ir" ) var targetPlugins = map[string]TargetPlugin{} diff --git a/vendor/github.com/open-policy-agent/opa/rego/rego.go b/vendor/github.com/open-policy-agent/opa/v1/rego/rego.go similarity index 88% rename from vendor/github.com/open-policy-agent/opa/rego/rego.go rename to vendor/github.com/open-policy-agent/opa/v1/rego/rego.go index 5a5ea0d123..ef930a2cf7 100644 --- a/vendor/github.com/open-policy-agent/opa/rego/rego.go +++ b/vendor/github.com/open-policy-agent/opa/v1/rego/rego.go @@ -14,28 +14,28 @@ import ( "strings" "time" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/bundle" bundleUtils "github.com/open-policy-agent/opa/internal/bundle" "github.com/open-policy-agent/opa/internal/compiler/wasm" "github.com/open-policy-agent/opa/internal/future" "github.com/open-policy-agent/opa/internal/planner" "github.com/open-policy-agent/opa/internal/rego/opa" "github.com/open-policy-agent/opa/internal/wasm/encoding" - "github.com/open-policy-agent/opa/ir" - "github.com/open-policy-agent/opa/loader" - "github.com/open-policy-agent/opa/metrics" - "github.com/open-policy-agent/opa/plugins" - "github.com/open-policy-agent/opa/resolver" - "github.com/open-policy-agent/opa/storage" - "github.com/open-policy-agent/opa/storage/inmem" - "github.com/open-policy-agent/opa/topdown" - "github.com/open-policy-agent/opa/topdown/builtins" - "github.com/open-policy-agent/opa/topdown/cache" - "github.com/open-policy-agent/opa/topdown/print" - "github.com/open-policy-agent/opa/tracing" - "github.com/open-policy-agent/opa/types" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/bundle" + "github.com/open-policy-agent/opa/v1/ir" + "github.com/open-policy-agent/opa/v1/loader" + "github.com/open-policy-agent/opa/v1/metrics" + "github.com/open-policy-agent/opa/v1/plugins" + "github.com/open-policy-agent/opa/v1/resolver" + "github.com/open-policy-agent/opa/v1/storage" + "github.com/open-policy-agent/opa/v1/storage/inmem" + "github.com/open-policy-agent/opa/v1/topdown" + "github.com/open-policy-agent/opa/v1/topdown/builtins" + "github.com/open-policy-agent/opa/v1/topdown/cache" + "github.com/open-policy-agent/opa/v1/topdown/print" + "github.com/open-policy-agent/opa/v1/tracing" + "github.com/open-policy-agent/opa/v1/types" + "github.com/open-policy-agent/opa/v1/util" ) const ( @@ -99,32 +99,35 @@ type preparedQuery struct { // EvalContext defines the set of options allowed to be set at evaluation // time. Any other options will need to be set on a new Rego object. type EvalContext struct { - hasInput bool - time time.Time - seed io.Reader - rawInput *interface{} - parsedInput ast.Value - metrics metrics.Metrics - txn storage.Transaction - instrument bool - instrumentation *topdown.Instrumentation - partialNamespace string - queryTracers []topdown.QueryTracer - compiledQuery compiledQuery - unknowns []string - disableInlining []ast.Ref - parsedUnknowns []*ast.Term - indexing bool - earlyExit bool - interQueryBuiltinCache cache.InterQueryCache - ndBuiltinCache builtins.NDBCache - resolvers []refResolver - sortSets bool - copyMaps bool - printHook print.Hook - capabilities *ast.Capabilities - strictBuiltinErrors bool - virtualCache topdown.VirtualCache + hasInput bool + time time.Time + seed io.Reader + rawInput *interface{} + parsedInput ast.Value + metrics metrics.Metrics + txn storage.Transaction + instrument bool + instrumentation *topdown.Instrumentation + partialNamespace string + queryTracers []topdown.QueryTracer + compiledQuery compiledQuery + unknowns []string + disableInlining []ast.Ref + nondeterministicBuiltins bool + parsedUnknowns []*ast.Term + indexing bool + earlyExit bool + interQueryBuiltinCache cache.InterQueryCache + interQueryBuiltinValueCache cache.InterQueryValueCache + ndBuiltinCache builtins.NDBCache + resolvers []refResolver + httpRoundTripper topdown.CustomizeRoundTripper + sortSets bool + copyMaps bool + printHook print.Hook + capabilities *ast.Capabilities + strictBuiltinErrors bool + virtualCache topdown.VirtualCache } func (e *EvalContext) RawInput() *interface{} { @@ -147,6 +150,10 @@ func (e *EvalContext) InterQueryBuiltinCache() cache.InterQueryCache { return e.interQueryBuiltinCache } +func (e *EvalContext) InterQueryBuiltinValueCache() cache.InterQueryValueCache { + return e.interQueryBuiltinValueCache +} + func (e *EvalContext) PrintHook() print.Hook { return e.printHook } @@ -307,6 +314,14 @@ func EvalInterQueryBuiltinCache(c cache.InterQueryCache) EvalOption { } } +// EvalInterQueryBuiltinValueCache sets the inter-query value cache that built-in functions can utilize +// during evaluation. +func EvalInterQueryBuiltinValueCache(c cache.InterQueryValueCache) EvalOption { + return func(e *EvalContext) { + e.interQueryBuiltinValueCache = c + } +} + // EvalNDBuiltinCache sets the non-deterministic builtin cache that built-in functions can // use during evaluation. func EvalNDBuiltinCache(c builtins.NDBCache) EvalOption { @@ -322,6 +337,13 @@ func EvalResolver(ref ast.Ref, r resolver.Resolver) EvalOption { } } +// EvalHTTPRoundTripper allows customizing the http.RoundTripper for this evaluation. +func EvalHTTPRoundTripper(t topdown.CustomizeRoundTripper) EvalOption { + return func(e *EvalContext) { + e.httpRoundTripper = t + } +} + // EvalSortSets causes the evaluator to sort sets before returning them as JSON arrays. func EvalSortSets(yes bool) EvalOption { return func(e *EvalContext) { @@ -351,6 +373,15 @@ func EvalVirtualCache(vc topdown.VirtualCache) EvalOption { } } +// EvalNondeterministicBuiltins causes non-deterministic builtins to be evalued +// during partial evaluation. This is needed to pull in external data, or validate +// a JWT, during PE, so that the result informs what queries are returned. +func EvalNondeterministicBuiltins(yes bool) EvalOption { + return func(e *EvalContext) { + e.nondeterministicBuiltins = yes + } +} + func (pq preparedQuery) Modules() map[string]*ast.Module { mods := make(map[string]*ast.Module) @@ -373,24 +404,25 @@ func (pq preparedQuery) Modules() map[string]*ast.Module { // been opened. func (pq preparedQuery) newEvalContext(ctx context.Context, options []EvalOption) (*EvalContext, func(context.Context), error) { ectx := &EvalContext{ - hasInput: false, - rawInput: nil, - parsedInput: nil, - metrics: nil, - txn: nil, - instrument: false, - instrumentation: nil, - partialNamespace: pq.r.partialNamespace, - queryTracers: nil, - unknowns: pq.r.unknowns, - parsedUnknowns: pq.r.parsedUnknowns, - compiledQuery: compiledQuery{}, - indexing: true, - earlyExit: true, - resolvers: pq.r.resolvers, - printHook: pq.r.printHook, - capabilities: pq.r.capabilities, - strictBuiltinErrors: pq.r.strictBuiltinErrors, + hasInput: false, + rawInput: nil, + parsedInput: nil, + metrics: nil, + txn: nil, + instrument: false, + instrumentation: nil, + partialNamespace: pq.r.partialNamespace, + queryTracers: nil, + unknowns: pq.r.unknowns, + parsedUnknowns: pq.r.parsedUnknowns, + nondeterministicBuiltins: pq.r.nondeterministicBuiltins, + compiledQuery: compiledQuery{}, + indexing: true, + earlyExit: true, + resolvers: pq.r.resolvers, + printHook: pq.r.printHook, + capabilities: pq.r.capabilities, + strictBuiltinErrors: pq.r.strictBuiltinErrors, } for _, o := range options { @@ -546,64 +578,71 @@ type loadPaths struct { // Rego constructs a query and can be evaluated to obtain results. type Rego struct { - query string - parsedQuery ast.Body - compiledQueries map[queryType]compiledQuery - pkg string - parsedPackage *ast.Package - imports []string - parsedImports []*ast.Import - rawInput *interface{} - parsedInput ast.Value - unknowns []string - parsedUnknowns []*ast.Term - disableInlining []string - shallowInlining bool - skipPartialNamespace bool - partialNamespace string - modules []rawModule - parsedModules map[string]*ast.Module - compiler *ast.Compiler - store storage.Store - ownStore bool - txn storage.Transaction - metrics metrics.Metrics - queryTracers []topdown.QueryTracer - tracebuf *topdown.BufferTracer - trace bool - instrumentation *topdown.Instrumentation - instrument bool - capture map[*ast.Expr]ast.Var // map exprs to generated capture vars - termVarID int - dump io.Writer - runtime *ast.Term - time time.Time - seed io.Reader - capabilities *ast.Capabilities - builtinDecls map[string]*ast.Builtin - builtinFuncs map[string]*topdown.Builtin - unsafeBuiltins map[string]struct{} - loadPaths loadPaths - bundlePaths []string - bundles map[string]*bundle.Bundle - skipBundleVerification bool - interQueryBuiltinCache cache.InterQueryCache - ndBuiltinCache builtins.NDBCache - strictBuiltinErrors bool - builtinErrorList *[]topdown.Error - resolvers []refResolver - schemaSet *ast.SchemaSet - target string // target type (wasm, rego, etc.) - opa opa.EvalEngine - generateJSON func(*ast.Term, *EvalContext) (interface{}, error) - printHook print.Hook - enablePrintStatements bool - distributedTacingOpts tracing.Options - strict bool - pluginMgr *plugins.Manager - plugins []TargetPlugin - targetPrepState TargetPluginEval - regoVersion ast.RegoVersion + query string + parsedQuery ast.Body + compiledQueries map[queryType]compiledQuery + pkg string + parsedPackage *ast.Package + imports []string + parsedImports []*ast.Import + rawInput *interface{} + parsedInput ast.Value + unknowns []string + parsedUnknowns []*ast.Term + disableInlining []string + shallowInlining bool + nondeterministicBuiltins bool + skipPartialNamespace bool + partialNamespace string + modules []rawModule + parsedModules map[string]*ast.Module + compiler *ast.Compiler + store storage.Store + ownStore bool + ownStoreReadAst bool + txn storage.Transaction + metrics metrics.Metrics + queryTracers []topdown.QueryTracer + tracebuf *topdown.BufferTracer + trace bool + instrumentation *topdown.Instrumentation + instrument bool + capture map[*ast.Expr]ast.Var // map exprs to generated capture vars + termVarID int + dump io.Writer + runtime *ast.Term + time time.Time + seed io.Reader + capabilities *ast.Capabilities + builtinDecls map[string]*ast.Builtin + builtinFuncs map[string]*topdown.Builtin + unsafeBuiltins map[string]struct{} + loadPaths loadPaths + bundlePaths []string + bundles map[string]*bundle.Bundle + skipBundleVerification bool + interQueryBuiltinCache cache.InterQueryCache + interQueryBuiltinValueCache cache.InterQueryValueCache + ndBuiltinCache builtins.NDBCache + strictBuiltinErrors bool + builtinErrorList *[]topdown.Error + resolvers []refResolver + schemaSet *ast.SchemaSet + target string // target type (wasm, rego, etc.) + opa opa.EvalEngine + generateJSON func(*ast.Term, *EvalContext) (interface{}, error) + printHook print.Hook + enablePrintStatements bool + distributedTacingOpts tracing.Options + strict bool + pluginMgr *plugins.Manager + plugins []TargetPlugin + targetPrepState TargetPluginEval + regoVersion ast.RegoVersion +} + +func (r *Rego) RegoVersion() ast.RegoVersion { + return r.regoVersion } // Function represents a built-in function that is callable in Rego. @@ -786,7 +825,7 @@ func memoize(decl *Function, bctx BuiltinContext, terms []*ast.Term, ifEmpty fun // The term slice _may_ include an output term depending on how the caller // referred to the built-in function. Only use the arguments as the cache // key. Unification ensures we don't get false positive matches. - for i := 0; i < len(decl.Decl.Args()); i++ { + for i := 0; i < decl.Decl.Arity(); i++ { if _, err := b.WriteString(terms[i].String()); err != nil { return nil, err } @@ -895,6 +934,15 @@ func DisableInlining(paths []string) func(r *Rego) { } } +// NondeterministicBuiltins causes non-deterministic builtins to be evalued during +// partial evaluation. This is needed to pull in external data, or validate a JWT, +// during PE, so that the result informs what queries are returned. +func NondeterministicBuiltins(yes bool) func(r *Rego) { + return func(r *Rego) { + r.nondeterministicBuiltins = yes + } +} + // ShallowInlining prevents rules that depend on unknown values from being inlined. // Rules that only depend on known values are inlined. func ShallowInlining(yes bool) func(r *Rego) { @@ -993,6 +1041,15 @@ func Store(s storage.Store) func(r *Rego) { } } +// StoreReadAST returns an argument that sets whether the store should eagerly convert data to AST values. +// +// Only applicable when no store has been set on the Rego object through the Store option. +func StoreReadAST(enabled bool) func(r *Rego) { + return func(r *Rego) { + r.ownStoreReadAst = enabled + } +} + // Transaction returns an argument that sets the transaction to use for storage // layer operations. // @@ -1114,6 +1171,14 @@ func InterQueryBuiltinCache(c cache.InterQueryCache) func(r *Rego) { } } +// InterQueryBuiltinValueCache sets the inter-query value cache that built-in functions can utilize +// during evaluation. +func InterQueryBuiltinValueCache(c cache.InterQueryValueCache) func(r *Rego) { + return func(r *Rego) { + r.interQueryBuiltinValueCache = c + } +} + // NDBuiltinCache sets the non-deterministic builtins cache. func NDBuiltinCache(c builtins.NDBCache) func(r *Rego) { return func(r *Rego) { @@ -1241,10 +1306,14 @@ func New(options ...func(r *Rego)) *Rego { if r.target == targetWasm { r.compiler = r.compiler.WithEvalMode(ast.EvalModeIR) } + + if r.regoVersion != ast.RegoUndefined { + r.compiler = r.compiler.WithDefaultRegoVersion(r.regoVersion) + } } if r.store == nil { - r.store = inmem.New() + r.store = inmem.NewWithOpts(inmem.OptReturnASTValuesOnRead(r.ownStoreReadAst)) r.ownStore = true } else { r.ownStore = false @@ -1309,6 +1378,7 @@ func (r *Rego) Eval(ctx context.Context) (ResultSet, error) { EvalInstrument(r.instrument), EvalTime(r.time), EvalInterQueryBuiltinCache(r.interQueryBuiltinCache), + EvalInterQueryBuiltinValueCache(r.interQueryBuiltinValueCache), EvalSeed(r.seed), } @@ -1386,6 +1456,7 @@ func (r *Rego) Partial(ctx context.Context) (*PartialQueries, error) { EvalMetrics(r.metrics), EvalInstrument(r.instrument), EvalInterQueryBuiltinCache(r.interQueryBuiltinCache), + EvalInterQueryBuiltinValueCache(r.interQueryBuiltinValueCache), } if r.ndBuiltinCache != nil { @@ -1685,9 +1756,6 @@ func (r *Rego) PrepareForEval(ctx context.Context, opts ...PrepareOption) (Prepa } txnErr := txnClose(ctx, err) // Always call closer - if err != nil { - return PreparedEvalQuery{}, err - } if txnErr != nil { return PreparedEvalQuery{}, txnErr } @@ -1863,6 +1931,7 @@ func (r *Rego) loadFiles(ctx context.Context, txn storage.Transaction, m metrics WithMetrics(m). WithProcessAnnotation(true). WithRegoVersion(r.regoVersion). + WithCapabilities(r.capabilities). Filtered(r.loadPaths.paths, r.loadPaths.filter) if err != nil { return err @@ -1894,6 +1963,7 @@ func (r *Rego) loadBundles(_ context.Context, _ storage.Transaction, m metrics.M WithProcessAnnotation(true). WithSkipBundleVerification(r.skipBundleVerification). WithRegoVersion(r.regoVersion). + WithCapabilities(r.capabilities). AsBundle(path) if err != nil { return fmt.Errorf("loading error: %s", err) @@ -1943,6 +2013,7 @@ func (r *Rego) parseQuery(queryImports []*ast.Import, m metrics.Metrics) (ast.Bo if err != nil { return nil, err } + popts.RegoVersion = r.regoVersion popts, err = parserOptionsFromRegoVersionImport(queryImports, popts) if err != nil { return nil, err @@ -2106,6 +2177,7 @@ func (r *Rego) eval(ctx context.Context, ectx *EvalContext) (ResultSet, error) { WithIndexing(ectx.indexing). WithEarlyExit(ectx.earlyExit). WithInterQueryBuiltinCache(ectx.interQueryBuiltinCache). + WithInterQueryBuiltinValueCache(ectx.interQueryBuiltinValueCache). WithStrictBuiltinErrors(r.strictBuiltinErrors). WithBuiltinErrorList(r.builtinErrorList). WithSeed(ectx.seed). @@ -2129,6 +2201,10 @@ func (r *Rego) eval(ctx context.Context, ectx *EvalContext) (ResultSet, error) { q = q.WithInput(ast.NewTerm(ectx.parsedInput)) } + if ectx.httpRoundTripper != nil { + q = q.WithHTTPRoundTripper(ectx.httpRoundTripper) + } + for i := range ectx.resolvers { q = q.WithResolver(ectx.resolvers[i].ref, ectx.resolvers[i].r) } @@ -2164,7 +2240,6 @@ func (r *Rego) eval(ctx context.Context, ectx *EvalContext) (ResultSet, error) { } func (r *Rego) evalWasm(ctx context.Context, ectx *EvalContext) (ResultSet, error) { - input := ectx.rawInput if ectx.parsedInput != nil { i := interface{}(ectx.parsedInput) @@ -2280,17 +2355,18 @@ func (r *Rego) partialResult(ctx context.Context, pCfg *PrepareConfig) (PartialR } ectx := &EvalContext{ - parsedInput: r.parsedInput, - metrics: r.metrics, - txn: r.txn, - partialNamespace: r.partialNamespace, - queryTracers: r.queryTracers, - compiledQuery: r.compiledQueries[partialResultQueryType], - instrumentation: r.instrumentation, - indexing: true, - resolvers: r.resolvers, - capabilities: r.capabilities, - strictBuiltinErrors: r.strictBuiltinErrors, + parsedInput: r.parsedInput, + metrics: r.metrics, + txn: r.txn, + partialNamespace: r.partialNamespace, + queryTracers: r.queryTracers, + compiledQuery: r.compiledQueries[partialResultQueryType], + instrumentation: r.instrumentation, + indexing: true, + resolvers: r.resolvers, + capabilities: r.capabilities, + strictBuiltinErrors: r.strictBuiltinErrors, + nondeterministicBuiltins: r.nondeterministicBuiltins, } disableInlining := r.disableInlining @@ -2312,7 +2388,8 @@ func (r *Rego) partialResult(ctx context.Context, pCfg *PrepareConfig) (PartialR // Construct module for queries. id := fmt.Sprintf("__partialresult__%s__", ectx.partialNamespace) - module, err := ast.ParseModule(id, "package "+ectx.partialNamespace) + module, err := ast.ParseModuleWithOpts(id, "package "+ectx.partialNamespace, + ast.ParserOptions{RegoVersion: r.regoVersion}) if err != nil { return PartialResult{}, fmt.Errorf("bad partial namespace") } @@ -2386,6 +2463,7 @@ func (r *Rego) partial(ctx context.Context, ectx *EvalContext) (*PartialQueries, WithInstrumentation(ectx.instrumentation). WithUnknowns(unknowns). WithDisableInlining(ectx.disableInlining). + WithNondeterministicBuiltins(ectx.nondeterministicBuiltins). WithRuntime(r.runtime). WithIndexing(ectx.indexing). WithEarlyExit(ectx.earlyExit). @@ -2393,6 +2471,7 @@ func (r *Rego) partial(ctx context.Context, ectx *EvalContext) (*PartialQueries, WithSkipPartialNamespace(r.skipPartialNamespace). WithShallowInlining(r.shallowInlining). WithInterQueryBuiltinCache(ectx.interQueryBuiltinCache). + WithInterQueryBuiltinValueCache(ectx.interQueryBuiltinValueCache). WithStrictBuiltinErrors(ectx.strictBuiltinErrors). WithSeed(ectx.seed). WithPrintHook(ectx.printHook) @@ -2431,14 +2510,13 @@ func (r *Rego) partial(ctx context.Context, ectx *EvalContext) (*PartialQueries, return nil, err } - if r.regoVersion == ast.RegoV0 && (r.capabilities == nil || r.capabilities.ContainsFeature(ast.FeatureRegoV1Import)) { - // If the target rego-version in v0, and the rego.v1 import is available, then we attempt to apply it to support modules. + // If the target rego-version is v0, and the rego.v1 import is available, then we attempt to apply it to support modules. + if r.regoVersion == ast.RegoV0 && + (r.capabilities == nil || + r.capabilities.ContainsFeature(ast.FeatureRegoV1Import) || + r.capabilities.ContainsFeature(ast.FeatureRegoV1)) { for i, mod := range support { - if mod.RegoVersion() != ast.RegoV0 { - continue - } - // We can't apply the RegoV0CompatV1 version to the support module if it contains rules or vars that // conflict with future keywords. applyRegoVersion := true @@ -2448,7 +2526,7 @@ func (r *Rego) partial(ctx context.Context, ectx *EvalContext) (*PartialQueries, if name == "" && len(r.Head.Reference) > 0 { name = r.Head.Reference[0].Value.(ast.Var) } - if ast.IsFutureKeyword(name.String()) { + if ast.IsFutureKeywordForRegoVersion(name.String(), ast.RegoV0) { applyRegoVersion = false return true } @@ -2457,7 +2535,7 @@ func (r *Rego) partial(ctx context.Context, ectx *EvalContext) (*PartialQueries, if applyRegoVersion { ast.WalkVars(mod, func(v ast.Var) bool { - if ast.IsFutureKeyword(v.String()) { + if ast.IsFutureKeywordForRegoVersion(v.String(), ast.RegoV0) { applyRegoVersion = false return true } @@ -2543,7 +2621,7 @@ func (r *Rego) rewriteQueryForPartialEval(_ ast.QueryCompiler, query ast.Body) ( ref, ok := term.Value.(ast.Ref) if !ok { - return nil, fmt.Errorf("partial evaluation requires ref (not %v)", ast.TypeName(term.Value)) + return nil, fmt.Errorf("partial evaluation requires ref (not %v)", ast.ValueName(term.Value)) } if !ref.IsGround() { diff --git a/vendor/github.com/open-policy-agent/opa/rego/resultset.go b/vendor/github.com/open-policy-agent/opa/v1/rego/resultset.go similarity index 98% rename from vendor/github.com/open-policy-agent/opa/rego/resultset.go rename to vendor/github.com/open-policy-agent/opa/v1/rego/resultset.go index e60fa6fbe4..cc0710426e 100644 --- a/vendor/github.com/open-policy-agent/opa/rego/resultset.go +++ b/vendor/github.com/open-policy-agent/opa/v1/rego/resultset.go @@ -3,7 +3,7 @@ package rego import ( "fmt" - "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/v1/ast" ) // ResultSet represents a collection of output from Rego evaluation. An empty diff --git a/vendor/github.com/open-policy-agent/opa/resolver/interface.go b/vendor/github.com/open-policy-agent/opa/v1/resolver/interface.go similarity index 86% rename from vendor/github.com/open-policy-agent/opa/resolver/interface.go rename to vendor/github.com/open-policy-agent/opa/v1/resolver/interface.go index fc02329f57..1f04d21c01 100644 --- a/vendor/github.com/open-policy-agent/opa/resolver/interface.go +++ b/vendor/github.com/open-policy-agent/opa/v1/resolver/interface.go @@ -7,8 +7,8 @@ package resolver import ( "context" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/metrics" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/metrics" ) // Resolver defines an external value resolver for OPA evaluations. diff --git a/vendor/github.com/open-policy-agent/opa/resolver/wasm/wasm.go b/vendor/github.com/open-policy-agent/opa/v1/resolver/wasm/wasm.go similarity index 97% rename from vendor/github.com/open-policy-agent/opa/resolver/wasm/wasm.go rename to vendor/github.com/open-policy-agent/opa/v1/resolver/wasm/wasm.go index 9c13879dc3..4f57b3ef82 100644 --- a/vendor/github.com/open-policy-agent/opa/resolver/wasm/wasm.go +++ b/vendor/github.com/open-policy-agent/opa/v1/resolver/wasm/wasm.go @@ -9,9 +9,9 @@ import ( "fmt" "strconv" - "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/internal/rego/opa" - "github.com/open-policy-agent/opa/resolver" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/resolver" ) // New creates a new Resolver instance which is using the Wasm module diff --git a/vendor/github.com/open-policy-agent/opa/schemas/authorizationPolicy.json b/vendor/github.com/open-policy-agent/opa/v1/schemas/authorizationPolicy.json similarity index 100% rename from vendor/github.com/open-policy-agent/opa/schemas/authorizationPolicy.json rename to vendor/github.com/open-policy-agent/opa/v1/schemas/authorizationPolicy.json diff --git a/vendor/github.com/open-policy-agent/opa/schemas/schemas.go b/vendor/github.com/open-policy-agent/opa/v1/schemas/schemas.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/schemas/schemas.go rename to vendor/github.com/open-policy-agent/opa/v1/schemas/schemas.go diff --git a/vendor/github.com/open-policy-agent/opa/storage/doc.go b/vendor/github.com/open-policy-agent/opa/v1/storage/doc.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/storage/doc.go rename to vendor/github.com/open-policy-agent/opa/v1/storage/doc.go diff --git a/vendor/github.com/open-policy-agent/opa/storage/errors.go b/vendor/github.com/open-policy-agent/opa/v1/storage/errors.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/storage/errors.go rename to vendor/github.com/open-policy-agent/opa/v1/storage/errors.go diff --git a/vendor/github.com/open-policy-agent/opa/v1/storage/inmem/ast.go b/vendor/github.com/open-policy-agent/opa/v1/storage/inmem/ast.go new file mode 100644 index 0000000000..667ca608e0 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/v1/storage/inmem/ast.go @@ -0,0 +1,314 @@ +// Copyright 2024 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package inmem + +import ( + "fmt" + "strconv" + + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/storage" + "github.com/open-policy-agent/opa/v1/storage/internal/errors" + "github.com/open-policy-agent/opa/v1/storage/internal/ptr" +) + +type updateAST struct { + path storage.Path // data path modified by update + remove bool // indicates whether update removes the value at path + value ast.Value // value to add/replace at path (ignored if remove is true) +} + +func (u *updateAST) Path() storage.Path { + return u.path +} + +func (u *updateAST) Remove() bool { + return u.remove +} + +func (u *updateAST) Set(v interface{}) { + if v, ok := v.(ast.Value); ok { + u.value = v + } else { + panic("illegal value type") // FIXME: do conversion? + } +} + +func (u *updateAST) Value() interface{} { + return u.value +} + +func (u *updateAST) Relative(path storage.Path) dataUpdate { + cpy := *u + cpy.path = cpy.path[len(path):] + return &cpy +} + +func (u *updateAST) Apply(v interface{}) interface{} { + if len(u.path) == 0 { + return u.value + } + + data, ok := v.(ast.Value) + if !ok { + panic(fmt.Errorf("illegal value type %T, expected ast.Value", v)) + } + + if u.remove { + newV, err := removeInAst(data, u.path) + if err != nil { + panic(err) + } + return newV + } + + // If we're not removing, we're replacing (adds are turned into replaces during updateAST creation). + newV, err := setInAst(data, u.path, u.value) + if err != nil { + panic(err) + } + return newV +} + +func newUpdateAST(data interface{}, op storage.PatchOp, path storage.Path, idx int, value ast.Value) (*updateAST, error) { + + switch data.(type) { + case ast.Null, ast.Boolean, ast.Number, ast.String: + return nil, errors.NewNotFoundError(path) + } + + switch data := data.(type) { + case ast.Object: + return newUpdateObjectAST(data, op, path, idx, value) + + case *ast.Array: + return newUpdateArrayAST(data, op, path, idx, value) + } + + return nil, &storage.Error{ + Code: storage.InternalErr, + Message: "invalid data value encountered", + } +} + +func newUpdateArrayAST(data *ast.Array, op storage.PatchOp, path storage.Path, idx int, value ast.Value) (*updateAST, error) { + + if idx == len(path)-1 { + if path[idx] == "-" || path[idx] == strconv.Itoa(data.Len()) { + if op != storage.AddOp { + return nil, invalidPatchError("%v: invalid patch path", path) + } + + cpy := data.Copy() + cpy = cpy.Append(ast.NewTerm(value)) + return &updateAST{path[:len(path)-1], false, cpy}, nil + } + + pos, err := ptr.ValidateASTArrayIndex(data, path[idx], path) + if err != nil { + return nil, err + } + + switch op { + case storage.AddOp: + var results []*ast.Term + for i := 0; i < data.Len(); i++ { + if i == pos { + results = append(results, ast.NewTerm(value)) + } + results = append(results, data.Elem(i)) + } + + return &updateAST{path[:len(path)-1], false, ast.NewArray(results...)}, nil + + case storage.RemoveOp: + var results []*ast.Term + for i := 0; i < data.Len(); i++ { + if i != pos { + results = append(results, data.Elem(i)) + } + } + return &updateAST{path[:len(path)-1], false, ast.NewArray(results...)}, nil + + default: + var results []*ast.Term + for i := 0; i < data.Len(); i++ { + if i == pos { + results = append(results, ast.NewTerm(value)) + } else { + results = append(results, data.Elem(i)) + } + } + + return &updateAST{path[:len(path)-1], false, ast.NewArray(results...)}, nil + } + } + + pos, err := ptr.ValidateASTArrayIndex(data, path[idx], path) + if err != nil { + return nil, err + } + + return newUpdateAST(data.Elem(pos).Value, op, path, idx+1, value) +} + +func newUpdateObjectAST(data ast.Object, op storage.PatchOp, path storage.Path, idx int, value ast.Value) (*updateAST, error) { + key := ast.StringTerm(path[idx]) + val := data.Get(key) + + if idx == len(path)-1 { + switch op { + case storage.ReplaceOp, storage.RemoveOp: + if val == nil { + return nil, errors.NewNotFoundError(path) + } + } + return &updateAST{path, op == storage.RemoveOp, value}, nil + } + + if val != nil { + return newUpdateAST(val.Value, op, path, idx+1, value) + } + + return nil, errors.NewNotFoundError(path) +} + +func interfaceToValue(v interface{}) (ast.Value, error) { + if v, ok := v.(ast.Value); ok { + return v, nil + } + return ast.InterfaceToValue(v) +} + +// setInAst updates the value in the AST at the given path with the given value. +// Values can only be replaced in arrays, not added. +// Values for new keys can be added to objects +func setInAst(data ast.Value, path storage.Path, value ast.Value) (ast.Value, error) { + if len(path) == 0 { + return data, nil + } + + switch data := data.(type) { + case ast.Object: + return setInAstObject(data, path, value) + case *ast.Array: + return setInAstArray(data, path, value) + default: + return nil, fmt.Errorf("illegal value type %T, expected ast.Object or ast.Array", data) + } +} + +func setInAstObject(obj ast.Object, path storage.Path, value ast.Value) (ast.Value, error) { + key := ast.StringTerm(path[0]) + + if len(path) == 1 { + obj.Insert(key, ast.NewTerm(value)) + return obj, nil + } + + child := obj.Get(key) + newChild, err := setInAst(child.Value, path[1:], value) + if err != nil { + return nil, err + } + obj.Insert(key, ast.NewTerm(newChild)) + return obj, nil +} + +func setInAstArray(arr *ast.Array, path storage.Path, value ast.Value) (ast.Value, error) { + idx, err := strconv.Atoi(path[0]) + if err != nil { + return nil, fmt.Errorf("illegal array index %v: %v", path[0], err) + } + + if idx < 0 || idx >= arr.Len() { + return arr, nil + } + + if len(path) == 1 { + arr.Set(idx, ast.NewTerm(value)) + return arr, nil + } + + child := arr.Elem(idx) + newChild, err := setInAst(child.Value, path[1:], value) + if err != nil { + return nil, err + } + arr.Set(idx, ast.NewTerm(newChild)) + return arr, nil +} + +func removeInAst(value ast.Value, path storage.Path) (ast.Value, error) { + if len(path) == 0 { + return value, nil + } + + switch value := value.(type) { + case ast.Object: + return removeInAstObject(value, path) + case *ast.Array: + return removeInAstArray(value, path) + default: + return nil, fmt.Errorf("illegal value type %T, expected ast.Object or ast.Array", value) + } +} + +func removeInAstObject(obj ast.Object, path storage.Path) (ast.Value, error) { + key := ast.StringTerm(path[0]) + + if len(path) == 1 { + var items [][2]*ast.Term + // Note: possibly expensive operation for large data. + obj.Foreach(func(k *ast.Term, v *ast.Term) { + if k.Equal(key) { + return + } + items = append(items, [2]*ast.Term{k, v}) + }) + return ast.NewObject(items...), nil + } + + if child := obj.Get(key); child != nil { + updatedChild, err := removeInAst(child.Value, path[1:]) + if err != nil { + return nil, err + } + obj.Insert(key, ast.NewTerm(updatedChild)) + } + + return obj, nil +} + +func removeInAstArray(arr *ast.Array, path storage.Path) (ast.Value, error) { + idx, err := strconv.Atoi(path[0]) + if err != nil { + // We expect the path to be valid at this point. + return arr, nil + } + + if idx < 0 || idx >= arr.Len() { + return arr, err + } + + if len(path) == 1 { + var elems []*ast.Term + // Note: possibly expensive operation for large data. + for i := 0; i < arr.Len(); i++ { + if i == idx { + continue + } + elems = append(elems, arr.Elem(i)) + } + return ast.NewArray(elems...), nil + } + + updatedChild, err := removeInAst(arr.Elem(idx).Value, path[1:]) + if err != nil { + return nil, err + } + arr.Set(idx, ast.NewTerm(updatedChild)) + return arr, nil +} diff --git a/vendor/github.com/open-policy-agent/opa/storage/inmem/inmem.go b/vendor/github.com/open-policy-agent/opa/v1/storage/inmem/inmem.go similarity index 85% rename from vendor/github.com/open-policy-agent/opa/storage/inmem/inmem.go rename to vendor/github.com/open-policy-agent/opa/v1/storage/inmem/inmem.go index b6433795a3..7c5116b527 100644 --- a/vendor/github.com/open-policy-agent/opa/storage/inmem/inmem.go +++ b/vendor/github.com/open-policy-agent/opa/v1/storage/inmem/inmem.go @@ -25,8 +25,9 @@ import ( "sync/atomic" "github.com/open-policy-agent/opa/internal/merge" - "github.com/open-policy-agent/opa/storage" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/storage" + "github.com/open-policy-agent/opa/v1/util" ) // New returns an empty in-memory store. @@ -37,16 +38,22 @@ func New() storage.Store { // NewWithOpts returns an empty in-memory store, with extra options passed. func NewWithOpts(opts ...Opt) storage.Store { s := &store{ - data: map[string]interface{}{}, - triggers: map[*handle]storage.TriggerConfig{}, - policies: map[string][]byte{}, - roundTripOnWrite: true, + triggers: map[*handle]storage.TriggerConfig{}, + policies: map[string][]byte{}, + roundTripOnWrite: true, + returnASTValuesOnRead: false, } for _, opt := range opts { opt(s) } + if s.returnASTValuesOnRead { + s.data = ast.NewObject() + } else { + s.data = map[string]interface{}{} + } + return s } @@ -55,7 +62,7 @@ func NewFromObject(data map[string]interface{}) storage.Store { return NewFromObjectWithOpts(data) } -// NewFromObject returns a new in-memory store from the supplied data object, with the +// NewFromObjectWithOpts returns a new in-memory store from the supplied data object, with the // options passed. func NewFromObjectWithOpts(data map[string]interface{}, opts ...Opt) storage.Store { db := NewWithOpts(opts...) @@ -94,13 +101,18 @@ type store struct { rmu sync.RWMutex // reader-writer lock wmu sync.Mutex // writer lock xid uint64 // last generated transaction id - data map[string]interface{} // raw data + data interface{} // raw or AST data policies map[string][]byte // raw policies triggers map[*handle]storage.TriggerConfig // registered triggers // roundTripOnWrite, if true, means that every call to Write round trips the // data through JSON before adding the data to the store. Defaults to true. roundTripOnWrite bool + + // returnASTValuesOnRead, if true, means that the store will eagerly convert data to AST values, + // and return them on Read. + // FIXME: naming(?) + returnASTValuesOnRead bool } type handle struct { @@ -295,7 +307,13 @@ func (db *store) Read(_ context.Context, txn storage.Transaction, path storage.P if err != nil { return nil, err } - return underlying.Read(path) + + v, err := underlying.Read(path) + if err != nil { + return nil, err + } + + return v, nil } func (db *store) Write(_ context.Context, txn storage.Transaction, op storage.PatchOp, path storage.Path, value interface{}) error { @@ -327,11 +345,45 @@ func (h *handle) Unregister(_ context.Context, txn storage.Transaction) { } func (db *store) runOnCommitTriggers(ctx context.Context, txn storage.Transaction, event storage.TriggerEvent) { + if db.returnASTValuesOnRead && len(db.triggers) > 0 { + // FIXME: Not very performant for large data. + + dataEvents := make([]storage.DataEvent, 0, len(event.Data)) + + for _, dataEvent := range event.Data { + if astData, ok := dataEvent.Data.(ast.Value); ok { + jsn, err := ast.ValueToInterface(astData, illegalResolver{}) + if err != nil { + panic(err) + } + dataEvents = append(dataEvents, storage.DataEvent{ + Path: dataEvent.Path, + Data: jsn, + Removed: dataEvent.Removed, + }) + } else { + dataEvents = append(dataEvents, dataEvent) + } + } + + event = storage.TriggerEvent{ + Policy: event.Policy, + Data: dataEvents, + Context: event.Context, + } + } + for _, t := range db.triggers { t.OnCommit(ctx, txn, event) } } +type illegalResolver struct{} + +func (illegalResolver) Resolve(ref ast.Ref) (interface{}, error) { + return nil, fmt.Errorf("illegal value: %v", ref) +} + func (db *store) underlying(txn storage.Transaction) (*transaction, error) { underlying, ok := txn.(*transaction) if !ok { diff --git a/vendor/github.com/open-policy-agent/opa/storage/inmem/opts.go b/vendor/github.com/open-policy-agent/opa/v1/storage/inmem/opts.go similarity index 63% rename from vendor/github.com/open-policy-agent/opa/storage/inmem/opts.go rename to vendor/github.com/open-policy-agent/opa/v1/storage/inmem/opts.go index fb8dc8e2bf..2239fc73a3 100644 --- a/vendor/github.com/open-policy-agent/opa/storage/inmem/opts.go +++ b/vendor/github.com/open-policy-agent/opa/v1/storage/inmem/opts.go @@ -23,3 +23,15 @@ func OptRoundTripOnWrite(enabled bool) Opt { s.roundTripOnWrite = enabled } } + +// OptReturnASTValuesOnRead sets whether data values added to the store should be +// eagerly converted to AST values, which are then returned on read. +// +// When enabled, this feature does not sanity check data before converting it to AST values, +// which may result in panics if the data is not valid. Callers should ensure that passed data +// can be serialized to AST values; otherwise, it's recommended to also enable OptRoundTripOnWrite. +func OptReturnASTValuesOnRead(enabled bool) Opt { + return func(s *store) { + s.returnASTValuesOnRead = enabled + } +} diff --git a/vendor/github.com/open-policy-agent/opa/storage/inmem/txn.go b/vendor/github.com/open-policy-agent/opa/v1/storage/inmem/txn.go similarity index 65% rename from vendor/github.com/open-policy-agent/opa/storage/inmem/txn.go rename to vendor/github.com/open-policy-agent/opa/v1/storage/inmem/txn.go index 3a61018291..f8a7303912 100644 --- a/vendor/github.com/open-policy-agent/opa/storage/inmem/txn.go +++ b/vendor/github.com/open-policy-agent/opa/v1/storage/inmem/txn.go @@ -10,9 +10,10 @@ import ( "strconv" "github.com/open-policy-agent/opa/internal/deepcopy" - "github.com/open-policy-agent/opa/storage" - "github.com/open-policy-agent/opa/storage/internal/errors" - "github.com/open-policy-agent/opa/storage/internal/ptr" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/storage" + "github.com/open-policy-agent/opa/v1/storage/internal/errors" + "github.com/open-policy-agent/opa/v1/storage/internal/ptr" ) // transaction implements the low-level read/write operations on the in-memory @@ -76,13 +77,13 @@ func (txn *transaction) Write(op storage.PatchOp, path storage.Path, value inter } for curr := txn.updates.Front(); curr != nil; { - update := curr.Value.(*update) + update := curr.Value.(dataUpdate) // Check if new update masks existing update exactly. In this case, the // existing update can be removed and no other updates have to be // visited (because no two updates overlap.) - if update.path.Equal(path) { - if update.remove { + if update.Path().Equal(path) { + if update.Remove() { if op != storage.AddOp { return errors.NewNotFoundError(path) } @@ -94,7 +95,7 @@ func (txn *transaction) Write(op storage.PatchOp, path storage.Path, value inter // Check if new update masks existing update. In this case, the // existing update has to be removed but other updates may overlap, so // we must continue. - if update.path.HasPrefix(path) { + if update.Path().HasPrefix(path) { remove := curr curr = curr.Next() txn.updates.Remove(remove) @@ -103,23 +104,23 @@ func (txn *transaction) Write(op storage.PatchOp, path storage.Path, value inter // Check if new update modifies existing update. In this case, the // existing update is mutated. - if path.HasPrefix(update.path) { - if update.remove { + if path.HasPrefix(update.Path()) { + if update.Remove() { return errors.NewNotFoundError(path) } - suffix := path[len(update.path):] - newUpdate, err := newUpdate(update.value, op, suffix, 0, value) + suffix := path[len(update.Path()):] + newUpdate, err := txn.db.newUpdate(update.Value(), op, suffix, 0, value) if err != nil { return err } - update.value = newUpdate.Apply(update.value) + update.Set(newUpdate.Apply(update.Value())) return nil } curr = curr.Next() } - update, err := newUpdate(txn.db.data, op, path, 0, value) + update, err := txn.db.newUpdate(txn.db.data, op, path, 0, value) if err != nil { return err } @@ -132,72 +133,115 @@ func (txn *transaction) updateRoot(op storage.PatchOp, value interface{}) error if op == storage.RemoveOp { return invalidPatchError(rootCannotBeRemovedMsg) } - if _, ok := value.(map[string]interface{}); !ok { - return invalidPatchError(rootMustBeObjectMsg) + + var update any + if txn.db.returnASTValuesOnRead { + valueAST, err := interfaceToValue(value) + if err != nil { + return err + } + if _, ok := valueAST.(ast.Object); !ok { + return invalidPatchError(rootMustBeObjectMsg) + } + + update = &updateAST{ + path: storage.Path{}, + remove: false, + value: valueAST, + } + } else { + if _, ok := value.(map[string]interface{}); !ok { + return invalidPatchError(rootMustBeObjectMsg) + } + + update = &updateRaw{ + path: storage.Path{}, + remove: false, + value: value, + } } + txn.updates.Init() - txn.updates.PushFront(&update{ - path: storage.Path{}, - remove: false, - value: value, - }) + txn.updates.PushFront(update) return nil } func (txn *transaction) Commit() (result storage.TriggerEvent) { result.Context = txn.context for curr := txn.updates.Front(); curr != nil; curr = curr.Next() { - action := curr.Value.(*update) - updated := action.Apply(txn.db.data) - txn.db.data = updated.(map[string]interface{}) + action := curr.Value.(dataUpdate) + txn.db.data = action.Apply(txn.db.data) result.Data = append(result.Data, storage.DataEvent{ - Path: action.path, - Data: action.value, - Removed: action.remove, + Path: action.Path(), + Data: action.Value(), + Removed: action.Remove(), }) } - for id, update := range txn.policies { - if update.remove { + for id, upd := range txn.policies { + if upd.remove { delete(txn.db.policies, id) } else { - txn.db.policies[id] = update.value + txn.db.policies[id] = upd.value } result.Policy = append(result.Policy, storage.PolicyEvent{ ID: id, - Data: update.value, - Removed: update.remove, + Data: upd.value, + Removed: upd.remove, }) } return result } +func pointer(v interface{}, path storage.Path) (interface{}, error) { + if v, ok := v.(ast.Value); ok { + return ptr.ValuePtr(v, path) + } + return ptr.Ptr(v, path) +} + +func deepcpy(v interface{}) interface{} { + if v, ok := v.(ast.Value); ok { + var cpy ast.Value + + switch data := v.(type) { + case ast.Object: + cpy = data.Copy() + case *ast.Array: + cpy = data.Copy() + } + + return cpy + } + return deepcopy.DeepCopy(v) +} + func (txn *transaction) Read(path storage.Path) (interface{}, error) { if !txn.write { - return ptr.Ptr(txn.db.data, path) + return pointer(txn.db.data, path) } - merge := []*update{} + var merge []dataUpdate for curr := txn.updates.Front(); curr != nil; curr = curr.Next() { - update := curr.Value.(*update) + upd := curr.Value.(dataUpdate) - if path.HasPrefix(update.path) { - if update.remove { + if path.HasPrefix(upd.Path()) { + if upd.Remove() { return nil, errors.NewNotFoundError(path) } - return ptr.Ptr(update.value, path[len(update.path):]) + return pointer(upd.Value(), path[len(upd.Path()):]) } - if update.path.HasPrefix(path) { - merge = append(merge, update) + if upd.Path().HasPrefix(path) { + merge = append(merge, upd) } } - data, err := ptr.Ptr(txn.db.data, path) + data, err := pointer(txn.db.data, path) if err != nil { return nil, err @@ -207,7 +251,7 @@ func (txn *transaction) Read(path storage.Path) (interface{}, error) { return data, nil } - cpy := deepcopy.DeepCopy(data) + cpy := deepcpy(data) for _, update := range merge { cpy = update.Relative(path).Apply(cpy) @@ -266,15 +310,44 @@ func (txn *transaction) DeletePolicy(id string) error { return nil } +type dataUpdate interface { + Path() storage.Path + Remove() bool + Apply(interface{}) interface{} + Relative(path storage.Path) dataUpdate + Set(interface{}) + Value() interface{} +} + // update contains state associated with an update to be applied to the // in-memory data store. -type update struct { +type updateRaw struct { path storage.Path // data path modified by update remove bool // indicates whether update removes the value at path value interface{} // value to add/replace at path (ignored if remove is true) } -func newUpdate(data interface{}, op storage.PatchOp, path storage.Path, idx int, value interface{}) (*update, error) { +func (db *store) newUpdate(data interface{}, op storage.PatchOp, path storage.Path, idx int, value interface{}) (dataUpdate, error) { + if db.returnASTValuesOnRead { + astData, err := interfaceToValue(data) + if err != nil { + return nil, err + } + astValue, err := interfaceToValue(value) + if err != nil { + return nil, err + } + return newUpdateAST(astData, op, path, idx, astValue) + } + return newUpdateRaw(data, op, path, idx, value) +} + +func newUpdateRaw(data interface{}, op storage.PatchOp, path storage.Path, idx int, value interface{}) (dataUpdate, error) { + + switch data.(type) { + case nil, bool, json.Number, string: + return nil, errors.NewNotFoundError(path) + } switch data := data.(type) { case map[string]interface{}: @@ -282,9 +355,6 @@ func newUpdate(data interface{}, op storage.PatchOp, path storage.Path, idx int, case []interface{}: return newUpdateArray(data, op, path, idx, value) - - case nil, bool, json.Number, string: - return nil, errors.NewNotFoundError(path) } return nil, &storage.Error{ @@ -293,7 +363,7 @@ func newUpdate(data interface{}, op storage.PatchOp, path storage.Path, idx int, } } -func newUpdateArray(data []interface{}, op storage.PatchOp, path storage.Path, idx int, value interface{}) (*update, error) { +func newUpdateArray(data []interface{}, op storage.PatchOp, path storage.Path, idx int, value interface{}) (dataUpdate, error) { if idx == len(path)-1 { if path[idx] == "-" || path[idx] == strconv.Itoa(len(data)) { @@ -303,7 +373,7 @@ func newUpdateArray(data []interface{}, op storage.PatchOp, path storage.Path, i cpy := make([]interface{}, len(data)+1) copy(cpy, data) cpy[len(data)] = value - return &update{path[:len(path)-1], false, cpy}, nil + return &updateRaw{path[:len(path)-1], false, cpy}, nil } pos, err := ptr.ValidateArrayIndex(data, path[idx], path) @@ -317,19 +387,19 @@ func newUpdateArray(data []interface{}, op storage.PatchOp, path storage.Path, i copy(cpy[:pos], data[:pos]) copy(cpy[pos+1:], data[pos:]) cpy[pos] = value - return &update{path[:len(path)-1], false, cpy}, nil + return &updateRaw{path[:len(path)-1], false, cpy}, nil case storage.RemoveOp: cpy := make([]interface{}, len(data)-1) copy(cpy[:pos], data[:pos]) copy(cpy[pos:], data[pos+1:]) - return &update{path[:len(path)-1], false, cpy}, nil + return &updateRaw{path[:len(path)-1], false, cpy}, nil default: cpy := make([]interface{}, len(data)) copy(cpy, data) cpy[pos] = value - return &update{path[:len(path)-1], false, cpy}, nil + return &updateRaw{path[:len(path)-1], false, cpy}, nil } } @@ -338,10 +408,10 @@ func newUpdateArray(data []interface{}, op storage.PatchOp, path storage.Path, i return nil, err } - return newUpdate(data[pos], op, path, idx+1, value) + return newUpdateRaw(data[pos], op, path, idx+1, value) } -func newUpdateObject(data map[string]interface{}, op storage.PatchOp, path storage.Path, idx int, value interface{}) (*update, error) { +func newUpdateObject(data map[string]interface{}, op storage.PatchOp, path storage.Path, idx int, value interface{}) (dataUpdate, error) { if idx == len(path)-1 { switch op { @@ -350,16 +420,25 @@ func newUpdateObject(data map[string]interface{}, op storage.PatchOp, path stora return nil, errors.NewNotFoundError(path) } } - return &update{path, op == storage.RemoveOp, value}, nil + return &updateRaw{path, op == storage.RemoveOp, value}, nil } if data, ok := data[path[idx]]; ok { - return newUpdate(data, op, path, idx+1, value) + return newUpdateRaw(data, op, path, idx+1, value) } return nil, errors.NewNotFoundError(path) } -func (u *update) Apply(data interface{}) interface{} { + +func (u *updateRaw) Remove() bool { + return u.remove +} + +func (u *updateRaw) Path() storage.Path { + return u.path +} + +func (u *updateRaw) Apply(data interface{}) interface{} { if len(u.path) == 0 { return u.value } @@ -389,7 +468,15 @@ func (u *update) Apply(data interface{}) interface{} { return data } -func (u *update) Relative(path storage.Path) *update { +func (u *updateRaw) Set(v interface{}) { + u.value = v +} + +func (u *updateRaw) Value() interface{} { + return u.value +} + +func (u *updateRaw) Relative(path storage.Path) dataUpdate { cpy := *u cpy.path = cpy.path[len(path):] return &cpy diff --git a/vendor/github.com/open-policy-agent/opa/storage/interface.go b/vendor/github.com/open-policy-agent/opa/v1/storage/interface.go similarity index 99% rename from vendor/github.com/open-policy-agent/opa/storage/interface.go rename to vendor/github.com/open-policy-agent/opa/v1/storage/interface.go index 6baca9a59f..94e02a47bc 100644 --- a/vendor/github.com/open-policy-agent/opa/storage/interface.go +++ b/vendor/github.com/open-policy-agent/opa/v1/storage/interface.go @@ -7,7 +7,7 @@ package storage import ( "context" - "github.com/open-policy-agent/opa/metrics" + "github.com/open-policy-agent/opa/v1/metrics" ) // Transaction defines the interface that identifies a consistent snapshot over diff --git a/vendor/github.com/open-policy-agent/opa/storage/internal/errors/errors.go b/vendor/github.com/open-policy-agent/opa/v1/storage/internal/errors/errors.go similarity index 95% rename from vendor/github.com/open-policy-agent/opa/storage/internal/errors/errors.go rename to vendor/github.com/open-policy-agent/opa/v1/storage/internal/errors/errors.go index 0bba74b907..06063b4c77 100644 --- a/vendor/github.com/open-policy-agent/opa/storage/internal/errors/errors.go +++ b/vendor/github.com/open-policy-agent/opa/v1/storage/internal/errors/errors.go @@ -8,7 +8,7 @@ package errors import ( "fmt" - "github.com/open-policy-agent/opa/storage" + "github.com/open-policy-agent/opa/v1/storage" ) const ArrayIndexTypeMsg = "array index must be integer" diff --git a/vendor/github.com/open-policy-agent/opa/storage/internal/ptr/ptr.go b/vendor/github.com/open-policy-agent/opa/v1/storage/internal/ptr/ptr.go similarity index 57% rename from vendor/github.com/open-policy-agent/opa/storage/internal/ptr/ptr.go rename to vendor/github.com/open-policy-agent/opa/v1/storage/internal/ptr/ptr.go index 56772f7976..d1c36a15a0 100644 --- a/vendor/github.com/open-policy-agent/opa/storage/internal/ptr/ptr.go +++ b/vendor/github.com/open-policy-agent/opa/v1/storage/internal/ptr/ptr.go @@ -8,8 +8,9 @@ package ptr import ( "strconv" - "github.com/open-policy-agent/opa/storage" - "github.com/open-policy-agent/opa/storage/internal/errors" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/storage" + "github.com/open-policy-agent/opa/v1/storage/internal/errors" ) func Ptr(data interface{}, path storage.Path) (interface{}, error) { @@ -36,6 +37,32 @@ func Ptr(data interface{}, path storage.Path) (interface{}, error) { return node, nil } +func ValuePtr(data ast.Value, path storage.Path) (ast.Value, error) { + node := data + for i := range path { + key := path[i] + switch curr := node.(type) { + case ast.Object: + keyTerm := ast.StringTerm(key) + val := curr.Get(keyTerm) + if val == nil { + return nil, errors.NewNotFoundError(path) + } + node = val.Value + case *ast.Array: + pos, err := ValidateASTArrayIndex(curr, key, path) + if err != nil { + return nil, err + } + node = curr.Elem(pos).Value + default: + return nil, errors.NewNotFoundError(path) + } + } + + return node, nil +} + func ValidateArrayIndex(arr []interface{}, s string, path storage.Path) (int, error) { idx, ok := isInt(s) if !ok { @@ -44,6 +71,14 @@ func ValidateArrayIndex(arr []interface{}, s string, path storage.Path) (int, er return inRange(idx, arr, path) } +func ValidateASTArrayIndex(arr *ast.Array, s string, path storage.Path) (int, error) { + idx, ok := isInt(s) + if !ok { + return 0, errors.NewNotFoundErrorWithHint(path, errors.ArrayIndexTypeMsg) + } + return inRange(idx, arr, path) +} + // ValidateArrayIndexForWrite also checks that `s` is a valid way to address an // array element like `ValidateArrayIndex`, but returns a `resource_conflict` error // if it is not. @@ -60,8 +95,18 @@ func isInt(s string) (int, bool) { return idx, err == nil } -func inRange(i int, arr []interface{}, path storage.Path) (int, error) { - if i < 0 || i >= len(arr) { +func inRange(i int, arr interface{}, path storage.Path) (int, error) { + + var arrLen int + + switch v := arr.(type) { + case []interface{}: + arrLen = len(v) + case *ast.Array: + arrLen = v.Len() + } + + if i < 0 || i >= arrLen { return 0, errors.NewNotFoundErrorWithHint(path, errors.OutOfRangeMsg) } return i, nil diff --git a/vendor/github.com/open-policy-agent/opa/storage/path.go b/vendor/github.com/open-policy-agent/opa/v1/storage/path.go similarity index 96% rename from vendor/github.com/open-policy-agent/opa/storage/path.go rename to vendor/github.com/open-policy-agent/opa/v1/storage/path.go index 02ef4cab40..7f90c666b0 100644 --- a/vendor/github.com/open-policy-agent/opa/storage/path.go +++ b/vendor/github.com/open-policy-agent/opa/v1/storage/path.go @@ -10,7 +10,7 @@ import ( "strconv" "strings" - "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/v1/ast" ) // Path refers to a document in storage. @@ -84,11 +84,7 @@ func NewPathForRef(ref ast.Ref) (path Path, err error) { // is less than other, 0 if p is equal to other, or 1 if p is greater than // other. func (p Path) Compare(other Path) (cmp int) { - min := len(p) - if len(other) < min { - min = len(other) - } - for i := 0; i < min; i++ { + for i := 0; i < min(len(p), len(other)); i++ { if cmp := strings.Compare(p[i], other[i]); cmp != 0 { return cmp } diff --git a/vendor/github.com/open-policy-agent/opa/storage/storage.go b/vendor/github.com/open-policy-agent/opa/v1/storage/storage.go similarity index 95% rename from vendor/github.com/open-policy-agent/opa/storage/storage.go rename to vendor/github.com/open-policy-agent/opa/v1/storage/storage.go index 1e290c50bb..34305f2912 100644 --- a/vendor/github.com/open-policy-agent/opa/storage/storage.go +++ b/vendor/github.com/open-policy-agent/opa/v1/storage/storage.go @@ -6,6 +6,8 @@ package storage import ( "context" + + "github.com/open-policy-agent/opa/v1/ast" ) // NewTransactionOrDie is a helper function to create a new transaction. If the @@ -78,6 +80,11 @@ func MakeDir(ctx context.Context, store Store, txn Transaction, path Path) error if _, ok := node.(map[string]interface{}); ok { return nil } + + if _, ok := node.(ast.Object); ok { + return nil + } + return writeConflictError(path) } @@ -118,6 +125,9 @@ func NonEmpty(ctx context.Context, store Store, txn Transaction) func([]string) if _, ok := val.(map[string]interface{}); ok { return false, nil } + if _, ok := val.(ast.Object); ok { + return false, nil + } return true, nil } } diff --git a/vendor/github.com/open-policy-agent/opa/topdown/aggregates.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/aggregates.go similarity index 80% rename from vendor/github.com/open-policy-agent/opa/topdown/aggregates.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/aggregates.go index a0f67a7c95..02425d2411 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/aggregates.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/aggregates.go @@ -7,20 +7,20 @@ package topdown import ( "math/big" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) func builtinCount(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { switch a := operands[0].Value.(type) { case *ast.Array: - return iter(ast.IntNumberTerm(a.Len())) + return iter(ast.InternedIntNumberTerm(a.Len())) case ast.Object: - return iter(ast.IntNumberTerm(a.Len())) + return iter(ast.InternedIntNumberTerm(a.Len())) case ast.Set: - return iter(ast.IntNumberTerm(a.Len())) + return iter(ast.InternedIntNumberTerm(a.Len())) case ast.String: - return iter(ast.IntNumberTerm(len([]rune(a)))) + return iter(ast.InternedIntNumberTerm(len([]rune(a)))) } return builtins.NewOperandTypeErr(1, operands[0].Value, "array", "object", "set", "string") } @@ -99,7 +99,7 @@ func builtinMax(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) err if a.Len() == 0 { return nil } - var max = ast.Value(ast.Null{}) + max := ast.InternedNullTerm.Value a.Foreach(func(x *ast.Term) { if ast.Compare(max, x.Value) <= 0 { max = x.Value @@ -110,7 +110,7 @@ func builtinMax(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) err if a.Len() == 0 { return nil } - max, err := a.Reduce(ast.NullTerm(), func(max *ast.Term, elem *ast.Term) (*ast.Term, error) { + max, err := a.Reduce(ast.InternedNullTerm, func(max *ast.Term, elem *ast.Term) (*ast.Term, error) { if ast.Compare(max, elem) <= 0 { return elem, nil } @@ -142,11 +142,11 @@ func builtinMin(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) err if a.Len() == 0 { return nil } - min, err := a.Reduce(ast.NullTerm(), func(min *ast.Term, elem *ast.Term) (*ast.Term, error) { + min, err := a.Reduce(ast.InternedNullTerm, func(min *ast.Term, elem *ast.Term) (*ast.Term, error) { // The null term is considered to be less than any other term, // so in order for min of a set to make sense, we need to check // for it. - if min.Value.Compare(ast.Null{}) == 0 { + if min.Value.Compare(ast.InternedNullTerm.Value) == 0 { return elem, nil } @@ -178,7 +178,7 @@ func builtinAll(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) err switch val := operands[0].Value.(type) { case ast.Set: res := true - match := ast.BooleanTerm(true) + match := ast.InternedBooleanTerm(true) val.Until(func(term *ast.Term) bool { if !match.Equal(term) { res = false @@ -186,10 +186,10 @@ func builtinAll(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) err } return false }) - return iter(ast.BooleanTerm(res)) + return iter(ast.InternedBooleanTerm(res)) case *ast.Array: res := true - match := ast.BooleanTerm(true) + match := ast.InternedBooleanTerm(true) val.Until(func(term *ast.Term) bool { if !match.Equal(term) { res = false @@ -197,7 +197,7 @@ func builtinAll(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) err } return false }) - return iter(ast.BooleanTerm(res)) + return iter(ast.InternedBooleanTerm(res)) default: return builtins.NewOperandTypeErr(1, operands[0].Value, "array", "set") } @@ -206,11 +206,11 @@ func builtinAll(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) err func builtinAny(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { switch val := operands[0].Value.(type) { case ast.Set: - res := val.Len() > 0 && val.Contains(ast.BooleanTerm(true)) - return iter(ast.BooleanTerm(res)) + res := val.Len() > 0 && val.Contains(ast.InternedBooleanTerm(true)) + return iter(ast.InternedBooleanTerm(res)) case *ast.Array: res := false - match := ast.BooleanTerm(true) + match := ast.InternedBooleanTerm(true) val.Until(func(term *ast.Term) bool { if match.Equal(term) { res = true @@ -218,7 +218,7 @@ func builtinAny(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) err } return false }) - return iter(ast.BooleanTerm(res)) + return iter(ast.InternedBooleanTerm(res)) default: return builtins.NewOperandTypeErr(1, operands[0].Value, "array", "set") } @@ -228,27 +228,20 @@ func builtinMember(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) containee := operands[0] switch c := operands[1].Value.(type) { case ast.Set: - return iter(ast.BooleanTerm(c.Contains(containee))) + return iter(ast.InternedBooleanTerm(c.Contains(containee))) case *ast.Array: - ret := false - c.Until(func(v *ast.Term) bool { - if v.Value.Compare(containee.Value) == 0 { - ret = true + for i := 0; i < c.Len(); i++ { + if c.Elem(i).Value.Compare(containee.Value) == 0 { + return iter(ast.InternedBooleanTerm(true)) } - return ret - }) - return iter(ast.BooleanTerm(ret)) + } + return iter(ast.InternedBooleanTerm(false)) case ast.Object: - ret := false - c.Until(func(_, v *ast.Term) bool { - if v.Value.Compare(containee.Value) == 0 { - ret = true - } - return ret - }) - return iter(ast.BooleanTerm(ret)) + return iter(ast.InternedBooleanTerm(c.Until(func(_, v *ast.Term) bool { + return v.Value.Compare(containee.Value) == 0 + }))) } - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } func builtinMemberWithKey(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -259,9 +252,9 @@ func builtinMemberWithKey(_ BuiltinContext, operands []*ast.Term, iter func(*ast if act := c.Get(key); act != nil { ret = act.Value.Compare(val.Value) == 0 } - return iter(ast.BooleanTerm(ret)) + return iter(ast.InternedBooleanTerm(ret)) } - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } func init() { diff --git a/vendor/github.com/open-policy-agent/opa/topdown/arithmetic.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/arithmetic.go similarity index 95% rename from vendor/github.com/open-policy-agent/opa/topdown/arithmetic.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/arithmetic.go index 3ac703efa3..68c3b496e2 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/arithmetic.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/arithmetic.go @@ -8,8 +8,8 @@ import ( "fmt" "math/big" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) type arithArity1 func(a *big.Float) (*big.Float, error) @@ -67,7 +67,7 @@ func builtinPlus(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) er y, ok2 := n2.Int() if ok1 && ok2 && inSmallIntRange(x) && inSmallIntRange(y) { - return iter(ast.IntNumberTerm(x + y)) + return iter(ast.InternedIntNumberTerm(x + y)) } f, err := arithPlus(builtins.NumberToFloat(n1), builtins.NumberToFloat(n2)) @@ -91,7 +91,7 @@ func builtinMultiply(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term y, ok2 := n2.Int() if ok1 && ok2 && inSmallIntRange(x) && inSmallIntRange(y) { - return iter(ast.IntNumberTerm(x * y)) + return iter(ast.InternedIntNumberTerm(x * y)) } f, err := arithMultiply(builtins.NumberToFloat(n1), builtins.NumberToFloat(n2)) @@ -171,7 +171,7 @@ func builtinMinus(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) e y, oky := n2.Int() if okx && oky && inSmallIntRange(x) && inSmallIntRange(y) { - return iter(ast.IntNumberTerm(x - y)) + return iter(ast.InternedIntNumberTerm(x - y)) } f, err := arithMinus(builtins.NumberToFloat(n1), builtins.NumberToFloat(n2)) @@ -213,7 +213,7 @@ func builtinRem(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) err return fmt.Errorf("modulo by zero") } - return iter(ast.IntNumberTerm(x % y)) + return iter(ast.InternedIntNumberTerm(x % y)) } op1, err1 := builtins.NumberToInt(n1) diff --git a/vendor/github.com/open-policy-agent/opa/topdown/array.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/array.go similarity index 87% rename from vendor/github.com/open-policy-agent/opa/topdown/array.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/array.go index e7fe5be643..4a2a2ed148 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/array.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/array.go @@ -5,8 +5,8 @@ package topdown import ( - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) func builtinArrayConcat(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -20,6 +20,13 @@ func builtinArrayConcat(_ BuiltinContext, operands []*ast.Term, iter func(*ast.T return err } + if arrA.Len() == 0 { + return iter(operands[1]) + } + if arrB.Len() == 0 { + return iter(operands[0]) + } + arrC := make([]*ast.Term, arrA.Len()+arrB.Len()) i := 0 @@ -33,7 +40,7 @@ func builtinArrayConcat(_ BuiltinContext, operands []*ast.Term, iter func(*ast.T i++ }) - return iter(ast.NewTerm(ast.NewArray(arrC...))) + return iter(ast.ArrayTerm(arrC...)) } func builtinArraySlice(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -68,6 +75,10 @@ func builtinArraySlice(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Te startIndex = stopIndex } + if startIndex == 0 && stopIndex >= arr.Len() { + return iter(operands[0]) + } + return iter(ast.NewTerm(arr.Slice(startIndex, stopIndex))) } diff --git a/vendor/github.com/open-policy-agent/opa/topdown/binary.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/binary.go similarity index 90% rename from vendor/github.com/open-policy-agent/opa/topdown/binary.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/binary.go index b4f9dbd392..6f7ebaf40c 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/binary.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/binary.go @@ -5,8 +5,8 @@ package topdown import ( - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) func builtinBinaryAnd(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { diff --git a/vendor/github.com/open-policy-agent/opa/topdown/bindings.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/bindings.go similarity index 99% rename from vendor/github.com/open-policy-agent/opa/topdown/bindings.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/bindings.go index 30a8ac5ec4..ae6ca15daa 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/bindings.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/bindings.go @@ -8,7 +8,7 @@ import ( "fmt" "strings" - "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/v1/ast" ) type undo struct { @@ -68,7 +68,7 @@ func (u *bindings) Plug(a *ast.Term) *ast.Term { } func (u *bindings) PlugNamespaced(a *ast.Term, caller *bindings) *ast.Term { - if u != nil { + if u != nil && u.instr != nil { u.instr.startTimer(evalOpPlug) t := u.plugNamespaced(a, caller) u.instr.stopTimer(evalOpPlug) diff --git a/vendor/github.com/open-policy-agent/opa/topdown/bits.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/bits.go similarity index 96% rename from vendor/github.com/open-policy-agent/opa/topdown/bits.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/bits.go index 7a63c0df1e..e420ffe611 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/bits.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/bits.go @@ -7,8 +7,8 @@ package topdown import ( "math/big" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) type bitsArity1 func(a *big.Int) (*big.Int, error) diff --git a/vendor/github.com/open-policy-agent/opa/topdown/builtins.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/builtins.go similarity index 71% rename from vendor/github.com/open-policy-agent/opa/topdown/builtins.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/builtins.go index 30c488050f..e0b893d477 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/builtins.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/builtins.go @@ -11,12 +11,12 @@ import ( "io" "math/rand" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/metrics" - "github.com/open-policy-agent/opa/topdown/builtins" - "github.com/open-policy-agent/opa/topdown/cache" - "github.com/open-policy-agent/opa/topdown/print" - "github.com/open-policy-agent/opa/tracing" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/metrics" + "github.com/open-policy-agent/opa/v1/topdown/builtins" + "github.com/open-policy-agent/opa/v1/topdown/cache" + "github.com/open-policy-agent/opa/v1/topdown/print" + "github.com/open-policy-agent/opa/v1/tracing" ) type ( @@ -35,25 +35,27 @@ type ( // BuiltinContext contains context from the evaluator that may be used by // built-in functions. BuiltinContext struct { - Context context.Context // request context that was passed when query started - Metrics metrics.Metrics // metrics registry for recording built-in specific metrics - Seed io.Reader // randomization source - Time *ast.Term // wall clock time - Cancel Cancel // atomic value that signals evaluation to halt - Runtime *ast.Term // runtime information on the OPA instance - Cache builtins.Cache // built-in function state cache - InterQueryBuiltinCache cache.InterQueryCache // cross-query built-in function state cache - NDBuiltinCache builtins.NDBCache // cache for non-deterministic built-in state - Location *ast.Location // location of built-in call - Tracers []Tracer // Deprecated: Use QueryTracers instead - QueryTracers []QueryTracer // tracer objects for trace() built-in function - TraceEnabled bool // indicates whether tracing is enabled for the evaluation - QueryID uint64 // identifies query being evaluated - ParentID uint64 // identifies parent of query being evaluated - PrintHook print.Hook // provides callback function to use for printing - DistributedTracingOpts tracing.Options // options to be used by distributed tracing. - rand *rand.Rand // randomization source for non-security-sensitive operations - Capabilities *ast.Capabilities + Context context.Context // request context that was passed when query started + Metrics metrics.Metrics // metrics registry for recording built-in specific metrics + Seed io.Reader // randomization source + Time *ast.Term // wall clock time + Cancel Cancel // atomic value that signals evaluation to halt + Runtime *ast.Term // runtime information on the OPA instance + Cache builtins.Cache // built-in function state cache + InterQueryBuiltinCache cache.InterQueryCache // cross-query built-in function state cache + InterQueryBuiltinValueCache cache.InterQueryValueCache // cross-query built-in function state value cache. this cache is useful for scenarios where the entry size cannot be calculated + NDBuiltinCache builtins.NDBCache // cache for non-deterministic built-in state + Location *ast.Location // location of built-in call + Tracers []Tracer // Deprecated: Use QueryTracers instead + QueryTracers []QueryTracer // tracer objects for trace() built-in function + TraceEnabled bool // indicates whether tracing is enabled for the evaluation + QueryID uint64 // identifies query being evaluated + ParentID uint64 // identifies parent of query being evaluated + PrintHook print.Hook // provides callback function to use for printing + RoundTripper CustomizeRoundTripper // customize transport to use for HTTP requests + DistributedTracingOpts tracing.Options // options to be used by distributed tracing. + rand *rand.Rand // randomization source for non-security-sensitive operations + Capabilities *ast.Capabilities } // BuiltinFunc defines an interface for implementing built-in functions. diff --git a/vendor/github.com/open-policy-agent/opa/topdown/builtins/builtins.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/builtins/builtins.go similarity index 95% rename from vendor/github.com/open-policy-agent/opa/topdown/builtins/builtins.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/builtins/builtins.go index 353f956840..45a0b88408 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/builtins/builtins.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/builtins/builtins.go @@ -11,8 +11,8 @@ import ( "math/big" "strings" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/util" ) // Cache defines the built-in cache used by the top-down evaluation. The keys @@ -128,23 +128,23 @@ func NewOperandErr(pos int, f string, a ...interface{}) error { func NewOperandTypeErr(pos int, got ast.Value, expected ...string) error { if len(expected) == 1 { - return NewOperandErr(pos, "must be %v but got %v", expected[0], ast.TypeName(got)) + return NewOperandErr(pos, "must be %v but got %v", expected[0], ast.ValueName(got)) } - return NewOperandErr(pos, "must be one of {%v} but got %v", strings.Join(expected, ", "), ast.TypeName(got)) + return NewOperandErr(pos, "must be one of {%v} but got %v", strings.Join(expected, ", "), ast.ValueName(got)) } // NewOperandElementErr returns an operand error indicating an element in the // composite operand was wrong. func NewOperandElementErr(pos int, composite ast.Value, got ast.Value, expected ...string) error { - tpe := ast.TypeName(composite) + tpe := ast.ValueName(composite) if len(expected) == 1 { - return NewOperandErr(pos, "must be %v of %vs but got %v containing %v", tpe, expected[0], tpe, ast.TypeName(got)) + return NewOperandErr(pos, "must be %v of %vs but got %v containing %v", tpe, expected[0], tpe, ast.ValueName(got)) } - return NewOperandErr(pos, "must be %v of (any of) {%v} but got %v containing %v", tpe, strings.Join(expected, ", "), tpe, ast.TypeName(got)) + return NewOperandErr(pos, "must be %v of (any of) {%v} but got %v containing %v", tpe, strings.Join(expected, ", "), tpe, ast.ValueName(got)) } // NewOperandEnumErr returns an operand error indicating a value was wrong. @@ -233,7 +233,7 @@ func ObjectOperand(x ast.Value, pos int) (ast.Object, error) { func ArrayOperand(x ast.Value, pos int) (*ast.Array, error) { a, ok := x.(*ast.Array) if !ok { - return ast.NewArray(), NewOperandTypeErr(pos, x, "array") + return nil, NewOperandTypeErr(pos, x, "array") } return a, nil } diff --git a/vendor/github.com/open-policy-agent/opa/topdown/cache.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/cache.go similarity index 98% rename from vendor/github.com/open-policy-agent/opa/topdown/cache.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/cache.go index 265457e02f..607abf46e7 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/cache.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/cache.go @@ -5,8 +5,8 @@ package topdown import ( - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/util" ) // VirtualCache defines the interface for a cache that stores the results of diff --git a/vendor/github.com/open-policy-agent/opa/topdown/cache/cache.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/cache/cache.go similarity index 51% rename from vendor/github.com/open-policy-agent/opa/topdown/cache/cache.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/cache/cache.go index c83c9828bf..a2b80c0a77 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/cache/cache.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/cache/cache.go @@ -13,19 +13,47 @@ import ( "sync" "time" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/util" ) const ( + defaultInterQueryBuiltinValueCacheSize = int(0) // unlimited defaultMaxSizeBytes = int64(0) // unlimited defaultForcedEvictionThresholdPercentage = int64(100) // trigger at max_size_bytes defaultStaleEntryEvictionPeriodSeconds = int64(0) // never ) -// Config represents the configuration of the inter-query cache. +var interQueryBuiltinValueCacheDefaultConfigs = map[string]*NamedValueCacheConfig{} + +func getDefaultInterQueryBuiltinValueCacheConfig(name string) *NamedValueCacheConfig { + return interQueryBuiltinValueCacheDefaultConfigs[name] +} + +// RegisterDefaultInterQueryBuiltinValueCacheConfig registers a default configuration for the inter-query value cache; +// used when none has been explicitly configured. +// To disable a named cache when not configured, pass a nil config. +func RegisterDefaultInterQueryBuiltinValueCacheConfig(name string, config *NamedValueCacheConfig) { + interQueryBuiltinValueCacheDefaultConfigs[name] = config +} + +// Config represents the configuration for the inter-query builtin cache. type Config struct { - InterQueryBuiltinCache InterQueryBuiltinCacheConfig `json:"inter_query_builtin_cache"` + InterQueryBuiltinCache InterQueryBuiltinCacheConfig `json:"inter_query_builtin_cache"` + InterQueryBuiltinValueCache InterQueryBuiltinValueCacheConfig `json:"inter_query_builtin_value_cache"` +} + +// NamedValueCacheConfig represents the configuration of a named cache that built-in functions can utilize. +// A default configuration to be used if not explicitly configured can be registered using RegisterDefaultInterQueryBuiltinValueCacheConfig. +type NamedValueCacheConfig struct { + MaxNumEntries *int `json:"max_num_entries,omitempty"` +} + +// InterQueryBuiltinValueCacheConfig represents the configuration of the inter-query value cache that built-in functions can utilize. +// MaxNumEntries - max number of cache entries +type InterQueryBuiltinValueCacheConfig struct { + MaxNumEntries *int `json:"max_num_entries,omitempty"` + NamedCacheConfigs map[string]*NamedValueCacheConfig `json:"named,omitempty"` } // InterQueryBuiltinCacheConfig represents the configuration of the inter-query cache that built-in functions can utilize. @@ -47,7 +75,20 @@ func ParseCachingConfig(raw []byte) (*Config, error) { *threshold = defaultForcedEvictionThresholdPercentage period := new(int64) *period = defaultStaleEntryEvictionPeriodSeconds - return &Config{InterQueryBuiltinCache: InterQueryBuiltinCacheConfig{MaxSizeBytes: maxSize, ForcedEvictionThresholdPercentage: threshold, StaleEntryEvictionPeriodSeconds: period}}, nil + + maxInterQueryBuiltinValueCacheSize := new(int) + *maxInterQueryBuiltinValueCacheSize = defaultInterQueryBuiltinValueCacheSize + + return &Config{ + InterQueryBuiltinCache: InterQueryBuiltinCacheConfig{ + MaxSizeBytes: maxSize, + ForcedEvictionThresholdPercentage: threshold, + StaleEntryEvictionPeriodSeconds: period, + }, + InterQueryBuiltinValueCache: InterQueryBuiltinValueCacheConfig{ + MaxNumEntries: maxInterQueryBuiltinValueCacheSize, + }, + }, nil } var config Config @@ -89,6 +130,25 @@ func (c *Config) validateAndInjectDefaults() error { return fmt.Errorf("invalid stale_entry_eviction_period_seconds %v", period) } } + + if c.InterQueryBuiltinValueCache.MaxNumEntries == nil { + maxSize := new(int) + *maxSize = defaultInterQueryBuiltinValueCacheSize + c.InterQueryBuiltinValueCache.MaxNumEntries = maxSize + } else { + numEntries := *c.InterQueryBuiltinValueCache.MaxNumEntries + if numEntries < 0 { + return fmt.Errorf("invalid max_num_entries %v", numEntries) + } + } + + for name, namedConfig := range c.InterQueryBuiltinValueCache.NamedCacheConfigs { + numEntries := *namedConfig.MaxNumEntries + if numEntries < 0 { + return fmt.Errorf("invalid max_num_entries %v for named cache %v", numEntries, name) + } + } + return nil } @@ -129,11 +189,14 @@ func NewInterQueryCache(config *Config) InterQueryCache { func NewInterQueryCacheWithContext(ctx context.Context, config *Config) InterQueryCache { iqCache := newCache(config) if iqCache.staleEntryEvictionTimePeriodSeconds() > 0 { - cleanupTicker := time.NewTicker(time.Duration(iqCache.staleEntryEvictionTimePeriodSeconds()) * time.Second) go func() { + cleanupTicker := time.NewTicker(time.Duration(iqCache.staleEntryEvictionTimePeriodSeconds()) * time.Second) for { select { case <-cleanupTicker.C: + // NOTE: We stop the ticker and create a new one here to ensure that applications + // get _at least_ staleEntryEvictionTimePeriodSeconds with the cache unlocked; + // see https://github.com/open-policy-agent/opa/pull/7188/files#r1855342998 cleanupTicker.Stop() iqCache.cleanStaleValues() cleanupTicker = time.NewTicker(time.Duration(iqCache.staleEntryEvictionTimePeriodSeconds()) * time.Second) @@ -301,3 +364,217 @@ func (c *cache) cleanStaleValues() (dropped int) { } return dropped } + +type InterQueryValueCacheBucket interface { + Get(key ast.Value) (value any, found bool) + Insert(key ast.Value, value any) int + Delete(key ast.Value) +} + +type interQueryValueCacheBucket struct { + items util.TypedHashMap[ast.Value, any] + config *NamedValueCacheConfig + mtx sync.RWMutex +} + +func newItemsMap() *util.TypedHashMap[ast.Value, any] { + return util.NewTypedHashMap[ast.Value, any]( + func(a, b ast.Value) bool { return a.Compare(b) == 0 }, + func(any, any) bool { return false }, // map equality not supported + func(a ast.Value) int { return a.Hash() }, + func(any) int { return 0 }, // map equality not supported + nil, + ) +} + +func (c *interQueryValueCacheBucket) Get(k ast.Value) (any, bool) { + c.mtx.RLock() + defer c.mtx.RUnlock() + return c.items.Get(k) +} + +func (c *interQueryValueCacheBucket) Insert(k ast.Value, v any) (dropped int) { + c.mtx.Lock() + defer c.mtx.Unlock() + + maxEntries := c.maxNumEntries() + if maxEntries > 0 { + l := c.items.Len() + if l >= maxEntries { + itemsToRemove := l - maxEntries + 1 + + // Delete a (semi-)random key to make room for the new one. + c.items.Iter(func(k ast.Value, _ any) bool { + c.items.Delete(k) + dropped++ + + return itemsToRemove == dropped + }) + } + } + + c.items.Put(k, v) + return dropped +} + +func (c *interQueryValueCacheBucket) Delete(k ast.Value) { + c.mtx.Lock() + defer c.mtx.Unlock() + c.items.Delete(k) +} + +func (c *interQueryValueCacheBucket) updateConfig(config *NamedValueCacheConfig) { + if config == nil { + return + } + c.mtx.Lock() + defer c.mtx.Unlock() + c.config = config +} + +func (c *interQueryValueCacheBucket) maxNumEntries() int { + if c.config == nil { + return defaultInterQueryBuiltinValueCacheSize + } + return *c.config.MaxNumEntries +} + +type InterQueryValueCache interface { + InterQueryValueCacheBucket + GetCache(name string) InterQueryValueCacheBucket + UpdateConfig(config *Config) +} + +func NewInterQueryValueCache(_ context.Context, config *Config) InterQueryValueCache { + var c *InterQueryBuiltinValueCacheConfig + var nc *NamedValueCacheConfig + if config != nil { + c = &config.InterQueryBuiltinValueCache + // NOTE: This is a side-effect of reusing the interQueryValueCacheBucket as the global cache. + // It's a hidden implementation detail that we can clean up in the future when revisiting the named caches + // to automatically apply them to any built-in instead of the global cache. + nc = &NamedValueCacheConfig{ + MaxNumEntries: c.MaxNumEntries, + } + } + + return &interQueryBuiltinValueCache{ + globalCache: interQueryValueCacheBucket{ + items: *newItemsMap(), + config: nc, + }, + namedCaches: map[string]*interQueryValueCacheBucket{}, + config: c, + } +} + +type interQueryBuiltinValueCache struct { + globalCache interQueryValueCacheBucket + namedCachesLock sync.RWMutex + namedCaches map[string]*interQueryValueCacheBucket + config *InterQueryBuiltinValueCacheConfig +} + +func (c *interQueryBuiltinValueCache) Get(k ast.Value) (any, bool) { + if c == nil { + return nil, false + } + + return c.globalCache.Get(k) +} + +func (c *interQueryBuiltinValueCache) Insert(k ast.Value, v any) int { + if c == nil { + return 0 + } + + return c.globalCache.Insert(k, v) +} + +func (c *interQueryBuiltinValueCache) Delete(k ast.Value) { + if c == nil { + return + } + + c.globalCache.Delete(k) +} + +func (c *interQueryBuiltinValueCache) GetCache(name string) InterQueryValueCacheBucket { + if c == nil { + return nil + } + + if c.namedCaches == nil { + return nil + } + + c.namedCachesLock.RLock() + nc, ok := c.namedCaches[name] + c.namedCachesLock.RUnlock() + + if !ok { + c.namedCachesLock.Lock() + defer c.namedCachesLock.Unlock() + + if nc, ok := c.namedCaches[name]; ok { + // Some other goroutine has created the cache while we were waiting for the lock. + return nc + } + + var config *NamedValueCacheConfig + if c.config != nil { + config = c.config.NamedCacheConfigs[name] + if config == nil { + config = getDefaultInterQueryBuiltinValueCacheConfig(name) + } + } + + if config == nil { + // No config, cache disabled. + return nil + } + + nc = &interQueryValueCacheBucket{ + items: *newItemsMap(), + config: config, + } + + c.namedCaches[name] = nc + } + + return nc +} + +func (c *interQueryBuiltinValueCache) UpdateConfig(config *Config) { + if c == nil { + return + } + + if config == nil { + c.globalCache.updateConfig(nil) + } else { + + c.globalCache.updateConfig(&NamedValueCacheConfig{ + MaxNumEntries: config.InterQueryBuiltinValueCache.MaxNumEntries, + }) + } + + c.namedCachesLock.Lock() + defer c.namedCachesLock.Unlock() + + c.config = &config.InterQueryBuiltinValueCache + + for name, nc := range c.namedCaches { + // For each named cache: if it has a config, update it; if no config, remove it. + namedConfig := c.config.NamedCacheConfigs[name] + if namedConfig == nil { + namedConfig = getDefaultInterQueryBuiltinValueCacheConfig(name) + } + + if namedConfig == nil { + delete(c.namedCaches, name) + } else { + nc.updateConfig(namedConfig) + } + } +} diff --git a/vendor/github.com/open-policy-agent/opa/topdown/cancel.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/cancel.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/topdown/cancel.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/cancel.go diff --git a/vendor/github.com/open-policy-agent/opa/topdown/casts.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/casts.go similarity index 82% rename from vendor/github.com/open-policy-agent/opa/topdown/casts.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/casts.go index 2eb8f97fc9..9be7271c44 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/casts.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/casts.go @@ -6,24 +6,38 @@ package topdown import ( "strconv" + "strings" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) func builtinToNumber(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { switch a := operands[0].Value.(type) { case ast.Null: - return iter(ast.NumberTerm("0")) + return iter(ast.InternedIntNumberTerm(0)) case ast.Boolean: if a { - return iter(ast.NumberTerm("1")) + return iter(ast.InternedIntNumberTerm(1)) } - return iter(ast.NumberTerm("0")) + return iter(ast.InternedIntNumberTerm(0)) case ast.Number: return iter(ast.NewTerm(a)) case ast.String: - _, err := strconv.ParseFloat(string(a), 64) + strValue := string(a) + + if it := ast.InternedIntNumberTermFromString(strValue); it != nil { + return iter(it) + } + + trimmedVal := strings.TrimLeft(strValue, "+-") + lowerCaseVal := strings.ToLower(trimmedVal) + + if lowerCaseVal == "inf" || lowerCaseVal == "infinity" || lowerCaseVal == "nan" { + return builtins.NewOperandTypeErr(1, operands[0].Value, "valid number string") + } + + _, err := strconv.ParseFloat(strValue, 64) if err != nil { return err } diff --git a/vendor/github.com/open-policy-agent/opa/topdown/cidr.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/cidr.go similarity index 95% rename from vendor/github.com/open-policy-agent/opa/topdown/cidr.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/cidr.go index 5b011bd161..113bd2f372 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/cidr.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/cidr.go @@ -8,9 +8,9 @@ import ( "net" "sort" - "github.com/open-policy-agent/opa/ast" cidrMerge "github.com/open-policy-agent/opa/internal/cidr/merge" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) func getNetFromOperand(v ast.Value) (*net.IPNet, error) { @@ -75,7 +75,7 @@ func builtinNetCIDRIntersects(_ BuiltinContext, operands []*ast.Term, iter func( // If either net contains the others starting IP they are overlapping cidrsOverlap := cidrnetA.Contains(cidrnetB.IP) || cidrnetB.Contains(cidrnetA.IP) - return iter(ast.BooleanTerm(cidrsOverlap)) + return iter(ast.InternedBooleanTerm(cidrsOverlap)) } func builtinNetCIDRContains(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -92,7 +92,7 @@ func builtinNetCIDRContains(_ BuiltinContext, operands []*ast.Term, iter func(*a ip := net.ParseIP(string(bStr)) if ip != nil { - return iter(ast.BooleanTerm(cidrnetA.Contains(ip))) + return iter(ast.InternedBooleanTerm(cidrnetA.Contains(ip))) } // It wasn't an IP, try and parse it as a CIDR @@ -113,7 +113,7 @@ func builtinNetCIDRContains(_ BuiltinContext, operands []*ast.Term, iter func(*a cidrContained = cidrnetA.Contains(lastIP) } - return iter(ast.BooleanTerm(cidrContained)) + return iter(ast.InternedBooleanTerm(cidrContained)) } var errNetCIDRContainsMatchElementType = errors.New("element must be string or non-empty array") @@ -142,7 +142,7 @@ func evalNetCIDRContainsMatchesOperand(operand int, a *ast.Term, iter func(cidr, if err != nil { return fmt.Errorf("operand %v: %v", operand, err) } - if err := iter(cidr, ast.IntNumberTerm(i)); err != nil { + if err := iter(cidr, ast.InternedIntNumberTerm(i)); err != nil { return err } } @@ -219,13 +219,13 @@ func builtinNetCIDRExpand(bctx BuiltinContext, operands []*ast.Term, iter func(* func builtinNetCIDRIsValid(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { cidr, err := builtins.StringOperand(operands[0].Value, 1) if err != nil { - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } if _, _, err := net.ParseCIDR(string(cidr)); err != nil { - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } - return iter(ast.BooleanTerm(true)) + return iter(ast.InternedBooleanTerm(true)) } type cidrBlockRange struct { diff --git a/vendor/github.com/open-policy-agent/opa/topdown/comparison.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/comparison.go similarity index 90% rename from vendor/github.com/open-policy-agent/opa/topdown/comparison.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/comparison.go index 0d033d2c32..9e1585a28a 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/comparison.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/comparison.go @@ -4,7 +4,7 @@ package topdown -import "github.com/open-policy-agent/opa/ast" +import "github.com/open-policy-agent/opa/v1/ast" type compareFunc func(a, b ast.Value) bool @@ -34,7 +34,7 @@ func compareEq(a, b ast.Value) bool { func builtinCompare(cmp compareFunc) BuiltinFunc { return func(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { - return iter(ast.BooleanTerm(cmp(operands[0].Value, operands[1].Value))) + return iter(ast.InternedBooleanTerm(cmp(operands[0].Value, operands[1].Value))) } } diff --git a/vendor/github.com/open-policy-agent/opa/topdown/copypropagation/copypropagation.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/copypropagation/copypropagation.go similarity index 99% rename from vendor/github.com/open-policy-agent/opa/topdown/copypropagation/copypropagation.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/copypropagation/copypropagation.go index 8824d19bd2..233bbcad1b 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/copypropagation/copypropagation.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/copypropagation/copypropagation.go @@ -8,7 +8,7 @@ import ( "fmt" "sort" - "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/v1/ast" ) // CopyPropagator implements a simple copy propagation optimization to remove diff --git a/vendor/github.com/open-policy-agent/opa/topdown/copypropagation/unionfind.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/copypropagation/unionfind.go similarity index 96% rename from vendor/github.com/open-policy-agent/opa/topdown/copypropagation/unionfind.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/copypropagation/unionfind.go index 38ec56f315..679464250e 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/copypropagation/unionfind.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/copypropagation/unionfind.go @@ -7,8 +7,8 @@ package copypropagation import ( "fmt" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/util" ) type rankFunc func(*unionFindRoot, *unionFindRoot) (*unionFindRoot, *unionFindRoot) diff --git a/vendor/github.com/open-policy-agent/opa/topdown/crypto.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/crypto.go similarity index 93% rename from vendor/github.com/open-policy-agent/opa/topdown/crypto.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/crypto.go index f24432a264..ab499e3e8f 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/crypto.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/crypto.go @@ -15,6 +15,7 @@ import ( "crypto/tls" "crypto/x509" "encoding/base64" + "encoding/hex" "encoding/json" "encoding/pem" "fmt" @@ -25,9 +26,9 @@ import ( "github.com/open-policy-agent/opa/internal/jwx/jwk" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" + "github.com/open-policy-agent/opa/v1/util" ) const ( @@ -96,7 +97,7 @@ func builtinCryptoX509ParseAndVerifyCertificates(_ BuiltinContext, operands []*a } invalid := ast.ArrayTerm( - ast.BooleanTerm(false), + ast.InternedBooleanTerm(false), ast.NewTerm(ast.NewArray()), ) @@ -116,7 +117,7 @@ func builtinCryptoX509ParseAndVerifyCertificates(_ BuiltinContext, operands []*a } valid := ast.ArrayTerm( - ast.BooleanTerm(true), + ast.InternedBooleanTerm(true), ast.NewTerm(value), ) @@ -152,14 +153,12 @@ func builtinCryptoX509ParseAndVerifyCertificatesWithOptions(_ BuiltinContext, op return err } - invalid := ast.ArrayTerm( - ast.BooleanTerm(false), - ast.NewTerm(ast.NewArray()), - ) - certs, err := getX509CertsFromString(string(input)) if err != nil { - return iter(invalid) + return iter(ast.ArrayTerm( + ast.InternedBooleanTerm(false), + ast.NewTerm(ast.NewArray()), + )) } // Collect the cert verification options @@ -170,7 +169,10 @@ func builtinCryptoX509ParseAndVerifyCertificatesWithOptions(_ BuiltinContext, op verified, err := verifyX509CertificateChain(certs, verifyOpt) if err != nil { - return iter(invalid) + return iter(ast.ArrayTerm( + ast.InternedBooleanTerm(false), + ast.NewTerm(ast.NewArray()), + )) } value, err := ast.InterfaceToValue(verified) @@ -178,12 +180,10 @@ func builtinCryptoX509ParseAndVerifyCertificatesWithOptions(_ BuiltinContext, op return err } - valid := ast.ArrayTerm( - ast.BooleanTerm(true), + return iter(ast.ArrayTerm( + ast.InternedBooleanTerm(true), ast.NewTerm(value), - ) - - return iter(valid) + )) } func extractVerifyOpts(options ast.Object) (verifyOpt x509.VerifyOptions, err error) { @@ -374,7 +374,7 @@ func builtinCryptoJWKFromPrivateKey(_ BuiltinContext, operands []*ast.Term, iter } if len(rawKeys) == 0 { - return iter(ast.NullTerm()) + return iter(ast.InternedNullTerm) } key, err := jwk.New(rawKeys[0]) @@ -408,7 +408,7 @@ func builtinCryptoParsePrivateKeys(_ BuiltinContext, operands []*ast.Term, iter } if string(input) == "" { - return iter(ast.NullTerm()) + return iter(ast.InternedNullTerm) } // get the raw private key @@ -418,7 +418,7 @@ func builtinCryptoParsePrivateKeys(_ BuiltinContext, operands []*ast.Term, iter } if len(rawKeys) == 0 { - return iter(ast.NewTerm(ast.NewArray())) + return iter(emptyArr) } bs, err := json.Marshal(rawKeys) @@ -439,36 +439,43 @@ func builtinCryptoParsePrivateKeys(_ BuiltinContext, operands []*ast.Term, iter return iter(ast.NewTerm(value)) } -func hashHelper(a ast.Value, h func(ast.String) string) (ast.Value, error) { - s, err := builtins.StringOperand(a, 1) - if err != nil { - return nil, err - } - return ast.String(h(s)), nil +func toHexEncodedString(src []byte) string { + dst := make([]byte, hex.EncodedLen(len(src))) + hex.Encode(dst, src) + return util.ByteSliceToString(dst) } func builtinCryptoMd5(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { - res, err := hashHelper(operands[0].Value, func(s ast.String) string { return fmt.Sprintf("%x", md5.Sum([]byte(s))) }) + s, err := builtins.StringOperand(operands[0].Value, 1) if err != nil { return err } - return iter(ast.NewTerm(res)) + + md5sum := md5.Sum([]byte(s)) + + return iter(ast.StringTerm(toHexEncodedString(md5sum[:]))) } func builtinCryptoSha1(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { - res, err := hashHelper(operands[0].Value, func(s ast.String) string { return fmt.Sprintf("%x", sha1.Sum([]byte(s))) }) + s, err := builtins.StringOperand(operands[0].Value, 1) if err != nil { return err } - return iter(ast.NewTerm(res)) + + sha1sum := sha1.Sum([]byte(s)) + + return iter(ast.StringTerm(toHexEncodedString(sha1sum[:]))) } func builtinCryptoSha256(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { - res, err := hashHelper(operands[0].Value, func(s ast.String) string { return fmt.Sprintf("%x", sha256.Sum256([]byte(s))) }) + s, err := builtins.StringOperand(operands[0].Value, 1) if err != nil { return err } - return iter(ast.NewTerm(res)) + + sha256sum := sha256.Sum256([]byte(s)) + + return iter(ast.StringTerm(toHexEncodedString(sha256sum[:]))) } func hmacHelper(operands []*ast.Term, iter func(*ast.Term) error, h func() hash.Hash) error { @@ -522,7 +529,7 @@ func builtinCryptoHmacEqual(_ BuiltinContext, operands []*ast.Term, iter func(*a res := hmac.Equal([]byte(mac1), []byte(mac2)) - return iter(ast.BooleanTerm(res)) + return iter(ast.InternedBooleanTerm(res)) } func init() { @@ -725,9 +732,11 @@ func readCertFromFile(localCertFile string) ([]byte, error) { return certPEM, nil } +var beginPrefix = []byte("-----BEGIN ") + func getTLSx509KeyPairFromString(certPemBlock []byte, keyPemBlock []byte) (*tls.Certificate, error) { - if !strings.HasPrefix(string(certPemBlock), "-----BEGIN") { + if !bytes.HasPrefix(certPemBlock, beginPrefix) { s, err := base64.StdEncoding.DecodeString(string(certPemBlock)) if err != nil { return nil, err @@ -735,7 +744,7 @@ func getTLSx509KeyPairFromString(certPemBlock []byte, keyPemBlock []byte) (*tls. certPemBlock = s } - if !strings.HasPrefix(string(keyPemBlock), "-----BEGIN") { + if !bytes.HasPrefix(keyPemBlock, beginPrefix) { s, err := base64.StdEncoding.DecodeString(string(keyPemBlock)) if err != nil { return nil, err @@ -744,7 +753,7 @@ func getTLSx509KeyPairFromString(certPemBlock []byte, keyPemBlock []byte) (*tls. } // we assume it a DER certificate and try to convert it to a PEM. - if !bytes.HasPrefix(certPemBlock, []byte("-----BEGIN")) { + if !bytes.HasPrefix(certPemBlock, beginPrefix) { pemBlock := &pem.Block{ Type: "CERTIFICATE", diff --git a/vendor/github.com/open-policy-agent/opa/topdown/doc.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/doc.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/topdown/doc.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/doc.go diff --git a/vendor/github.com/open-policy-agent/opa/topdown/encoding.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/encoding.go similarity index 95% rename from vendor/github.com/open-policy-agent/opa/topdown/encoding.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/encoding.go index f3475a60d0..a27a9c2450 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/encoding.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/encoding.go @@ -15,9 +15,9 @@ import ( "sigs.k8s.io/yaml" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" + "github.com/open-policy-agent/opa/v1/util" ) func builtinJSONMarshal(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -144,10 +144,10 @@ func builtinJSONIsValid(_ BuiltinContext, operands []*ast.Term, iter func(*ast.T str, err := builtins.StringOperand(operands[0].Value, 1) if err != nil { - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } - return iter(ast.BooleanTerm(json.Valid([]byte(str)))) + return iter(ast.InternedBooleanTerm(json.Valid([]byte(str)))) } func builtinBase64Encode(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -175,11 +175,11 @@ func builtinBase64Decode(_ BuiltinContext, operands []*ast.Term, iter func(*ast. func builtinBase64IsValid(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { str, err := builtins.StringOperand(operands[0].Value, 1) if err != nil { - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } _, err = base64.StdEncoding.DecodeString(string(str)) - return iter(ast.BooleanTerm(err == nil)) + return iter(ast.InternedBooleanTerm(err == nil)) } func builtinBase64UrlEncode(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -355,12 +355,12 @@ func builtinYAMLUnmarshal(_ BuiltinContext, operands []*ast.Term, iter func(*ast func builtinYAMLIsValid(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { str, err := builtins.StringOperand(operands[0].Value, 1) if err != nil { - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } var x interface{} err = yaml.Unmarshal([]byte(str), &x) - return iter(ast.BooleanTerm(err == nil)) + return iter(ast.InternedBooleanTerm(err == nil)) } func builtinHexEncode(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { diff --git a/vendor/github.com/open-policy-agent/opa/topdown/errors.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/errors.go similarity index 98% rename from vendor/github.com/open-policy-agent/opa/topdown/errors.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/errors.go index 918df6c853..cadd163198 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/errors.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/errors.go @@ -8,7 +8,7 @@ import ( "errors" "fmt" - "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/v1/ast" ) // Halt is a special error type that built-in function implementations return to indicate diff --git a/vendor/github.com/open-policy-agent/opa/topdown/eval.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/eval.go similarity index 87% rename from vendor/github.com/open-policy-agent/opa/topdown/eval.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/eval.go index 2fcc431c80..4758759e71 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/eval.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/eval.go @@ -5,19 +5,21 @@ import ( "errors" "fmt" "io" - "sort" + "slices" "strconv" "strings" - - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/metrics" - "github.com/open-policy-agent/opa/storage" - "github.com/open-policy-agent/opa/topdown/builtins" - "github.com/open-policy-agent/opa/topdown/cache" - "github.com/open-policy-agent/opa/topdown/copypropagation" - "github.com/open-policy-agent/opa/topdown/print" - "github.com/open-policy-agent/opa/tracing" - "github.com/open-policy-agent/opa/types" + "sync" + + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/metrics" + "github.com/open-policy-agent/opa/v1/storage" + "github.com/open-policy-agent/opa/v1/topdown/builtins" + "github.com/open-policy-agent/opa/v1/topdown/cache" + "github.com/open-policy-agent/opa/v1/topdown/copypropagation" + "github.com/open-policy-agent/opa/v1/topdown/print" + "github.com/open-policy-agent/opa/v1/tracing" + "github.com/open-policy-agent/opa/v1/types" + "github.com/open-policy-agent/opa/v1/util" ) type evalIterator func(*eval) error @@ -57,59 +59,91 @@ func (ee deferredEarlyExitError) Error() string { return fmt.Sprintf("%v: deferred early exit", ee.e.query) } +// Note(æ): this struct is formatted for optimal alignment as it is big, internal and instantiated +// *very* frequently during evaluation. If you need to add fields here, please consider the alignment +// of the struct, and use something like betteralign (https://github.com/dkorunic/betteralign) if you +// need help with that. type eval struct { - ctx context.Context - metrics metrics.Metrics - seed io.Reader - time *ast.Term - queryID uint64 - queryIDFact *queryIDFactory - parent *eval - caller *eval - cancel Cancel - query ast.Body - queryCompiler ast.QueryCompiler - index int - indexing bool - earlyExit bool - bindings *bindings - store storage.Store - baseCache *baseCache - txn storage.Transaction - compiler *ast.Compiler - input *ast.Term - data *ast.Term - external *resolverTrie - targetStack *refStack - tracers []QueryTracer - traceEnabled bool - traceLastLocation *ast.Location // Last location of a trace event. - plugTraceVars bool - instr *Instrumentation - builtins map[string]*Builtin - builtinCache builtins.Cache - ndBuiltinCache builtins.NDBCache - functionMocks *functionMocksStack - virtualCache VirtualCache - comprehensionCache *comprehensionCache - interQueryBuiltinCache cache.InterQueryCache - saveSet *saveSet - saveStack *saveStack - saveSupport *saveSupport - saveNamespace *ast.Term - skipSaveNamespace bool - inliningControl *inliningControl - genvarprefix string - genvarid int - runtime *ast.Term - builtinErrors *builtinErrors - printHook print.Hook - tracingOpts tracing.Options - findOne bool - strictObjects bool + ctx context.Context + metrics metrics.Metrics + seed io.Reader + cancel Cancel + queryCompiler ast.QueryCompiler + store storage.Store + txn storage.Transaction + virtualCache VirtualCache + interQueryBuiltinCache cache.InterQueryCache + interQueryBuiltinValueCache cache.InterQueryValueCache + printHook print.Hook + time *ast.Term + queryIDFact *queryIDFactory + parent *eval + caller *eval + bindings *bindings + baseCache *baseCache + compiler *ast.Compiler + input *ast.Term + data *ast.Term + external *resolverTrie + targetStack *refStack + traceLastLocation *ast.Location // Last location of a trace event. + instr *Instrumentation + builtins map[string]*Builtin + builtinCache builtins.Cache + ndBuiltinCache builtins.NDBCache + functionMocks *functionMocksStack + comprehensionCache *comprehensionCache + saveSet *saveSet + saveStack *saveStack + saveSupport *saveSupport + saveNamespace *ast.Term + inliningControl *inliningControl + runtime *ast.Term + builtinErrors *builtinErrors + roundTripper CustomizeRoundTripper + genvarprefix string + query ast.Body + tracers []QueryTracer + tracingOpts tracing.Options + queryID uint64 + index int + genvarid int + indexing bool + earlyExit bool + traceEnabled bool + plugTraceVars bool + skipSaveNamespace bool + findOne bool + strictObjects bool + defined bool +} + +type evp struct { + pool sync.Pool +} + +func (ep *evp) Put(e *eval) { + ep.pool.Put(e) +} + +func (ep *evp) Get() *eval { + return ep.pool.Get().(*eval) +} + +var evalPool = evp{ + pool: sync.Pool{ + New: func() any { + return &eval{} + }, + }, } func (e *eval) Run(iter evalIterator) error { + if !e.traceEnabled { + // avoid function literal escaping to heap if we don't need the trace + return e.eval(iter) + } + e.traceEnter(e.query) return e.eval(func(e *eval) error { e.traceExit(e.query) @@ -150,25 +184,23 @@ func (e *eval) builtinFunc(name string) (*ast.Builtin, BuiltinFunc, bool) { return nil, nil, false } -func (e *eval) closure(query ast.Body) *eval { - cpy := *e +func (e *eval) closure(query ast.Body, cpy *eval) { + *cpy = *e cpy.index = 0 cpy.query = query cpy.queryID = cpy.queryIDFact.Next() cpy.parent = e cpy.findOne = false - return &cpy } -func (e *eval) child(query ast.Body) *eval { - cpy := *e +func (e *eval) child(query ast.Body, cpy *eval) { + *cpy = *e cpy.index = 0 cpy.query = query cpy.queryID = cpy.queryIDFact.Next() cpy.bindings = newBindings(cpy.queryID, e.instr) cpy.parent = e cpy.findOne = false - return &cpy } func (e *eval) next(iter evalIterator) error { @@ -334,6 +366,13 @@ func (e *eval) evalExpr(iter evalIterator) error { } if e.cancel != nil && e.cancel.Cancelled() { + if e.ctx != nil && e.ctx.Err() != nil { + return &Error{ + Code: CancelErr, + Message: e.ctx.Err().Error(), + err: e.ctx.Err(), + } + } return &Error{ Code: CancelErr, Message: "caller cancelled query execution", @@ -345,9 +384,7 @@ func (e *eval) evalExpr(iter evalIterator) error { if err != nil { switch err := err.(type) { - case *deferredEarlyExitError: - return wrapErr(err) - case *earlyExitError: + case *deferredEarlyExitError, *earlyExitError: return wrapErr(err) default: return err @@ -373,46 +410,110 @@ func (e *eval) evalExpr(iter evalIterator) error { } func (e *eval) evalStep(iter evalIterator) error { - expr := e.query[e.index] if expr.Negated { return e.evalNot(iter) } - var defined bool var err error + + // NOTE(æ): the reason why there's one branch for the tracing case and one almost + // identical branch below for when tracing is disabled is that the tracing case + // allocates wildly. These allocations are cause by the "defined" boolean variable + // escaping to the heap as its value is set from inside of closures. There may very + // well be more elegant solutions to this problem, but this is one that works, and + // saves several *million* allocations for some workloads. So feel free to refactor + // this, but do make sure that the common non-tracing case doesn't pay in allocations + // for something that is only needed when tracing is enabled. + if e.traceEnabled { + var defined bool + switch terms := expr.Terms.(type) { + case []*ast.Term: + switch { + case expr.IsEquality(): + err = e.unify(terms[1], terms[2], func() error { + defined = true + err := iter(e) + e.traceRedo(expr) + return err + }) + default: + err = e.evalCall(terms, func() error { + defined = true + err := iter(e) + e.traceRedo(expr) + return err + }) + } + case *ast.Term: + // generateVar inlined here to avoid extra allocations in hot path + rterm := ast.VarTerm(e.fmtVarTerm()) + err = e.unify(terms, rterm, func() error { + if e.saveSet.Contains(rterm, e.bindings) { + return e.saveExpr(ast.NewExpr(rterm), e.bindings, func() error { + return iter(e) + }) + } + if !e.bindings.Plug(rterm).Equal(ast.InternedBooleanTerm(false)) { + defined = true + err := iter(e) + e.traceRedo(expr) + return err + } + return nil + }) + case *ast.Every: + eval := evalEvery{ + Every: terms, + e: e, + expr: expr, + } + err = eval.eval(func() error { + defined = true + err := iter(e) + e.traceRedo(expr) + return err + }) + + default: // guard-rail for adding extra (Expr).Terms types + return fmt.Errorf("got %T terms: %[1]v", terms) + } + + if err != nil { + return err + } + + if !defined { + e.traceFail(expr) + } + + return nil + } + switch terms := expr.Terms.(type) { case []*ast.Term: switch { case expr.IsEquality(): err = e.unify(terms[1], terms[2], func() error { - defined = true - err := iter(e) - e.traceRedo(expr) - return err + return iter(e) }) default: err = e.evalCall(terms, func() error { - defined = true - err := iter(e) - e.traceRedo(expr) - return err + return iter(e) }) } case *ast.Term: - rterm := e.generateVar(fmt.Sprintf("term_%d_%d", e.queryID, e.index)) + // generateVar inlined here to avoid extra allocations in hot path + rterm := ast.VarTerm(e.fmtVarTerm()) err = e.unify(terms, rterm, func() error { if e.saveSet.Contains(rterm, e.bindings) { return e.saveExpr(ast.NewExpr(rterm), e.bindings, func() error { return iter(e) }) } - if !e.bindings.Plug(rterm).Equal(ast.BooleanTerm(false)) { - defined = true - err := iter(e) - e.traceRedo(expr) - return err + if !e.bindings.Plug(rterm).Equal(ast.InternedBooleanTerm(false)) { + return iter(e) } return nil }) @@ -423,25 +524,28 @@ func (e *eval) evalStep(iter evalIterator) error { expr: expr, } err = eval.eval(func() error { - defined = true - err := iter(e) - e.traceRedo(expr) - return err + return iter(e) }) default: // guard-rail for adding extra (Expr).Terms types return fmt.Errorf("got %T terms: %[1]v", terms) } - if err != nil { - return err - } + return err +} - if !defined { - e.traceFail(expr) - } +// Single-purpose fmt.Sprintf replacement for generating variable names with only +// one allocation performed instead of 4, and in 1/3 the time. +func (e *eval) fmtVarTerm() string { + buf := make([]byte, 0, len(e.genvarprefix)+util.NumDigitsUint(e.queryID)+util.NumDigitsInt(e.index)+7) - return nil + buf = append(buf, e.genvarprefix...) + buf = append(buf, "_term_"...) + buf = strconv.AppendUint(buf, e.queryID, 10) + buf = append(buf, '_') + buf = strconv.AppendInt(buf, int64(e.index), 10) + + return util.ByteSliceToString(buf) } func (e *eval) evalNot(iter evalIterator) error { @@ -452,27 +556,34 @@ func (e *eval) evalNot(iter evalIterator) error { return e.evalNotPartial(iter) } - negation := ast.NewBody(expr.Complement().NoWith()) - child := e.closure(negation) + negation := ast.NewBody(expr.ComplementNoWith()) + child := evalPool.Get() + defer evalPool.Put(child) - var defined bool - child.traceEnter(negation) + e.closure(negation, child) - err := child.eval(func(*eval) error { - child.traceExit(negation) - defined = true - child.traceRedo(negation) - return nil - }) + if e.traceEnabled { + child.traceEnter(negation) + } - if err != nil { + if err := child.eval(func(*eval) error { + if e.traceEnabled { + child.traceExit(negation) + child.traceRedo(negation) + } + child.defined = true + + return nil + }); err != nil { return err } - if !defined { + if !child.defined { return iter(e) } + child.defined = false + e.traceFail(expr) return nil } @@ -612,11 +723,14 @@ func (e *eval) evalWithPop(input, data *ast.Term) { } func (e *eval) evalNotPartial(iter evalIterator) error { - // Prepare query normally. expr := e.query[e.index] - negation := expr.Complement().NoWith() - child := e.closure(ast.NewBody(negation)) + negation := expr.ComplementNoWith() + + child := evalPool.Get() + defer evalPool.Put(child) + + e.closure(ast.NewBody(negation), child) // Unknowns is the set of variables that are marked as unknown. The variables // are namespaced with the query ID that they originate in. This ensures that @@ -709,9 +823,7 @@ func (e *eval) evalNotPartialSupport(negationID uint64, expr *ast.Expr, unknowns args = append(args, ast.NewTerm(v)) } - sort.Slice(args, func(i, j int) bool { - return args[i].Value.Compare(args[j].Value) < 0 - }) + slices.SortFunc(args, ast.TermValueCompare) if len(args) > 0 { head.Args = args @@ -769,7 +881,7 @@ func (e *eval) evalCall(terms []*ast.Term, iter unifyIterator) error { if ref[0].Equal(ast.DefaultRootDocument) { if mocked { f := e.compiler.TypeEnv.Get(ref).(*types.Function) - return e.evalCallValue(len(f.FuncArgs().Args), terms, mock, iter) + return e.evalCallValue(f.Arity(), terms, mock, iter) } var ir *ast.IndexResult @@ -799,11 +911,11 @@ func (e *eval) evalCall(terms []*ast.Term, iter unifyIterator) error { } if mocked { // value replacement of built-in call - return e.evalCallValue(len(bi.Decl.Args()), terms, mock, iter) + return e.evalCallValue(bi.Decl.Arity(), terms, mock, iter) } if e.unknown(e.query[e.index], e.bindings) { - return e.saveCall(len(bi.Decl.Args()), terms, iter) + return e.saveCall(bi.Decl.Arity(), terms, iter) } var parentID uint64 @@ -817,23 +929,25 @@ func (e *eval) evalCall(terms []*ast.Term, iter unifyIterator) error { } bctx := BuiltinContext{ - Context: e.ctx, - Metrics: e.metrics, - Seed: e.seed, - Time: e.time, - Cancel: e.cancel, - Runtime: e.runtime, - Cache: e.builtinCache, - InterQueryBuiltinCache: e.interQueryBuiltinCache, - NDBuiltinCache: e.ndBuiltinCache, - Location: e.query[e.index].Location, - QueryTracers: e.tracers, - TraceEnabled: e.traceEnabled, - QueryID: e.queryID, - ParentID: parentID, - PrintHook: e.printHook, - DistributedTracingOpts: e.tracingOpts, - Capabilities: capabilities, + Context: e.ctx, + Metrics: e.metrics, + Seed: e.seed, + Time: e.time, + Cancel: e.cancel, + Runtime: e.runtime, + Cache: e.builtinCache, + InterQueryBuiltinCache: e.interQueryBuiltinCache, + InterQueryBuiltinValueCache: e.interQueryBuiltinValueCache, + NDBuiltinCache: e.ndBuiltinCache, + Location: e.query[e.index].Location, + QueryTracers: e.tracers, + TraceEnabled: e.traceEnabled, + QueryID: e.queryID, + ParentID: parentID, + PrintHook: e.printHook, + DistributedTracingOpts: e.tracingOpts, + Capabilities: capabilities, + RoundTripper: e.roundTripper, } eval := evalBuiltin{ @@ -853,7 +967,7 @@ func (e *eval) evalCallValue(arity int, terms []*ast.Term, mock *ast.Term, iter return e.unify(terms[len(terms)-1], mock, iter) case len(terms) == arity+1: - if mock.Value.Compare(ast.Boolean(false)) != 0 { + if !ast.Boolean(false).Equal(mock.Value) { return iter() } return nil @@ -930,6 +1044,22 @@ func (e *eval) biunifyArraysRec(a, b *ast.Array, b1, b2 *bindings, iter unifyIte }) } +func (e *eval) biunifyTerms(a, b []*ast.Term, b1, b2 *bindings, iter unifyIterator) error { + if len(a) != len(b) { + return nil + } + return e.biunifyTermsRec(a, b, b1, b2, iter, 0) +} + +func (e *eval) biunifyTermsRec(a, b []*ast.Term, b1, b2 *bindings, iter unifyIterator, idx int) error { + if idx == len(a) { + return iter() + } + return e.biunify(a[idx], b[idx], b1, b2, func() error { + return e.biunifyTermsRec(a, b, b1, b2, iter, idx+1) + }) +} + func (e *eval) biunifyObjects(a, b ast.Object, b1, b2 *bindings, iter unifyIterator) error { if a.Len() != b.Len() { return nil @@ -1163,7 +1293,10 @@ func (e *eval) buildComprehensionCache(a *ast.Term) (*ast.Term, error) { } func (e *eval) buildComprehensionCacheArray(x *ast.ArrayComprehension, keys []*ast.Term) (*comprehensionCacheElem, error) { - child := e.child(x.Body) + child := evalPool.Get() + defer evalPool.Put(child) + + e.child(x.Body, child) node := newComprehensionCacheElem() return node, child.Run(func(child *eval) error { values := make([]*ast.Term, len(keys)) @@ -1182,7 +1315,10 @@ func (e *eval) buildComprehensionCacheArray(x *ast.ArrayComprehension, keys []*a } func (e *eval) buildComprehensionCacheSet(x *ast.SetComprehension, keys []*ast.Term) (*comprehensionCacheElem, error) { - child := e.child(x.Body) + child := evalPool.Get() + defer evalPool.Put(child) + + e.child(x.Body, child) node := newComprehensionCacheElem() return node, child.Run(func(child *eval) error { values := make([]*ast.Term, len(keys)) @@ -1202,7 +1338,10 @@ func (e *eval) buildComprehensionCacheSet(x *ast.SetComprehension, keys []*ast.T } func (e *eval) buildComprehensionCacheObject(x *ast.ObjectComprehension, keys []*ast.Term) (*comprehensionCacheElem, error) { - child := e.child(x.Body) + child := evalPool.Get() + defer evalPool.Put(child) + + e.child(x.Body, child) node := newComprehensionCacheElem() return node, child.Run(func(child *eval) error { values := make([]*ast.Term, len(keys)) @@ -1283,7 +1422,11 @@ func (e *eval) amendComprehension(a *ast.Term, b1 *bindings) (*ast.Term, error) func (e *eval) biunifyComprehensionArray(x *ast.ArrayComprehension, b *ast.Term, b1, b2 *bindings, iter unifyIterator) error { result := ast.NewArray() - child := e.closure(x.Body) + child := evalPool.Get() + + e.closure(x.Body, child) + defer evalPool.Put(child) + err := child.Run(func(child *eval) error { result = result.Append(child.bindings.Plug(x.Term)) return nil @@ -1296,7 +1439,11 @@ func (e *eval) biunifyComprehensionArray(x *ast.ArrayComprehension, b *ast.Term, func (e *eval) biunifyComprehensionSet(x *ast.SetComprehension, b *ast.Term, b1, b2 *bindings, iter unifyIterator) error { result := ast.NewSet() - child := e.closure(x.Body) + child := evalPool.Get() + + e.closure(x.Body, child) + defer evalPool.Put(child) + err := child.Run(func(child *eval) error { result.Add(child.bindings.Plug(x.Term)) return nil @@ -1308,8 +1455,13 @@ func (e *eval) biunifyComprehensionSet(x *ast.SetComprehension, b *ast.Term, b1, } func (e *eval) biunifyComprehensionObject(x *ast.ObjectComprehension, b *ast.Term, b1, b2 *bindings, iter unifyIterator) error { + child := evalPool.Get() + defer evalPool.Put(child) + + e.closure(x.Body, child) + result := ast.NewObject() - child := e.closure(x.Body) + err := child.Run(func(child *eval) error { key := child.bindings.Plug(x.Key) value := child.bindings.Plug(x.Value) @@ -1446,12 +1598,22 @@ func (e *eval) getRules(ref ast.Ref, args []*ast.Term) (*ast.IndexResult, error) return nil, nil } + resolver := resolverPool.Get().(*evalResolver) + defer func() { + resolver.e = nil + resolver.args = nil + resolverPool.Put(resolver) + }() + var result *ast.IndexResult var err error if e.indexing { - result, err = index.Lookup(&evalResolver{e: e, args: args}) + resolver.e = e + resolver.args = args + result, err = index.Lookup(resolver) } else { - result, err = index.AllRules(&evalResolver{e: e}) + resolver.e = e + result, err = index.AllRules(resolver) } if err != nil { return nil, err @@ -1459,20 +1621,27 @@ func (e *eval) getRules(ref ast.Ref, args []*ast.Term) (*ast.IndexResult, error) result.EarlyExit = result.EarlyExit && e.earlyExit - var msg strings.Builder - if len(result.Rules) == 1 { - msg.WriteString("(matched 1 rule") - } else { - msg.Grow(len("(matched NNNN rules)")) - msg.WriteString("(matched ") - msg.WriteString(strconv.Itoa(len(result.Rules))) - msg.WriteString(" rules") - } - if result.EarlyExit { - msg.WriteString(", early exit") + if e.traceEnabled { + var msg strings.Builder + if len(result.Rules) == 1 { + msg.WriteString("(matched 1 rule") + } else { + msg.Grow(len("(matched NNNN rules)")) + msg.WriteString("(matched ") + msg.WriteString(strconv.Itoa(len(result.Rules))) + msg.WriteString(" rules") + } + if result.EarlyExit { + msg.WriteString(", early exit") + } + msg.WriteRune(')') + + // Copy ref here as ref otherwise always escapes to the heap, + // whether tracing is enabled or not. + r := ref.Copy() + e.traceIndex(e.query[e.index], msg.String(), &r) } - msg.WriteRune(')') - e.traceIndex(e.query[e.index], msg.String(), &ref) + return result, err } @@ -1485,10 +1654,20 @@ type evalResolver struct { args []*ast.Term } +var ( + resolverPool = sync.Pool{ + New: func() any { + return &evalResolver{} + }, + } +) + func (e *evalResolver) Resolve(ref ast.Ref) (ast.Value, error) { e.e.instr.startTimer(evalOpResolve) - if e.e.inliningControl.Disabled(ref, true) || e.e.saveSet.Contains(ast.NewTerm(ref), nil) { + // NOTE(ae): nil check on saveSet to avoid ast.NewTerm allocation when not needed + if e.e.inliningControl.Disabled(ref, true) || (e.e.saveSet != nil && + e.e.saveSet.Contains(ast.NewTerm(ref), nil)) { e.e.instr.stopTimer(evalOpResolve) return nil, ast.UnknownValueErr{} } @@ -1652,7 +1831,13 @@ func (e *eval) resolveReadFromStorage(ref ast.Ref, a ast.Value) (ast.Value, erro } func (e *eval) generateVar(suffix string) *ast.Term { - return ast.VarTerm(fmt.Sprintf("%v_%v", e.genvarprefix, suffix)) + buf := make([]byte, 0, len(e.genvarprefix)+len(suffix)+1) + + buf = append(buf, e.genvarprefix...) + buf = append(buf, '_') + buf = append(buf, suffix...) + + return ast.VarTerm(util.ByteSliceToString(buf)) } func (e *eval) rewrittenVar(v ast.Var) (ast.Var, bool) { @@ -1679,7 +1864,7 @@ func (e *eval) getDeclArgsLen(x *ast.Expr) (int, error) { bi, _, ok := e.builtinFunc(operator.String()) if ok { - return len(bi.Decl.Args()), nil + return bi.Decl.Arity(), nil } ir, err := e.getRules(operator, nil) @@ -1714,7 +1899,7 @@ func (e *evalBuiltin) canUseNDBCache(bi *ast.Builtin) bool { return bi.Nondeterministic && e.bctx.NDBuiltinCache != nil } -func (e evalBuiltin) eval(iter unifyIterator) error { +func (e *evalBuiltin) eval(iter unifyIterator) error { operands := make([]*ast.Term, len(e.terms)) @@ -1722,7 +1907,7 @@ func (e evalBuiltin) eval(iter unifyIterator) error { operands[i] = e.e.bindings.Plug(e.terms[i]) } - numDeclArgs := len(e.bi.Decl.FuncArgs().Args) + numDeclArgs := e.bi.Decl.Arity() e.e.instr.startTimer(evalOpBuiltinCall) var err error @@ -1747,7 +1932,7 @@ func (e evalBuiltin) eval(iter unifyIterator) error { case e.bi.Decl.Result() == nil: return iter() case len(operands) == numDeclArgs: - if v.Compare(ast.Boolean(false)) == 0 { + if ast.Boolean(false).Equal(v) { return nil // nothing to do } return iter() @@ -1771,7 +1956,7 @@ func (e evalBuiltin) eval(iter unifyIterator) error { case e.bi.Decl.Result() == nil: err = iter() case len(operands) == numDeclArgs: - if output.Value.Compare(ast.Boolean(false)) != 0 { + if !ast.Boolean(false).Equal(output.Value) { err = iter() } // else: nothing to do, don't iter() default: @@ -1811,9 +1996,9 @@ func (e evalBuiltin) eval(iter unifyIterator) error { type evalFunc struct { e *eval + ir *ast.IndexResult ref ast.Ref terms []*ast.Term - ir *ast.IndexResult } func (e evalFunc) eval(iter unifyIterator) error { @@ -1852,9 +2037,9 @@ func (e evalFunc) eval(iter unifyIterator) error { func (e evalFunc) evalValue(iter unifyIterator, argCount int, findOne bool) error { var cacheKey ast.Ref - var hit bool - var err error if !e.e.partial() { + var hit bool + var err error cacheKey, hit, err = e.evalCache(argCount, iter) if err != nil { return err @@ -1920,9 +2105,15 @@ func (e evalFunc) evalCache(argCount int, iter unifyIterator) (ast.Ref, bool, er } else { plen = len(e.terms) } + cacheKey := make([]*ast.Term, plen) for i := 0; i < plen; i++ { - cacheKey[i] = e.e.bindings.Plug(e.terms[i]) + if e.terms[i].IsGround() { + // Avoid expensive copying of ref if it is ground. + cacheKey[i] = e.terms[i] + } else { + cacheKey[i] = e.e.bindings.Plug(e.terms[i]) + } } cached, _ := e.e.virtualCache.Get(cacheKey) @@ -1942,8 +2133,10 @@ func (e evalFunc) evalCache(argCount int, iter unifyIterator) (ast.Ref, bool, er } func (e evalFunc) evalOneRule(iter unifyIterator, rule *ast.Rule, cacheKey ast.Ref, prev *ast.Term, findOne bool) (*ast.Term, error) { + child := evalPool.Get() + defer evalPool.Put(child) - child := e.e.child(rule.Body) + e.e.child(rule.Body, child) child.findOne = findOne args := make([]*ast.Term, len(e.terms)-1) @@ -1957,7 +2150,7 @@ func (e evalFunc) evalOneRule(iter unifyIterator, rule *ast.Rule, cacheKey ast.R child.traceEnter(rule) - err := child.biunifyArrays(ast.NewArray(e.terms[1:]...), ast.NewArray(args...), e.e.bindings, child.bindings, func() error { + err := child.biunifyTerms(e.terms[1:], args, e.e.bindings, child.bindings, func() error { return child.eval(func(child *eval) error { child.traceExit(rule) @@ -1975,8 +2168,8 @@ func (e evalFunc) evalOneRule(iter unifyIterator, rule *ast.Rule, cacheKey ast.R } if len(rule.Head.Args) == len(e.terms)-1 { - if result.Value.Compare(ast.Boolean(false)) == 0 { - if prev != nil && ast.Compare(prev, result) != 0 { + if ast.Boolean(false).Equal(result.Value) { + if prev != nil && !prev.Equal(result) { return functionConflictErr(rule.Location) } prev = result @@ -1990,7 +2183,7 @@ func (e evalFunc) evalOneRule(iter unifyIterator, rule *ast.Rule, cacheKey ast.R // an example. if !e.e.partial() { if prev != nil { - if ast.Compare(prev, result) != 0 { + if !prev.Equal(result) { return functionConflictErr(rule.Location) } child.traceRedo(rule) @@ -2015,7 +2208,6 @@ func (e evalFunc) evalOneRule(iter unifyIterator, rule *ast.Rule, cacheKey ast.R func (e evalFunc) partialEvalSupport(declArgsLen int, iter unifyIterator) error { path := e.e.namespaceRef(e.ref) - term := ast.NewTerm(path) if !e.e.saveSupport.Exists(path) { for _, rule := range e.ir.Rules { @@ -2030,12 +2222,16 @@ func (e evalFunc) partialEvalSupport(declArgsLen int, iter unifyIterator) error return nil } + term := ast.NewTerm(path) + return e.e.saveCall(declArgsLen, append([]*ast.Term{term}, e.terms[1:]...), iter) } func (e evalFunc) partialEvalSupportRule(rule *ast.Rule, path ast.Ref) error { + child := evalPool.Get() + defer evalPool.Put(child) - child := e.e.child(rule.Body) + e.e.child(rule.Body, child) child.traceEnter(rule) e.e.saveStack.PushQuery(nil) @@ -2084,13 +2280,13 @@ func (e evalFunc) partialEvalSupportRule(rule *ast.Rule, path ast.Ref) error { type evalTree struct { e *eval - ref ast.Ref - plugged ast.Ref - pos int bindings *bindings rterm *ast.Term rbindings *bindings node *ast.TreeNode + ref ast.Ref + plugged ast.Ref + pos int } func (e evalTree) eval(iter unifyIterator) error { @@ -2113,9 +2309,7 @@ func (e evalTree) finish(iter unifyIterator) error { // In some cases, it may not be possible to PE the ref. If the path refers // to virtual docs that PE does not support or base documents where inlining // has been disabled, then we have to save. - save := e.e.unknown(e.plugged, e.e.bindings) - - if save { + if e.e.partial() && e.e.unknown(e.plugged, e.e.bindings) { return e.e.saveUnify(ast.NewTerm(e.plugged), e.rterm, e.bindings, e.rbindings, iter) } @@ -2185,7 +2379,7 @@ func (e evalTree) enumerate(iter unifyIterator) error { switch doc := doc.(type) { case *ast.Array: for i := 0; i < doc.Len(); i++ { - k := ast.IntNumberTerm(i) + k := ast.InternedIntNumberTerm(i) err := e.e.biunify(k, e.ref[e.pos], e.bindings, e.bindings, func() error { return e.next(iter, k) }) @@ -2315,12 +2509,12 @@ func (e evalTree) leaves(plugged ast.Ref, node *ast.TreeNode) (ast.Object, error type evalVirtual struct { e *eval - ref ast.Ref - plugged ast.Ref - pos int bindings *bindings rterm *ast.Term rbindings *bindings + ref ast.Ref + plugged ast.Ref + pos int } func (e evalVirtual) eval(iter unifyIterator) error { @@ -2391,14 +2585,14 @@ func (e evalVirtual) eval(iter unifyIterator) error { type evalVirtualPartial struct { e *eval - ref ast.Ref - plugged ast.Ref - pos int ir *ast.IndexResult bindings *bindings rterm *ast.Term rbindings *bindings empty *ast.Term + ref ast.Ref + plugged ast.Ref + pos int } type evalVirtualPartialCacheHint struct { @@ -2457,14 +2651,16 @@ func (e evalVirtualPartial) evalEachRule(iter unifyIterator, unknown bool) error return nil } - m := maxRefLength(e.ir.Rules, len(e.ref)) - if e.e.unknown(e.ref[e.pos+1:m], e.bindings) { - for _, rule := range e.ir.Rules { - if err := e.evalOneRulePostUnify(iter, rule); err != nil { - return err + if e.e.partial() { + m := maxRefLength(e.ir.Rules, len(e.ref)) + if e.e.unknown(e.ref[e.pos+1:m], e.bindings) { + for _, rule := range e.ir.Rules { + if err := e.evalOneRulePostUnify(iter, rule); err != nil { + return err + } } + return nil } - return nil } hint, err := e.evalCache(iter) @@ -2534,8 +2730,11 @@ func (e evalVirtualPartial) evalAllRulesNoCache(rules []*ast.Rule) (*ast.Term, e var visitedRefs []ast.Ref + child := evalPool.Get() + defer evalPool.Put(child) + for _, rule := range rules { - child := e.e.child(rule.Body) + e.e.child(rule.Body, child) child.traceEnter(rule) err := child.eval(func(*eval) error { child.traceExit(rule) @@ -2568,8 +2767,10 @@ func wrapInObjects(leaf *ast.Term, ref ast.Ref) *ast.Term { } func (e evalVirtualPartial) evalOneRulePreUnify(iter unifyIterator, rule *ast.Rule, result *ast.Term, unknown bool, visitedRefs *[]ast.Ref) (*ast.Term, error) { + child := evalPool.Get() + defer evalPool.Put(child) - child := e.e.child(rule.Body) + e.e.child(rule.Body, child) child.traceEnter(rule) var defined bool @@ -2661,7 +2862,10 @@ func (e *eval) biunifyDynamicRef(pos int, a, b ast.Ref, b1, b2 *bindings, iter u } func (e evalVirtualPartial) evalOneRulePostUnify(iter unifyIterator, rule *ast.Rule) error { - child := e.e.child(rule.Body) + child := evalPool.Get() + defer evalPool.Put(child) + + e.e.child(rule.Body, child) child.traceEnter(rule) var defined bool @@ -2745,8 +2949,10 @@ func (e evalVirtualPartial) partialEvalSupport(iter unifyIterator) error { } func (e evalVirtualPartial) partialEvalSupportRule(rule *ast.Rule, _ ast.Ref) (bool, error) { + child := evalPool.Get() + defer evalPool.Put(child) - child := e.e.child(rule.Body) + e.e.child(rule.Body, child) child.traceEnter(rule) e.e.saveStack.PushQuery(nil) @@ -3109,13 +3315,13 @@ func (e evalVirtualPartial) reduce(rule *ast.Rule, b *bindings, result *ast.Term type evalVirtualComplete struct { e *eval - ref ast.Ref - plugged ast.Ref - pos int ir *ast.IndexResult bindings *bindings rterm *ast.Term rbindings *bindings + ref ast.Ref + plugged ast.Ref + pos int } func (e evalVirtualComplete) eval(iter unifyIterator) error { @@ -3224,8 +3430,10 @@ func (e evalVirtualComplete) evalValue(iter unifyIterator, findOne bool) error { } func (e evalVirtualComplete) evalValueRule(iter unifyIterator, rule *ast.Rule, prev *ast.Term, findOne bool) (*ast.Term, error) { + child := evalPool.Get() + defer evalPool.Put(child) - child := e.e.child(rule.Body) + e.e.child(rule.Body, child) child.findOne = findOne child.traceEnter(rule) var result *ast.Term @@ -3260,9 +3468,11 @@ func (e evalVirtualComplete) evalValueRule(iter unifyIterator, rule *ast.Rule, p } func (e evalVirtualComplete) partialEval(iter unifyIterator) error { + child := evalPool.Get() + defer evalPool.Put(child) for _, rule := range e.ir.Rules { - child := e.e.child(rule.Body) + e.e.child(rule.Body, child) child.traceEnter(rule) err := child.eval(func(child *eval) error { @@ -3325,8 +3535,10 @@ func (e evalVirtualComplete) partialEvalSupport(iter unifyIterator) error { } func (e evalVirtualComplete) partialEvalSupportRule(rule *ast.Rule, path ast.Ref) (bool, error) { + child := evalPool.Get() + defer evalPool.Put(child) - child := e.e.child(rule.Body) + e.e.child(rule.Body, child) child.traceEnter(rule) e.e.saveStack.PushQuery(nil) @@ -3381,13 +3593,13 @@ func (e evalVirtualComplete) evalTerm(iter unifyIterator, term *ast.Term, termbi type evalTerm struct { e *eval - ref ast.Ref - pos int bindings *bindings term *ast.Term termbindings *bindings rterm *ast.Term rbindings *bindings + ref ast.Ref + pos int } func (e evalTerm) eval(iter unifyIterator) error { @@ -3439,32 +3651,28 @@ func (e evalTerm) enumerate(iter unifyIterator) error { switch v := e.term.Value.(type) { case *ast.Array: for i := 0; i < v.Len(); i++ { - k := ast.IntNumberTerm(i) - err := e.e.biunify(k, e.ref[e.pos], e.bindings, e.bindings, func() error { + k := ast.InternedIntNumberTerm(i) + if err := handleErr(e.e.biunify(k, e.ref[e.pos], e.bindings, e.bindings, func() error { return e.next(iter, k) - }) - - if err := handleErr(err); err != nil { + })); err != nil { return err } } case ast.Object: - if err := v.Iter(func(k, _ *ast.Term) error { - err := e.e.biunify(k, e.ref[e.pos], e.termbindings, e.bindings, func() error { + for _, k := range v.Keys() { + if err := handleErr(e.e.biunify(k, e.ref[e.pos], e.termbindings, e.bindings, func() error { return e.next(iter, e.termbindings.Plug(k)) - }) - return handleErr(err) - }); err != nil { - return err + })); err != nil { + return err + } } case ast.Set: - if err := v.Iter(func(elem *ast.Term) error { - err := e.e.biunify(elem, e.ref[e.pos], e.termbindings, e.bindings, func() error { + for _, elem := range v.Slice() { + if err := handleErr(e.e.biunify(elem, e.ref[e.pos], e.termbindings, e.bindings, func() error { return e.next(iter, e.termbindings.Plug(elem)) - }) - return handleErr(err) - }); err != nil { - return err + })); err != nil { + return err + } } } @@ -3567,7 +3775,11 @@ func (e evalEvery) eval(iter unifyIterator) error { ).SetLocation(e.Domain.Location), ) - domain := e.e.closure(generator) + domain := evalPool.Get() + defer evalPool.Put(domain) + + e.e.closure(generator, domain) + all := true // all generator evaluations yield one successful body evaluation domain.traceEnter(e.expr) @@ -3578,7 +3790,11 @@ func (e evalEvery) eval(iter unifyIterator) error { // This would do extra work, like iterating needlessly if domain was a large array. return nil } - body := child.closure(e.Body) + + body := evalPool.Get() + defer evalPool.Put(body) + + child.closure(e.Body, body) body.findOne = true body.traceEnter(e.Body) done := false @@ -3705,10 +3921,12 @@ func applyCopyPropagation(p *copypropagation.CopyPropagator, instr *Instrumentat return result } +func nonGroundKey(k, _ *ast.Term) bool { + return !k.IsGround() +} + func nonGroundKeys(a ast.Object) bool { - return a.Until(func(k, _ *ast.Term) bool { - return !k.IsGround() - }) + return a.Until(nonGroundKey) } func plugKeys(a ast.Object, b *bindings) ast.Object { diff --git a/vendor/github.com/open-policy-agent/opa/v1/topdown/glob.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/glob.go new file mode 100644 index 0000000000..efaf1d1248 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/glob.go @@ -0,0 +1,127 @@ +package topdown + +import ( + "strings" + "sync" + + "github.com/gobwas/glob" + + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" +) + +const globCacheMaxSize = 100 +const globInterQueryValueCacheHits = "rego_builtin_glob_interquery_value_cache_hits" + +var noDelimiters = []rune{} +var dotDelimiters = []rune{'.'} +var globCacheLock = sync.RWMutex{} +var globCache = map[string]glob.Glob{} + +func builtinGlobMatch(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + pattern, err := builtins.StringOperand(operands[0].Value, 1) + if err != nil { + return err + } + + var delimiters []rune + switch operands[1].Value.(type) { + case ast.Null: + delimiters = noDelimiters + case *ast.Array: + delimiters, err = builtins.RuneSliceOperand(operands[1].Value, 2) + if err != nil { + return err + } + if len(delimiters) == 0 { + delimiters = dotDelimiters + } + default: + return builtins.NewOperandTypeErr(2, operands[1].Value, "array", "null") + } + + match, err := builtins.StringOperand(operands[2].Value, 3) + if err != nil { + return err + } + + builder := strings.Builder{} + builder.WriteString(string(pattern)) + builder.WriteRune('-') + for _, v := range delimiters { + builder.WriteRune(v) + } + id := builder.String() + + m, err := globCompileAndMatch(bctx, id, string(pattern), string(match), delimiters) + if err != nil { + return err + } + return iter(ast.InternedBooleanTerm(m)) +} + +func globCompileAndMatch(bctx BuiltinContext, id, pattern, match string, delimiters []rune) (bool, error) { + + if bctx.InterQueryBuiltinValueCache != nil { + // TODO: Use named cache + val, ok := bctx.InterQueryBuiltinValueCache.Get(ast.String(id)) + if ok { + pat, valid := val.(glob.Glob) + if !valid { + // The cache key may exist for a different value type (eg. regex). + // In this case, we calculate the glob and return the result w/o updating the cache. + var err error + if pat, err = glob.Compile(pattern, delimiters...); err != nil { + return false, err + } + return pat.Match(match), nil + } + bctx.Metrics.Counter(globInterQueryValueCacheHits).Incr() + out := pat.Match(match) + return out, nil + } + + res, err := glob.Compile(pattern, delimiters...) + if err != nil { + return false, err + } + bctx.InterQueryBuiltinValueCache.Insert(ast.String(id), res) + return res.Match(match), nil + } + + globCacheLock.RLock() + p, ok := globCache[id] + globCacheLock.RUnlock() + if !ok { + var err error + if p, err = glob.Compile(pattern, delimiters...); err != nil { + return false, err + } + globCacheLock.Lock() + if len(globCache) >= globCacheMaxSize { + // Delete a (semi-)random key to make room for the new one. + for k := range globCache { + delete(globCache, k) + break + } + } + globCache[id] = p + globCacheLock.Unlock() + } + + return p.Match(match), nil +} + +func builtinGlobQuoteMeta(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + pattern, err := builtins.StringOperand(operands[0].Value, 1) + if err != nil { + return err + } + + return iter(ast.StringTerm(glob.QuoteMeta(string(pattern)))) +} + +func init() { + RegisterBuiltinFunc(ast.GlobMatch.Name, builtinGlobMatch) + RegisterBuiltinFunc(ast.GlobQuoteMeta.Name, builtinGlobQuoteMeta) +} diff --git a/vendor/github.com/open-policy-agent/opa/topdown/graphql.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/graphql.go similarity index 95% rename from vendor/github.com/open-policy-agent/opa/topdown/graphql.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/graphql.go index 8fb1b58a76..0ad1cfdb5f 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/graphql.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/graphql.go @@ -16,8 +16,8 @@ import ( // Side-effecting import. Triggers GraphQL library's validation rule init() functions. _ "github.com/open-policy-agent/opa/internal/gqlparser/validator/rules" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) // Parses a GraphQL schema, and returns the GraphQL AST for the schema. @@ -174,7 +174,7 @@ func pruneIrrelevantGraphQLASTNodes(value ast.Value) ast.Value { case ast.Object: // Safe, because we knew the type before going to prune it. vo := pruneIrrelevantGraphQLASTNodes(v).(ast.Object) - if len(vo.Keys()) > 0 { + if vo.Len() > 0 { result = result.Append(ast.NewTerm(vo)) } default: @@ -209,7 +209,7 @@ func pruneIrrelevantGraphQLASTNodes(value ast.Value) ast.Value { case ast.Object: // Safe, because we knew the type before going to prune it. vo := pruneIrrelevantGraphQLASTNodes(v).(ast.Object) - if len(vo.Keys()) > 0 { + if vo.Len() > 0 { result.Insert(k, ast.NewTerm(vo)) } default: @@ -295,7 +295,7 @@ func builtinGraphQLParseAndVerify(_ BuiltinContext, operands []*ast.Term, iter f var err error unverified := ast.ArrayTerm( - ast.BooleanTerm(false), + ast.InternedBooleanTerm(false), ast.NewTerm(ast.NewObject()), ast.NewTerm(ast.NewObject()), ) @@ -353,7 +353,7 @@ func builtinGraphQLParseAndVerify(_ BuiltinContext, operands []*ast.Term, iter f // Construct return value. verified := ast.ArrayTerm( - ast.BooleanTerm(true), + ast.InternedBooleanTerm(true), ast.NewTerm(queryResult), ast.NewTerm(querySchema), ) @@ -421,10 +421,10 @@ func builtinGraphQLIsValid(_ BuiltinContext, operands []*ast.Term, iter func(*as queryDoc, err = objectToQueryDocument(x) default: // Error if wrong type. - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } if err != nil { - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } switch x := operands[1].Value.(type) { @@ -434,23 +434,23 @@ func builtinGraphQLIsValid(_ BuiltinContext, operands []*ast.Term, iter func(*as schemaDoc, err = objectToSchemaDocument(x) default: // Error if wrong type. - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } if err != nil { - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } // Validate the query against the schema, erroring if there's an issue. schema, err := convertSchema(schemaDoc) if err != nil { - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } if err := validateQuery(schema, queryDoc); err != nil { - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } // If we got this far, the GraphQL query passed validation. - return iter(ast.BooleanTerm(true)) + return iter(ast.InternedBooleanTerm(true)) } func builtinGraphQLSchemaIsValid(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -464,15 +464,15 @@ func builtinGraphQLSchemaIsValid(_ BuiltinContext, operands []*ast.Term, iter fu schemaDoc, err = objectToSchemaDocument(x) default: // Error if wrong type. - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } if err != nil { - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } // Validate the schema, this determines the result _, err = convertSchema(schemaDoc) - return iter(ast.BooleanTerm(err == nil)) + return iter(ast.InternedBooleanTerm(err == nil)) } func init() { diff --git a/vendor/github.com/open-policy-agent/opa/topdown/http.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/http.go similarity index 90% rename from vendor/github.com/open-policy-agent/opa/topdown/http.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/http.go index 9d01bc14b2..71c7c7d9eb 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/http.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/http.go @@ -22,12 +22,12 @@ import ( "strings" "time" - "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/internal/version" - "github.com/open-policy-agent/opa/topdown/builtins" - "github.com/open-policy-agent/opa/topdown/cache" - "github.com/open-policy-agent/opa/tracing" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" + "github.com/open-policy-agent/opa/v1/topdown/cache" + "github.com/open-policy-agent/opa/v1/tracing" + "github.com/open-policy-agent/opa/v1/util" ) type cachingMode string @@ -86,16 +86,33 @@ var cacheableHTTPStatusCodes = [...]int{ http.StatusNotImplemented, } +var ( + codeTerm = ast.StringTerm("code") + messageTerm = ast.StringTerm("message") + statusCodeTerm = ast.StringTerm("status_code") + errorTerm = ast.StringTerm("error") + methodTerm = ast.StringTerm("method") + urlTerm = ast.StringTerm("url") + + httpSendNetworkErrTerm = ast.StringTerm(HTTPSendNetworkErr) + httpSendInternalErrTerm = ast.StringTerm(HTTPSendInternalErr) +) + var ( allowedKeys = ast.NewSet() + keyCache = make(map[string]*ast.Term, len(allowedKeyNames)) cacheableCodes = ast.NewSet() - requiredKeys = ast.NewSet(ast.StringTerm("method"), ast.StringTerm("url")) - httpSendLatencyMetricKey = "rego_builtin_" + strings.ReplaceAll(ast.HTTPSend.Name, ".", "_") + requiredKeys = ast.NewSet(methodTerm, urlTerm) + httpSendLatencyMetricKey = "rego_builtin_http_send" httpSendInterQueryCacheHits = httpSendLatencyMetricKey + "_interquery_cache_hits" ) type httpSendKey string +// CustomizeRoundTripper allows customizing an existing http.Transport, +// to the returned value, which could be the same Transport or a new one. +type CustomizeRoundTripper func(*http.Transport) http.RoundTripper + const ( // httpSendBuiltinCacheKey is the key in the builtin context cache that // points to the http.send() specific cache resides at. @@ -147,27 +164,30 @@ func builtinHTTPSend(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.T } func generateRaiseErrorResult(err error) *ast.Term { - obj := ast.NewObject() - obj.Insert(ast.StringTerm("status_code"), ast.IntNumberTerm(0)) - - errObj := ast.NewObject() - + var errObj ast.Object switch err.(type) { case *url.Error: - errObj.Insert(ast.StringTerm("code"), ast.StringTerm(HTTPSendNetworkErr)) + errObj = ast.NewObject( + ast.Item(codeTerm, httpSendNetworkErrTerm), + ast.Item(messageTerm, ast.StringTerm(err.Error())), + ) default: - errObj.Insert(ast.StringTerm("code"), ast.StringTerm(HTTPSendInternalErr)) + errObj = ast.NewObject( + ast.Item(codeTerm, httpSendInternalErrTerm), + ast.Item(messageTerm, ast.StringTerm(err.Error())), + ) } - errObj.Insert(ast.StringTerm("message"), ast.StringTerm(err.Error())) - obj.Insert(ast.StringTerm("error"), ast.NewTerm(errObj)) - - return ast.NewTerm(obj) + return ast.NewTerm(ast.NewObject( + ast.Item(statusCodeTerm, ast.InternedIntNumberTerm(0)), + ast.Item(errorTerm, ast.NewTerm(errObj)), + )) } func getHTTPResponse(bctx BuiltinContext, req ast.Object) (*ast.Term, error) { bctx.Metrics.Timer(httpSendLatencyMetricKey).Start() + defer bctx.Metrics.Timer(httpSendLatencyMetricKey).Stop() key, err := getKeyFromRequest(req) if err != nil { @@ -199,8 +219,6 @@ func getHTTPResponse(bctx BuiltinContext, req ast.Object) (*ast.Term, error) { } } - bctx.Metrics.Timer(httpSendLatencyMetricKey).Stop() - return ast.NewTerm(resp), nil } @@ -209,21 +227,21 @@ func getHTTPResponse(bctx BuiltinContext, req ast.Object) (*ast.Term, error) { func getKeyFromRequest(req ast.Object) (ast.Object, error) { // deep copy so changes to key do not reflect in the request object key := req.Copy() - cacheIgnoredHeadersTerm := req.Get(ast.StringTerm("cache_ignored_headers")) + cacheIgnoredHeadersTerm := req.Get(keyCache["cache_ignored_headers"]) allHeadersTerm := req.Get(ast.StringTerm("headers")) // skip because no headers to delete if cacheIgnoredHeadersTerm == nil || allHeadersTerm == nil { // need to explicitly set cache_ignored_headers to null // equivalent requests might have different sets of exclusion lists - key.Insert(ast.StringTerm("cache_ignored_headers"), ast.NullTerm()) + key.Insert(ast.StringTerm("cache_ignored_headers"), ast.InternedNullTerm) return key, nil } var cacheIgnoredHeaders []string - var allHeaders map[string]interface{} err := ast.As(cacheIgnoredHeadersTerm.Value, &cacheIgnoredHeaders) if err != nil { return nil, err } + var allHeaders map[string]interface{} err = ast.As(allHeadersTerm.Value, &allHeaders) if err != nil { return nil, err @@ -235,14 +253,14 @@ func getKeyFromRequest(req ast.Object) (ast.Object, error) { if err != nil { return nil, err } - key.Insert(ast.StringTerm("headers"), ast.NewTerm(val)) + key.Insert(keyCache["headers"], ast.NewTerm(val)) // remove cache_ignored_headers key - key.Insert(ast.StringTerm("cache_ignored_headers"), ast.NullTerm()) + key.Insert(keyCache["cache_ignored_headers"], ast.InternedNullTerm) return key, nil } func init() { - createAllowedKeys() + createKeys() createCacheableHTTPStatusCodes() initDefaults() RegisterBuiltinFunc(ast.HTTPSend.Name, builtinHTTPSend) @@ -386,34 +404,25 @@ func verifyURLHost(bctx BuiltinContext, unverifiedURL string) error { } func createHTTPRequest(bctx BuiltinContext, obj ast.Object) (*http.Request, *http.Client, error) { - var url string - var method string - - // Additional CA certificates loading options. - var tlsCaCert []byte - var tlsCaCertEnvVar string - var tlsCaCertFile string - - // Client TLS certificate and key options. Each input source - // comes in a matched pair. - var tlsClientCert []byte - var tlsClientKey []byte - - var tlsClientCertEnvVar string - var tlsClientKeyEnvVar string - - var tlsClientCertFile string - var tlsClientKeyFile string - - var tlsServerName string - var body *bytes.Buffer - var rawBody *bytes.Buffer - var enableRedirect bool - var tlsUseSystemCerts *bool - var tlsConfig tls.Config - var customHeaders map[string]interface{} - var tlsInsecureSkipVerify bool - var timeout = defaultHTTPRequestTimeout + var ( + url, method string + // Additional CA certificates loading options. + tlsCaCert []byte + tlsCaCertEnvVar, tlsCaCertFile string + // Client TLS certificate and key options. Each input source + // comes in a matched pair. + tlsClientCert, tlsClientKey []byte + tlsClientCertEnvVar, tlsClientKeyEnvVar string + tlsClientCertFile, tlsClientKeyFile, tlsServerName string + + body, rawBody *bytes.Buffer + enableRedirect, tlsInsecureSkipVerify bool + tlsUseSystemCerts *bool + tlsConfig tls.Config + customHeaders map[string]interface{} + ) + + timeout := defaultHTTPRequestTimeout for _, val := range obj.Keys() { key, err := ast.JSON(val.Value) @@ -474,7 +483,7 @@ func createHTTPRequest(bctx BuiltinContext, obj ast.Object) (*http.Request, *htt } body = bytes.NewBuffer(bodyValBytes) case "raw_body": - rawBody = bytes.NewBuffer([]byte(strVal)) + rawBody = bytes.NewBufferString(strVal) case "tls_use_system_certs": tempTLSUseSystemCerts, err := strconv.ParseBool(obj.Get(val).String()) if err != nil { @@ -627,23 +636,29 @@ func createHTTPRequest(bctx BuiltinContext, obj ast.Object) (*http.Request, *htt tlsConfig.RootCAs = pool } + var transport *http.Transport if isTLS { if ok, parsedURL, tr := useSocket(url, &tlsConfig); ok { - client.Transport = tr + transport = tr url = parsedURL } else { - tr := http.DefaultTransport.(*http.Transport).Clone() - tr.TLSClientConfig = &tlsConfig - tr.DisableKeepAlives = true - client.Transport = tr + transport = http.DefaultTransport.(*http.Transport).Clone() + transport.TLSClientConfig = &tlsConfig + transport.DisableKeepAlives = true } } else { if ok, parsedURL, tr := useSocket(url, nil); ok { - client.Transport = tr + transport = tr url = parsedURL } } + if bctx.RoundTripper != nil { + client.Transport = bctx.RoundTripper(transport) + } else if transport != nil { + client.Transport = transport + } + // check if redirects are enabled if enableRedirect { client.CheckRedirect = func(req *http.Request, _ []*http.Request) error { @@ -715,7 +730,7 @@ func executeHTTPRequest(req *http.Request, client *http.Client, inputReqObj ast. var err error var retry int - retry, err = getNumberValFromReqObj(inputReqObj, ast.StringTerm("max_retry_attempts")) + retry, err = getNumberValFromReqObj(inputReqObj, keyCache["max_retry_attempts"]) if err != nil { return nil, err } @@ -737,9 +752,12 @@ func executeHTTPRequest(req *http.Request, client *http.Client, inputReqObj ast. return nil, err } + delay := util.DefaultBackoff(float64(minRetryDelay), float64(maxRetryDelay), i) + timer, timerCancel := util.TimerWithCancel(delay) select { - case <-time.After(util.DefaultBackoff(float64(minRetryDelay), float64(maxRetryDelay), i)): + case <-timer.C: case <-req.Context().Done(): + timerCancel() // explicitly cancel the timer. return nil, context.Canceled } } @@ -964,7 +982,7 @@ func (c *interQueryCache) checkHTTPSendInterQueryCache() (ast.Value, error) { // insertIntoHTTPSendInterQueryCache inserts given key and value in the inter-query cache func insertIntoHTTPSendInterQueryCache(bctx BuiltinContext, key ast.Value, resp *http.Response, respBody []byte, cacheParams *forceCacheParams) error { - if resp == nil || (!forceCaching(cacheParams) && !canStore(resp.Header)) || !cacheableCodes.Contains(ast.IntNumberTerm(resp.StatusCode)) { + if resp == nil || (!forceCaching(cacheParams) && !canStore(resp.Header)) || !cacheableCodes.Contains(ast.InternedIntNumberTerm(resp.StatusCode)) { return nil } @@ -997,15 +1015,18 @@ func insertIntoHTTPSendInterQueryCache(bctx BuiltinContext, key ast.Value, resp return nil } -func createAllowedKeys() { +func createKeys() { for _, element := range allowedKeyNames { - allowedKeys.Add(ast.StringTerm(element)) + term := ast.StringTerm(element) + + allowedKeys.Add(term) + keyCache[element] = term } } func createCacheableHTTPStatusCodes() { for _, element := range cacheableHTTPStatusCodes { - cacheableCodes.Add(ast.IntNumberTerm(element)) + cacheableCodes.Add(ast.InternedIntNumberTerm(element)) } } @@ -1033,7 +1054,7 @@ func parseTimeout(timeoutVal ast.Value) (time.Duration, error) { } return timeout, nil default: - return timeout, builtins.NewOperandErr(1, "'timeout' must be one of {string, number} but got %s", ast.TypeName(t)) + return timeout, builtins.NewOperandErr(1, "'timeout' must be one of {string, number} but got %s", ast.ValueName(t)) } } @@ -1066,7 +1087,7 @@ func getNumberValFromReqObj(req ast.Object, key *ast.Term) (int, error) { } func getCachingMode(req ast.Object) (cachingMode, error) { - key := ast.StringTerm("caching_mode") + key := keyCache["caching_mode"] var s ast.String var ok bool if v := req.Get(key); v != nil { @@ -1465,11 +1486,11 @@ func (c *interQueryCache) CheckCache() (ast.Value, error) { return resp, nil } - c.forceJSONDecode, err = getBoolValFromReqObj(c.key, ast.StringTerm("force_json_decode")) + c.forceJSONDecode, err = getBoolValFromReqObj(c.key, keyCache["force_json_decode"]) if err != nil { return nil, handleHTTPSendErr(c.bctx, err) } - c.forceYAMLDecode, err = getBoolValFromReqObj(c.key, ast.StringTerm("force_yaml_decode")) + c.forceYAMLDecode, err = getBoolValFromReqObj(c.key, keyCache["force_yaml_decode"]) if err != nil { return nil, handleHTTPSendErr(c.bctx, err) } @@ -1533,11 +1554,11 @@ func (c *intraQueryCache) CheckCache() (ast.Value, error) { // InsertIntoCache inserts the key set on this object into the cache with the given value func (c *intraQueryCache) InsertIntoCache(value *http.Response) (ast.Value, error) { - forceJSONDecode, err := getBoolValFromReqObj(c.key, ast.StringTerm("force_json_decode")) + forceJSONDecode, err := getBoolValFromReqObj(c.key, keyCache["force_json_decode"]) if err != nil { return nil, handleHTTPSendErr(c.bctx, err) } - forceYAMLDecode, err := getBoolValFromReqObj(c.key, ast.StringTerm("force_yaml_decode")) + forceYAMLDecode, err := getBoolValFromReqObj(c.key, keyCache["force_yaml_decode"]) if err != nil { return nil, handleHTTPSendErr(c.bctx, err) } @@ -1547,7 +1568,7 @@ func (c *intraQueryCache) InsertIntoCache(value *http.Response) (ast.Value, erro return nil, handleHTTPSendErr(c.bctx, err) } - if cacheableCodes.Contains(ast.IntNumberTerm(value.StatusCode)) { + if cacheableCodes.Contains(ast.InternedIntNumberTerm(value.StatusCode)) { insertIntoHTTPSendCache(c.bctx, c.key, result) } @@ -1568,12 +1589,12 @@ func (c *intraQueryCache) ExecuteHTTPRequest() (*http.Response, error) { } func useInterQueryCache(req ast.Object) (bool, *forceCacheParams, error) { - value, err := getBoolValFromReqObj(req, ast.StringTerm("cache")) + value, err := getBoolValFromReqObj(req, keyCache["cache"]) if err != nil { return false, nil, err } - valueForceCache, err := getBoolValFromReqObj(req, ast.StringTerm("force_cache")) + valueForceCache, err := getBoolValFromReqObj(req, keyCache["force_cache"]) if err != nil { return false, nil, err } @@ -1591,7 +1612,7 @@ type forceCacheParams struct { } func newForceCacheParams(req ast.Object) (*forceCacheParams, error) { - term := req.Get(ast.StringTerm("force_cache_duration_seconds")) + term := req.Get(keyCache["force_cache_duration_seconds"]) if term == nil { return nil, fmt.Errorf("'force_cache' set but 'force_cache_duration_seconds' parameter is missing") } @@ -1609,7 +1630,7 @@ func newForceCacheParams(req ast.Object) (*forceCacheParams, error) { func getRaiseErrorValue(req ast.Object) (bool, error) { result := ast.Boolean(true) var ok bool - if v := req.Get(ast.StringTerm("raise_error")); v != nil { + if v := req.Get(keyCache["raise_error"]); v != nil { if result, ok = v.Value.(ast.Boolean); !ok { return false, fmt.Errorf("invalid value for raise_error field") } diff --git a/vendor/github.com/open-policy-agent/opa/topdown/http_fixup.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/http_fixup.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/topdown/http_fixup.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/http_fixup.go diff --git a/vendor/github.com/open-policy-agent/opa/topdown/http_fixup_darwin.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/http_fixup_darwin.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/topdown/http_fixup_darwin.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/http_fixup_darwin.go diff --git a/vendor/github.com/open-policy-agent/opa/topdown/input.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/input.go similarity index 98% rename from vendor/github.com/open-policy-agent/opa/topdown/input.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/input.go index cb70aeb71e..dccf94d89a 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/input.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/input.go @@ -7,7 +7,7 @@ package topdown import ( "fmt" - "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/v1/ast" ) var errBadPath = fmt.Errorf("bad document path") diff --git a/vendor/github.com/open-policy-agent/opa/topdown/instrumentation.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/instrumentation.go similarity index 97% rename from vendor/github.com/open-policy-agent/opa/topdown/instrumentation.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/instrumentation.go index 6eacc338ef..93da1d0022 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/instrumentation.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/instrumentation.go @@ -4,7 +4,7 @@ package topdown -import "github.com/open-policy-agent/opa/metrics" +import "github.com/open-policy-agent/opa/v1/metrics" const ( evalOpPlug = "eval_op_plug" diff --git a/vendor/github.com/open-policy-agent/opa/topdown/json.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/json.go similarity index 98% rename from vendor/github.com/open-policy-agent/opa/topdown/json.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/json.go index 8a5d232836..5b7c414e40 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/json.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/json.go @@ -9,8 +9,8 @@ import ( "strconv" "strings" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" "github.com/open-policy-agent/opa/internal/edittree" ) @@ -189,7 +189,7 @@ func parsePath(path *ast.Term) (ast.Ref, error) { pathSegments = append(pathSegments, term) }) default: - return nil, builtins.NewOperandErr(2, "must be one of {set, array} containing string paths or array of path segments but got %v", ast.TypeName(p)) + return nil, builtins.NewOperandErr(2, "must be one of {set, array} containing string paths or array of path segments but got %v", ast.ValueName(p)) } return pathSegments, nil @@ -231,7 +231,7 @@ func pathsToObject(paths []ast.Ref) ast.Object { } if !done { - node.Insert(path[len(path)-1], ast.NullTerm()) + node.Insert(path[len(path)-1], ast.InternedNullTerm) } } diff --git a/vendor/github.com/open-policy-agent/opa/topdown/jsonschema.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/jsonschema.go similarity index 77% rename from vendor/github.com/open-policy-agent/opa/topdown/jsonschema.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/jsonschema.go index f44398f1e7..b1609fb044 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/jsonschema.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/jsonschema.go @@ -8,8 +8,8 @@ import ( "encoding/json" "errors" - "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/internal/gojsonschema" + "github.com/open-policy-agent/opa/v1/ast" ) // astValueToJSONSchemaLoader converts a value to JSON Loader. @@ -44,7 +44,7 @@ func astValueToJSONSchemaLoader(value ast.Value) (gojsonschema.JSONLoader, error } func newResultTerm(valid bool, data *ast.Term) *ast.Term { - return ast.ArrayTerm(ast.BooleanTerm(valid), data) + return ast.ArrayTerm(ast.InternedBooleanTerm(valid), data) } // builtinJSONSchemaVerify accepts 1 argument which can be string or object and checks if it is valid JSON schema. @@ -61,13 +61,23 @@ func builtinJSONSchemaVerify(_ BuiltinContext, operands []*ast.Term, iter func(* return iter(newResultTerm(false, ast.StringTerm("jsonschema: "+err.Error()))) } - return iter(newResultTerm(true, ast.NullTerm())) + return iter(newResultTerm(true, ast.InternedNullTerm)) } // builtinJSONMatchSchema accepts 2 arguments both can be string or object and verifies if the document matches the JSON schema. // Returns an array where first element is a boolean indicating a successful match, and the second is an array of errors that is empty on success and populated on failure. // In case of internal error returns empty array. -func builtinJSONMatchSchema(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { +func builtinJSONMatchSchema(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + var schema *gojsonschema.Schema + + if bctx.InterQueryBuiltinValueCache != nil { + if val, ok := bctx.InterQueryBuiltinValueCache.Get(operands[1].Value); ok { + if s, isSchema := val.(*gojsonschema.Schema); isSchema { + schema = s + } + } + } + // Take first argument and make JSON Loader from it. // This is a JSON document made from Rego JSON string or object. documentLoader, err := astValueToJSONSchemaLoader(operands[0].Value) @@ -75,15 +85,26 @@ func builtinJSONMatchSchema(_ BuiltinContext, operands []*ast.Term, iter func(*a return err } - // Take second argument and make JSON Loader from it. - // This is a JSON schema made from Rego JSON string or object. - schemaLoader, err := astValueToJSONSchemaLoader(operands[1].Value) - if err != nil { - return err + if schema == nil { + // Take second argument and make JSON Loader from it. + // This is a JSON schema made from Rego JSON string or object. + schemaLoader, err := astValueToJSONSchemaLoader(operands[1].Value) + if err != nil { + return err + } + + schema, err = gojsonschema.NewSchema(schemaLoader) + if err != nil { + return err + } + + if bctx.InterQueryBuiltinValueCache != nil { + bctx.InterQueryBuiltinValueCache.Insert(operands[1].Value, schema) + } } // Use schema to validate document. - result, err := gojsonschema.Validate(schemaLoader, documentLoader) + result, err := schema.Validate(documentLoader) if err != nil { return err } diff --git a/vendor/github.com/open-policy-agent/opa/topdown/net.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/net.go similarity index 93% rename from vendor/github.com/open-policy-agent/opa/topdown/net.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/net.go index 534520529a..17ed779844 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/net.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/net.go @@ -8,8 +8,8 @@ import ( "net" "strings" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) type lookupIPAddrCacheKey string diff --git a/vendor/github.com/open-policy-agent/opa/topdown/numbers.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/numbers.go similarity index 66% rename from vendor/github.com/open-policy-agent/opa/topdown/numbers.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/numbers.go index 27f3156b8a..855aef04b3 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/numbers.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/numbers.go @@ -8,15 +8,19 @@ import ( "fmt" "math/big" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) type randIntCachingKey string +var zero = big.NewInt(0) var one = big.NewInt(1) func builtinNumbersRange(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + if canGenerateCheapRange(operands) { + return generateCheapRange(operands, iter) + } x, err := builtins.BigIntOperand(operands[0].Value, 1) if err != nil { @@ -53,7 +57,7 @@ func builtinNumbersRangeStep(bctx BuiltinContext, operands []*ast.Term, iter fun return err } - if step.Cmp(big.NewInt(0)) <= 0 { + if step.Cmp(zero) <= 0 { return fmt.Errorf("numbers.range_step: step must be a positive number above zero") } @@ -65,6 +69,59 @@ func builtinNumbersRangeStep(bctx BuiltinContext, operands []*ast.Term, iter fun return iter(ast) } +func canGenerateCheapRange(operands []*ast.Term) bool { + x, err := builtins.IntOperand(operands[0].Value, 1) + if err != nil || !ast.HasInternedIntNumberTerm(x) { + return false + } + + y, err := builtins.IntOperand(operands[1].Value, 2) + if err != nil || !ast.HasInternedIntNumberTerm(y) { + return false + } + + return true +} + +func generateCheapRange(operands []*ast.Term, iter func(*ast.Term) error) error { + x, err := builtins.IntOperand(operands[0].Value, 1) + if err != nil { + return err + } + + y, err := builtins.IntOperand(operands[1].Value, 2) + if err != nil { + return err + } + + step := 1 + + if len(operands) > 2 { + stepOp, err := builtins.IntOperand(operands[2].Value, 3) + if err == nil { + step = stepOp + } + } + + if step <= 0 { + return fmt.Errorf("numbers.range_step: step must be a positive number above zero") + } + + terms := make([]*ast.Term, 0, y+1) + + if x <= y { + for i := x; i <= y; i += step { + terms = append(terms, ast.InternedIntNumberTerm(i)) + } + } else { + for i := x; i >= y; i -= step { + terms = append(terms, ast.InternedIntNumberTerm(i)) + } + } + + return iter(ast.ArrayTerm(terms...)) +} + func generateRange(bctx BuiltinContext, x *big.Int, y *big.Int, step *big.Int, funcName string) (*ast.Term, error) { cmp := x.Cmp(y) @@ -109,7 +166,7 @@ func builtinRandIntn(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.T } if n == 0 { - return iter(ast.IntNumberTerm(0)) + return iter(ast.InternedIntNumberTerm(0)) } if n < 0 { @@ -126,7 +183,7 @@ func builtinRandIntn(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.T if err != nil { return err } - result := ast.IntNumberTerm(r.Intn(n)) + result := ast.InternedIntNumberTerm(r.Intn(n)) bctx.Cache.Put(key, result) return iter(result) diff --git a/vendor/github.com/open-policy-agent/opa/topdown/object.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/object.go similarity index 91% rename from vendor/github.com/open-policy-agent/opa/topdown/object.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/object.go index ba5d77ff37..4db8fa8272 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/object.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/object.go @@ -5,9 +5,9 @@ package topdown import ( - "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/internal/ref" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) func builtinObjectUnion(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -50,9 +50,6 @@ func builtinObjectUnionN(_ BuiltinContext, operands []*ast.Term, iter func(*ast. return builtins.NewOperandElementErr(1, arr, arr.Elem(i).Value, "object") } mergewithOverwriteInPlace(result, o, frozenKeys) - if err != nil { - return err - } } return iter(ast.NewTerm(result)) @@ -95,7 +92,7 @@ func builtinObjectFilter(_ BuiltinContext, operands []*ast.Term, iter func(*ast. filterObj := ast.NewObject() keys.Foreach(func(key *ast.Term) { - filterObj.Insert(key, ast.NullTerm()) + filterObj.Insert(key, ast.InternedNullTerm) }) // Actually do the filtering @@ -144,37 +141,24 @@ func builtinObjectKeys(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Te return err } - keys := ast.SetTerm(object.Keys()...) - - return iter(keys) + return iter(ast.SetTerm(object.Keys()...)) } // getObjectKeysParam returns a set of key values // from a supplied ast array, object, set value func getObjectKeysParam(arrayOrSet ast.Value) (ast.Set, error) { - keys := ast.NewSet() - switch v := arrayOrSet.(type) { case *ast.Array: - _ = v.Iter(func(f *ast.Term) error { - keys.Add(f) - return nil - }) + keys := ast.NewSet() + v.Foreach(keys.Add) + return keys, nil case ast.Set: - _ = v.Iter(func(f *ast.Term) error { - keys.Add(f) - return nil - }) + return ast.NewSet(v.Slice()...), nil case ast.Object: - _ = v.Iter(func(k *ast.Term, _ *ast.Term) error { - keys.Add(k) - return nil - }) - default: - return nil, builtins.NewOperandTypeErr(2, arrayOrSet, "object", "set", "array") + return ast.NewSet(v.Keys()...), nil } - return keys, nil + return nil, builtins.NewOperandTypeErr(2, arrayOrSet, "object", "set", "array") } func mergeWithOverwrite(objA, objB ast.Object) ast.Object { diff --git a/vendor/github.com/open-policy-agent/opa/topdown/parse.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/parse.go similarity index 91% rename from vendor/github.com/open-policy-agent/opa/topdown/parse.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/parse.go index c46222b413..464e0141a2 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/parse.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/parse.go @@ -9,8 +9,8 @@ import ( "encoding/json" "fmt" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) func builtinRegoParseModule(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -25,6 +25,7 @@ func builtinRegoParseModule(_ BuiltinContext, operands []*ast.Term, iter func(*a return err } + // FIXME: Use configured rego-version? module, err := ast.ParseModule(string(filename), string(input)) if err != nil { return err diff --git a/vendor/github.com/open-policy-agent/opa/topdown/parse_bytes.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/parse_bytes.go similarity index 76% rename from vendor/github.com/open-policy-agent/opa/topdown/parse_bytes.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/parse_bytes.go index 0cd4bc193a..dcc8e21997 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/parse_bytes.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/parse_bytes.go @@ -10,8 +10,8 @@ import ( "strings" "unicode" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) const ( @@ -121,21 +121,35 @@ func extractNumAndUnit(s string) (string, string) { } firstNonNumIdx := -1 - for idx, r := range s { - if !isNum(r) { + for idx := 0; idx < len(s); idx++ { + r := rune(s[idx]) + // Identify the first non-numeric character, marking the boundary between the number and the unit. + if !isNum(r) && r != 'e' && r != 'E' && r != '+' && r != '-' { firstNonNumIdx = idx break } + if r == 'e' || r == 'E' { + // Check if the next character is a valid digit or +/- for scientific notation + if idx == len(s)-1 || (!unicode.IsDigit(rune(s[idx+1])) && rune(s[idx+1]) != '+' && rune(s[idx+1]) != '-') { + firstNonNumIdx = idx + break + } + // Skip the next character if it is '+' or '-' + if idx+1 < len(s) && (s[idx+1] == '+' || s[idx+1] == '-') { + idx++ + } + } } - if firstNonNumIdx == -1 { // only digits and '.' + if firstNonNumIdx == -1 { // only digits, '.', or valid scientific notation return s, "" } if firstNonNumIdx == 0 { // only units (starts with non-digit) return "", s } - return s[0:firstNonNumIdx], s[firstNonNumIdx:] + // Return the number and the rest as the unit + return s[:firstNonNumIdx], s[firstNonNumIdx:] } func init() { diff --git a/vendor/github.com/open-policy-agent/opa/topdown/parse_units.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/parse_units.go similarity index 96% rename from vendor/github.com/open-policy-agent/opa/topdown/parse_units.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/parse_units.go index daf240214c..47e459510a 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/parse_units.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/parse_units.go @@ -10,8 +10,8 @@ import ( "math/big" "strings" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) // Binary Si unit constants are borrowed from topdown/parse_bytes diff --git a/vendor/github.com/open-policy-agent/opa/topdown/print.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/print.go similarity index 88% rename from vendor/github.com/open-policy-agent/opa/topdown/print.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/print.go index 765b344b3a..f852f3e320 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/print.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/print.go @@ -9,9 +9,9 @@ import ( "io" "strings" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" - "github.com/open-policy-agent/opa/topdown/print" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" + "github.com/open-policy-agent/opa/v1/topdown/print" ) func NewPrintHook(w io.Writer) print.Hook { @@ -62,7 +62,7 @@ func builtinPrintCrossProductOperands(bctx BuiltinContext, buf []string, operand xs, ok := operands.Elem(i).Value.(ast.Set) if !ok { - return Halt{Err: internalErr(bctx.Location, fmt.Sprintf("illegal argument type: %v", ast.TypeName(operands.Elem(i).Value)))} + return Halt{Err: internalErr(bctx.Location, fmt.Sprintf("illegal argument type: %v", ast.ValueName(operands.Elem(i).Value)))} } if xs.Len() == 0 { diff --git a/vendor/github.com/open-policy-agent/opa/topdown/print/print.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/print/print.go similarity index 92% rename from vendor/github.com/open-policy-agent/opa/topdown/print/print.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/print/print.go index 0fb6abdca8..ce684ae945 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/print/print.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/print/print.go @@ -3,7 +3,7 @@ package print import ( "context" - "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/v1/ast" ) // Context provides the Hook implementation context about the print() call. diff --git a/vendor/github.com/open-policy-agent/opa/topdown/providers.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/providers.go similarity index 97% rename from vendor/github.com/open-policy-agent/opa/topdown/providers.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/providers.go index 77db917982..dd84026e4b 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/providers.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/providers.go @@ -9,9 +9,9 @@ import ( "net/url" "time" - "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/internal/providers/aws" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) var awsRequiredConfigKeyNames = ast.NewSet( @@ -119,9 +119,6 @@ func builtinAWSSigV4SignReq(_ BuiltinContext, operands []*ast.Term, iter func(*a } signingTimestamp = time.Unix(0, ts) - if err != nil { - return err - } // Make sure our required keys exist! // This check is stricter than required, but better to break here than downstream. diff --git a/vendor/github.com/open-policy-agent/opa/topdown/query.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/query.go similarity index 68% rename from vendor/github.com/open-policy-agent/opa/topdown/query.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/query.go index bbb4ba58f3..a008517cca 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/query.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/query.go @@ -7,15 +7,15 @@ import ( "sort" "time" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/metrics" - "github.com/open-policy-agent/opa/resolver" - "github.com/open-policy-agent/opa/storage" - "github.com/open-policy-agent/opa/topdown/builtins" - "github.com/open-policy-agent/opa/topdown/cache" - "github.com/open-policy-agent/opa/topdown/copypropagation" - "github.com/open-policy-agent/opa/topdown/print" - "github.com/open-policy-agent/opa/tracing" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/metrics" + "github.com/open-policy-agent/opa/v1/resolver" + "github.com/open-policy-agent/opa/v1/storage" + "github.com/open-policy-agent/opa/v1/topdown/builtins" + "github.com/open-policy-agent/opa/v1/topdown/cache" + "github.com/open-policy-agent/opa/v1/topdown/copypropagation" + "github.com/open-policy-agent/opa/v1/topdown/print" + "github.com/open-policy-agent/opa/v1/tracing" ) // QueryResultSet represents a collection of results returned by a query. @@ -27,38 +27,41 @@ type QueryResult map[ast.Var]*ast.Term // Query provides a configurable interface for performing query evaluation. type Query struct { - seed io.Reader - time time.Time - cancel Cancel - query ast.Body - queryCompiler ast.QueryCompiler - compiler *ast.Compiler - store storage.Store - txn storage.Transaction - input *ast.Term - external *resolverTrie - tracers []QueryTracer - plugTraceVars bool - unknowns []*ast.Term - partialNamespace string - skipSaveNamespace bool - metrics metrics.Metrics - instr *Instrumentation - disableInlining []ast.Ref - shallowInlining bool - genvarprefix string - runtime *ast.Term - builtins map[string]*Builtin - indexing bool - earlyExit bool - interQueryBuiltinCache cache.InterQueryCache - ndBuiltinCache builtins.NDBCache - strictBuiltinErrors bool - builtinErrorList *[]Error - strictObjects bool - printHook print.Hook - tracingOpts tracing.Options - virtualCache VirtualCache + seed io.Reader + time time.Time + cancel Cancel + query ast.Body + queryCompiler ast.QueryCompiler + compiler *ast.Compiler + store storage.Store + txn storage.Transaction + input *ast.Term + external *resolverTrie + tracers []QueryTracer + plugTraceVars bool + unknowns []*ast.Term + partialNamespace string + skipSaveNamespace bool + metrics metrics.Metrics + instr *Instrumentation + disableInlining []ast.Ref + shallowInlining bool + nondeterministicBuiltins bool + genvarprefix string + runtime *ast.Term + builtins map[string]*Builtin + indexing bool + earlyExit bool + interQueryBuiltinCache cache.InterQueryCache + interQueryBuiltinValueCache cache.InterQueryValueCache + ndBuiltinCache builtins.NDBCache + strictBuiltinErrors bool + builtinErrorList *[]Error + strictObjects bool + roundTripper CustomizeRoundTripper + printHook print.Hook + tracingOpts tracing.Options + virtualCache VirtualCache } // Builtin represents a built-in function that queries can call. @@ -246,6 +249,12 @@ func (q *Query) WithInterQueryBuiltinCache(c cache.InterQueryCache) *Query { return q } +// WithInterQueryBuiltinValueCache sets the inter-query value cache that built-in functions can utilize. +func (q *Query) WithInterQueryBuiltinValueCache(c cache.InterQueryValueCache) *Query { + q.interQueryBuiltinValueCache = c + return q +} + // WithNDBuiltinCache sets the non-deterministic builtin cache. func (q *Query) WithNDBuiltinCache(c builtins.NDBCache) *Query { q.ndBuiltinCache = c @@ -272,6 +281,12 @@ func (q *Query) WithResolver(ref ast.Ref, r resolver.Resolver) *Query { return q } +// WithHTTPRoundTripper configures a custom HTTP transport for built-in functions that make HTTP requests. +func (q *Query) WithHTTPRoundTripper(t CustomizeRoundTripper) *Query { + q.roundTripper = t + return q +} + func (q *Query) WithPrintHook(h print.Hook) *Query { q.printHook = h return q @@ -299,6 +314,14 @@ func (q *Query) WithVirtualCache(vc VirtualCache) *Query { return q } +// WithNondeterministicBuiltins causes non-deterministic builtins to be evalued +// during partial evaluation. This is needed to pull in external data, or validate +// a JWT, during PE, so that the result informs what queries are returned. +func (q *Query) WithNondeterministicBuiltins(yes bool) *Query { + q.nondeterministicBuiltins = yes + return q +} + // PartialRun executes partial evaluation on the query with respect to unknown // values. Partial evaluation attempts to evaluate as much of the query as // possible without requiring values for the unknowns set on the query. The @@ -331,41 +354,43 @@ func (q *Query) PartialRun(ctx context.Context) (partials []ast.Body, support [] } e := &eval{ - ctx: ctx, - metrics: q.metrics, - seed: q.seed, - time: ast.NumberTerm(int64ToJSONNumber(q.time.UnixNano())), - cancel: q.cancel, - query: q.query, - queryCompiler: q.queryCompiler, - queryIDFact: f, - queryID: f.Next(), - bindings: b, - compiler: q.compiler, - store: q.store, - baseCache: newBaseCache(), - targetStack: newRefStack(), - txn: q.txn, - input: q.input, - external: q.external, - tracers: q.tracers, - traceEnabled: len(q.tracers) > 0, - plugTraceVars: q.plugTraceVars, - instr: q.instr, - builtins: q.builtins, - builtinCache: builtins.Cache{}, - functionMocks: newFunctionMocksStack(), - interQueryBuiltinCache: q.interQueryBuiltinCache, - ndBuiltinCache: q.ndBuiltinCache, - virtualCache: vc, - comprehensionCache: newComprehensionCache(), - saveSet: newSaveSet(q.unknowns, b, q.instr), - saveStack: newSaveStack(), - saveSupport: newSaveSupport(), - saveNamespace: ast.StringTerm(q.partialNamespace), - skipSaveNamespace: q.skipSaveNamespace, + ctx: ctx, + metrics: q.metrics, + seed: q.seed, + time: ast.NumberTerm(int64ToJSONNumber(q.time.UnixNano())), + cancel: q.cancel, + query: q.query, + queryCompiler: q.queryCompiler, + queryIDFact: f, + queryID: f.Next(), + bindings: b, + compiler: q.compiler, + store: q.store, + baseCache: newBaseCache(), + targetStack: newRefStack(), + txn: q.txn, + input: q.input, + external: q.external, + tracers: q.tracers, + traceEnabled: len(q.tracers) > 0, + plugTraceVars: q.plugTraceVars, + instr: q.instr, + builtins: q.builtins, + builtinCache: builtins.Cache{}, + functionMocks: newFunctionMocksStack(), + interQueryBuiltinCache: q.interQueryBuiltinCache, + interQueryBuiltinValueCache: q.interQueryBuiltinValueCache, + ndBuiltinCache: q.ndBuiltinCache, + virtualCache: vc, + comprehensionCache: newComprehensionCache(), + saveSet: newSaveSet(q.unknowns, b, q.instr), + saveStack: newSaveStack(), + saveSupport: newSaveSupport(), + saveNamespace: ast.StringTerm(q.partialNamespace), + skipSaveNamespace: q.skipSaveNamespace, inliningControl: &inliningControl{ - shallow: q.shallowInlining, + shallow: q.shallowInlining, + nondeterministicBuiltins: q.nondeterministicBuiltins, }, genvarprefix: q.genvarprefix, runtime: q.runtime, @@ -466,7 +491,11 @@ func (q *Query) PartialRun(ctx context.Context) (partials []ast.Body, support [] } } - for i := range support { + for i, m := range support { + if regoVersion := q.compiler.DefaultRegoVersion(); regoVersion != ast.RegoUndefined { + ast.SetModuleRegoVersion(m, q.compiler.DefaultRegoVersion()) + } + sort.Slice(support[i].Rules, func(j, k int) bool { return support[i].Rules[j].Compare(support[i].Rules[k]) < 0 }) @@ -516,42 +545,44 @@ func (q *Query) Iter(ctx context.Context, iter func(QueryResult) error) error { } e := &eval{ - ctx: ctx, - metrics: q.metrics, - seed: q.seed, - time: ast.NumberTerm(int64ToJSONNumber(q.time.UnixNano())), - cancel: q.cancel, - query: q.query, - queryCompiler: q.queryCompiler, - queryIDFact: f, - queryID: f.Next(), - bindings: newBindings(0, q.instr), - compiler: q.compiler, - store: q.store, - baseCache: newBaseCache(), - targetStack: newRefStack(), - txn: q.txn, - input: q.input, - external: q.external, - tracers: q.tracers, - traceEnabled: len(q.tracers) > 0, - plugTraceVars: q.plugTraceVars, - instr: q.instr, - builtins: q.builtins, - builtinCache: builtins.Cache{}, - functionMocks: newFunctionMocksStack(), - interQueryBuiltinCache: q.interQueryBuiltinCache, - ndBuiltinCache: q.ndBuiltinCache, - virtualCache: vc, - comprehensionCache: newComprehensionCache(), - genvarprefix: q.genvarprefix, - runtime: q.runtime, - indexing: q.indexing, - earlyExit: q.earlyExit, - builtinErrors: &builtinErrors{}, - printHook: q.printHook, - tracingOpts: q.tracingOpts, - strictObjects: q.strictObjects, + ctx: ctx, + metrics: q.metrics, + seed: q.seed, + time: ast.NumberTerm(int64ToJSONNumber(q.time.UnixNano())), + cancel: q.cancel, + query: q.query, + queryCompiler: q.queryCompiler, + queryIDFact: f, + queryID: f.Next(), + bindings: newBindings(0, q.instr), + compiler: q.compiler, + store: q.store, + baseCache: newBaseCache(), + targetStack: newRefStack(), + txn: q.txn, + input: q.input, + external: q.external, + tracers: q.tracers, + traceEnabled: len(q.tracers) > 0, + plugTraceVars: q.plugTraceVars, + instr: q.instr, + builtins: q.builtins, + builtinCache: builtins.Cache{}, + functionMocks: newFunctionMocksStack(), + interQueryBuiltinCache: q.interQueryBuiltinCache, + interQueryBuiltinValueCache: q.interQueryBuiltinValueCache, + ndBuiltinCache: q.ndBuiltinCache, + virtualCache: vc, + comprehensionCache: newComprehensionCache(), + genvarprefix: q.genvarprefix, + runtime: q.runtime, + indexing: q.indexing, + earlyExit: q.earlyExit, + builtinErrors: &builtinErrors{}, + printHook: q.printHook, + tracingOpts: q.tracingOpts, + strictObjects: q.strictObjects, + roundTripper: q.roundTripper, } e.caller = e q.metrics.Timer(metrics.RegoQueryEval).Start() diff --git a/vendor/github.com/open-policy-agent/opa/topdown/reachable.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/reachable.go similarity index 97% rename from vendor/github.com/open-policy-agent/opa/topdown/reachable.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/reachable.go index 8d61018e76..1c31019db9 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/reachable.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/reachable.go @@ -5,8 +5,8 @@ package topdown import ( - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) // Helper: sets of vertices can be represented as Arrays or Sets. diff --git a/vendor/github.com/open-policy-agent/opa/topdown/regex.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/regex.go similarity index 74% rename from vendor/github.com/open-policy-agent/opa/topdown/regex.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/regex.go index 877f19e233..6c1f6794cc 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/regex.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/regex.go @@ -11,11 +11,12 @@ import ( gintersect "github.com/yashtewari/glob-intersection" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) const regexCacheMaxSize = 100 +const regexInterQueryValueCacheHits = "rego_builtin_regex_interquery_value_cache_hits" var regexpCacheLock = sync.Mutex{} var regexpCache map[string]*regexp.Regexp @@ -24,18 +25,18 @@ func builtinRegexIsValid(_ BuiltinContext, operands []*ast.Term, iter func(*ast. s, err := builtins.StringOperand(operands[0].Value, 1) if err != nil { - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } _, err = regexp.Compile(string(s)) if err != nil { - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } - return iter(ast.BooleanTerm(true)) + return iter(ast.InternedBooleanTerm(true)) } -func builtinRegexMatch(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { +func builtinRegexMatch(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { s1, err := builtins.StringOperand(operands[0].Value, 1) if err != nil { return err @@ -44,11 +45,11 @@ func builtinRegexMatch(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Te if err != nil { return err } - re, err := getRegexp(string(s1)) + re, err := getRegexp(bctx, string(s1)) if err != nil { return err } - return iter(ast.BooleanTerm(re.MatchString(string(s2)))) + return iter(ast.InternedBooleanTerm(re.MatchString(string(s2)))) } func builtinRegexMatchTemplate(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -78,10 +79,10 @@ func builtinRegexMatchTemplate(_ BuiltinContext, operands []*ast.Term, iter func if err != nil { return err } - return iter(ast.BooleanTerm(re.MatchString(string(match)))) + return iter(ast.InternedBooleanTerm(re.MatchString(string(match)))) } -func builtinRegexSplit(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { +func builtinRegexSplit(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { s1, err := builtins.StringOperand(operands[0].Value, 1) if err != nil { return err @@ -90,7 +91,7 @@ func builtinRegexSplit(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Te if err != nil { return err } - re, err := getRegexp(string(s1)) + re, err := getRegexp(bctx, string(s1)) if err != nil { return err } @@ -103,7 +104,30 @@ func builtinRegexSplit(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Te return iter(ast.NewTerm(ast.NewArray(arr...))) } -func getRegexp(pat string) (*regexp.Regexp, error) { +func getRegexp(bctx BuiltinContext, pat string) (*regexp.Regexp, error) { + if bctx.InterQueryBuiltinValueCache != nil { + // TODO: Use named cache + val, ok := bctx.InterQueryBuiltinValueCache.Get(ast.String(pat)) + if ok { + res, valid := val.(*regexp.Regexp) + if !valid { + // The cache key may exist for a different value type (eg. glob). + // In this case, we calculate the regex and return the result w/o updating the cache. + return regexp.Compile(pat) + } + + bctx.Metrics.Counter(regexInterQueryValueCacheHits).Incr() + return res, nil + } + + re, err := regexp.Compile(pat) + if err != nil { + return nil, err + } + bctx.InterQueryBuiltinValueCache.Insert(ast.String(pat), re) + return re, nil + } + regexpCacheLock.Lock() defer regexpCacheLock.Unlock() re, ok := regexpCache[pat] @@ -153,10 +177,10 @@ func builtinGlobsMatch(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Te if err != nil { return err } - return iter(ast.BooleanTerm(ne)) + return iter(ast.InternedBooleanTerm(ne)) } -func builtinRegexFind(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { +func builtinRegexFind(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { s1, err := builtins.StringOperand(operands[0].Value, 1) if err != nil { return err @@ -169,7 +193,7 @@ func builtinRegexFind(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Ter if err != nil { return err } - re, err := getRegexp(string(s1)) + re, err := getRegexp(bctx, string(s1)) if err != nil { return err } @@ -182,7 +206,7 @@ func builtinRegexFind(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Ter return iter(ast.NewTerm(ast.NewArray(arr...))) } -func builtinRegexFindAllStringSubmatch(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { +func builtinRegexFindAllStringSubmatch(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { s1, err := builtins.StringOperand(operands[0].Value, 1) if err != nil { return err @@ -196,7 +220,7 @@ func builtinRegexFindAllStringSubmatch(_ BuiltinContext, operands []*ast.Term, i return err } - re, err := getRegexp(string(s1)) + re, err := getRegexp(bctx, string(s1)) if err != nil { return err } @@ -214,7 +238,7 @@ func builtinRegexFindAllStringSubmatch(_ BuiltinContext, operands []*ast.Term, i return iter(ast.NewTerm(ast.NewArray(outer...))) } -func builtinRegexReplace(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { +func builtinRegexReplace(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { base, err := builtins.StringOperand(operands[0].Value, 1) if err != nil { return err @@ -230,7 +254,7 @@ func builtinRegexReplace(_ BuiltinContext, operands []*ast.Term, iter func(*ast. return err } - re, err := getRegexp(string(pattern)) + re, err := getRegexp(bctx, string(pattern)) if err != nil { return err } diff --git a/vendor/github.com/open-policy-agent/opa/topdown/regex_template.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/regex_template.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/topdown/regex_template.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/regex_template.go diff --git a/vendor/github.com/open-policy-agent/opa/topdown/resolver.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/resolver.go similarity index 94% rename from vendor/github.com/open-policy-agent/opa/topdown/resolver.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/resolver.go index 5ed6c1e443..170e6e6402 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/resolver.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/resolver.go @@ -5,9 +5,9 @@ package topdown import ( - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/metrics" - "github.com/open-policy-agent/opa/resolver" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/metrics" + "github.com/open-policy-agent/opa/v1/resolver" ) type resolverTrie struct { diff --git a/vendor/github.com/open-policy-agent/opa/topdown/runtime.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/runtime.go similarity index 88% rename from vendor/github.com/open-policy-agent/opa/topdown/runtime.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/runtime.go index 7d512f7c00..9323225832 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/runtime.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/runtime.go @@ -7,17 +7,21 @@ package topdown import ( "fmt" - "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/v1/ast" ) +var configStringTerm = ast.StringTerm("config") + +var nothingResolver ast.Resolver = illegalResolver{} + func builtinOPARuntime(bctx BuiltinContext, _ []*ast.Term, iter func(*ast.Term) error) error { if bctx.Runtime == nil { - return iter(ast.ObjectTerm()) + return iter(ast.InternedEmptyObject) } - if bctx.Runtime.Get(ast.StringTerm("config")) != nil { - iface, err := ast.ValueToInterface(bctx.Runtime.Value, illegalResolver{}) + if bctx.Runtime.Get(configStringTerm) != nil { + iface, err := ast.ValueToInterface(bctx.Runtime.Value, nothingResolver) if err != nil { return err } diff --git a/vendor/github.com/open-policy-agent/opa/topdown/save.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/save.go similarity index 96% rename from vendor/github.com/open-policy-agent/opa/topdown/save.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/save.go index 0468692cc6..439f554a34 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/save.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/save.go @@ -5,7 +5,7 @@ import ( "fmt" "strings" - "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/v1/ast" ) // saveSet contains a stack of terms that are considered 'unknown' during @@ -365,7 +365,13 @@ func saveRequired(c *ast.Compiler, ic *inliningControl, icIgnoreInternal bool, s } switch node := node.(type) { case *ast.Expr: - found = len(node.With) > 0 || ignoreExprDuringPartial(node) + found = len(node.With) > 0 + if found { + return found + } + if !ic.nondeterministicBuiltins { // skip evaluating non-det builtins for PE + found = ignoreExprDuringPartial(node) + } case *ast.Term: switch v := node.Value.(type) { case ast.Var: @@ -422,8 +428,9 @@ func ignoreDuringPartial(bi *ast.Builtin) bool { } type inliningControl struct { - shallow bool - disable []disableInliningFrame + shallow bool + disable []disableInliningFrame + nondeterministicBuiltins bool // evaluate non-det builtins during PE (if args are known) } type disableInliningFrame struct { diff --git a/vendor/github.com/open-policy-agent/opa/topdown/semver.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/semver.go similarity index 85% rename from vendor/github.com/open-policy-agent/opa/topdown/semver.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/semver.go index 7bb7b9c183..0e7daaeae6 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/semver.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/semver.go @@ -7,9 +7,9 @@ package topdown import ( "fmt" - "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/internal/semver" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) func builtinSemVerCompare(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -34,13 +34,13 @@ func builtinSemVerCompare(_ BuiltinContext, operands []*ast.Term, iter func(*ast result := versionA.Compare(*versionB) - return iter(ast.IntNumberTerm(result)) + return iter(ast.InternedIntNumberTerm(result)) } func builtinSemVerIsValid(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { versionString, err := builtins.StringOperand(operands[0].Value, 1) if err != nil { - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } result := true @@ -50,7 +50,7 @@ func builtinSemVerIsValid(_ BuiltinContext, operands []*ast.Term, iter func(*ast result = false } - return iter(ast.BooleanTerm(result)) + return iter(ast.InternedBooleanTerm(result)) } func init() { diff --git a/vendor/github.com/open-policy-agent/opa/topdown/sets.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/sets.go similarity index 95% rename from vendor/github.com/open-policy-agent/opa/topdown/sets.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/sets.go index a973404f3f..b7566b8e6e 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/sets.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/sets.go @@ -5,8 +5,8 @@ package topdown import ( - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) // Deprecated in v0.4.2 in favour of minus/infix "-" operation. diff --git a/vendor/github.com/open-policy-agent/opa/topdown/strings.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/strings.go similarity index 74% rename from vendor/github.com/open-policy-agent/opa/topdown/strings.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/strings.go index d9e4a55e58..929a18ea0a 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/strings.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/strings.go @@ -8,12 +8,16 @@ import ( "fmt" "math/big" "sort" + "strconv" "strings" + "unicode" + "unicode/utf8" "github.com/tchap/go-patricia/v2/patricia" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" + "github.com/open-policy-agent/opa/v1/util" ) func builtinAnyPrefixMatch(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -47,7 +51,7 @@ func builtinAnyPrefixMatch(_ BuiltinContext, operands []*ast.Term, iter func(*as return builtins.NewOperandTypeErr(2, b, "string", "set", "array") } - return iter(ast.BooleanTerm(anyStartsWithAny(strs, prefixes))) + return iter(ast.InternedBooleanTerm(anyStartsWithAny(strs, prefixes))) } func builtinAnySuffixMatch(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -87,7 +91,7 @@ func builtinAnySuffixMatch(_ BuiltinContext, operands []*ast.Term, iter func(*as return builtins.NewOperandTypeErr(2, b, "string", "set", "array") } - return iter(ast.BooleanTerm(anyStartsWithAny(strsReversed, suffixesReversed))) + return iter(ast.InternedBooleanTerm(anyStartsWithAny(strsReversed, suffixesReversed))) } func anyStartsWithAny(strs []string, prefixes []string) bool { @@ -151,33 +155,48 @@ func builtinConcat(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) return err } - strs := []string{} + var strs []string switch b := operands[1].Value.(type) { case *ast.Array: - err := b.Iter(func(x *ast.Term) error { - s, ok := x.Value.(ast.String) + var l int + for i := 0; i < b.Len(); i++ { + s, ok := b.Elem(i).Value.(ast.String) if !ok { - return builtins.NewOperandElementErr(2, operands[1].Value, x.Value, "string") + return builtins.NewOperandElementErr(2, operands[1].Value, b.Elem(i).Value, "string") } - strs = append(strs, string(s)) - return nil - }) - if err != nil { - return err + l += len(string(s)) + } + + if b.Len() == 1 { + return iter(b.Elem(0)) } + + strs = make([]string, 0, l) + for i := 0; i < b.Len(); i++ { + strs = append(strs, string(b.Elem(i).Value.(ast.String))) + } + case ast.Set: - err := b.Iter(func(x *ast.Term) error { - s, ok := x.Value.(ast.String) + var l int + terms := b.Slice() + for i := 0; i < len(terms); i++ { + s, ok := terms[i].Value.(ast.String) if !ok { - return builtins.NewOperandElementErr(2, operands[1].Value, x.Value, "string") + return builtins.NewOperandElementErr(2, operands[1].Value, terms[i].Value, "string") } - strs = append(strs, string(s)) - return nil - }) - if err != nil { - return err + l += len(string(s)) } + + if b.Len() == 1 { + return iter(b.Slice()[0]) + } + + strs = make([]string, 0, l) + for i := 0; i < b.Len(); i++ { + strs = append(strs, string(terms[i].Value.(ast.String))) + } + default: return builtins.NewOperandTypeErr(2, operands[1].Value, "set", "array") } @@ -211,6 +230,10 @@ func builtinIndexOf(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) return fmt.Errorf("empty search character") } + if isASCII(string(base)) && isASCII(string(search)) { + return iter(ast.InternedIntNumberTerm(strings.Index(string(base), string(search)))) + } + baseRunes := []rune(string(base)) searchRunes := []rune(string(search)) searchLen := len(searchRunes) @@ -218,14 +241,14 @@ func builtinIndexOf(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) for i, r := range baseRunes { if len(baseRunes) >= i+searchLen { if r == searchRunes[0] && runesEqual(baseRunes[i:i+searchLen], searchRunes) { - return iter(ast.IntNumberTerm(i)) + return iter(ast.InternedIntNumberTerm(i)) } } else { break } } - return iter(ast.IntNumberTerm(-1)) + return iter(ast.InternedIntNumberTerm(-1)) } func builtinIndexOfN(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -250,7 +273,7 @@ func builtinIndexOfN(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term for i, r := range baseRunes { if len(baseRunes) >= i+searchLen { if r == searchRunes[0] && runesEqual(baseRunes[i:i+searchLen], searchRunes) { - arr = append(arr, ast.IntNumberTerm(i)) + arr = append(arr, ast.InternedIntNumberTerm(i)) } } else { break @@ -266,15 +289,10 @@ func builtinSubstring(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Ter if err != nil { return err } - runes := []rune(base) startIndex, err := builtins.IntOperand(operands[1].Value, 2) if err != nil { return err - } else if startIndex >= len(runes) { - return iter(ast.StringTerm("")) - } else if startIndex < 0 { - return fmt.Errorf("negative offset") } length, err := builtins.IntOperand(operands[2].Value, 3) @@ -282,18 +300,60 @@ func builtinSubstring(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Ter return err } - var s ast.String + if startIndex < 0 { + return fmt.Errorf("negative offset") + } + + sbase := string(base) + if sbase == "" { + return iter(ast.InternedEmptyString) + } + + // Optimized path for the likely common case of ASCII strings. + // This allocates less memory and runs in about 1/3 the time. + if isASCII(sbase) { + if startIndex >= len(sbase) { + return iter(ast.InternedEmptyString) + } + + if length < 0 { + return iter(ast.StringTerm(sbase[startIndex:])) + } + + upto := startIndex + length + if len(sbase) < upto { + upto = len(sbase) + } + return iter(ast.StringTerm(sbase[startIndex:upto])) + } + + runes := []rune(base) + + if startIndex >= len(runes) { + return iter(ast.InternedEmptyString) + } + + var s string if length < 0 { - s = ast.String(runes[startIndex:]) + s = string(runes[startIndex:]) } else { upto := startIndex + length if len(runes) < upto { upto = len(runes) } - s = ast.String(runes[startIndex:upto]) + s = string(runes[startIndex:upto]) } - return iter(ast.NewTerm(s)) + return iter(ast.StringTerm(s)) +} + +func isASCII(s string) bool { + for i := 0; i < len(s); i++ { + if s[i] > unicode.MaxASCII { + return false + } + } + return true } func builtinContains(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -307,7 +367,7 @@ func builtinContains(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term return err } - return iter(ast.BooleanTerm(strings.Contains(string(s), string(substr)))) + return iter(ast.InternedBooleanTerm(strings.Contains(string(s), string(substr)))) } func builtinStringCount(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -323,10 +383,9 @@ func builtinStringCount(_ BuiltinContext, operands []*ast.Term, iter func(*ast.T baseTerm := string(s) searchTerm := string(substr) - count := strings.Count(baseTerm, searchTerm) - return iter(ast.IntNumberTerm(count)) + return iter(ast.InternedIntNumberTerm(count)) } func builtinStartsWith(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -340,7 +399,7 @@ func builtinStartsWith(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Te return err } - return iter(ast.BooleanTerm(strings.HasPrefix(string(s), string(prefix)))) + return iter(ast.InternedBooleanTerm(strings.HasPrefix(string(s), string(prefix)))) } func builtinEndsWith(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -354,7 +413,7 @@ func builtinEndsWith(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term return err } - return iter(ast.BooleanTerm(strings.HasSuffix(string(s), string(suffix)))) + return iter(ast.InternedBooleanTerm(strings.HasSuffix(string(s), string(suffix)))) } func builtinLower(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -380,15 +439,22 @@ func builtinSplit(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) e if err != nil { return err } + d, err := builtins.StringOperand(operands[1].Value, 2) if err != nil { return err } + + if !strings.Contains(string(s), string(d)) { + return iter(ast.ArrayTerm(operands[0])) + } + elems := strings.Split(string(s), string(d)) - arr := make([]*ast.Term, len(elems)) + arr := util.NewPtrSlice[ast.Term](len(elems)) for i := range elems { - arr[i] = ast.StringTerm(elems[i]) + arr[i].Value = ast.String(elems[i]) } + return iter(ast.ArrayTerm(arr...)) } @@ -408,7 +474,12 @@ func builtinReplace(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) return err } - return iter(ast.StringTerm(strings.Replace(string(s), string(old), string(n), -1))) + replaced := strings.Replace(string(s), string(old), string(n), -1) + if replaced == string(s) { + return iter(operands[0]) + } + + return iter(ast.StringTerm(replaced)) } func builtinReplaceN(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -437,14 +508,8 @@ func builtinReplaceN(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term } oldnewArr = append(oldnewArr, string(keyVal), string(strVal)) } - if err != nil { - return err - } - - r := strings.NewReplacer(oldnewArr...) - replaced := r.Replace(string(s)) - return iter(ast.StringTerm(replaced)) + return iter(ast.StringTerm(strings.NewReplacer(oldnewArr...).Replace(string(s)))) } func builtinTrim(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -458,6 +523,11 @@ func builtinTrim(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) er return err } + trimmed := strings.Trim(string(s), string(c)) + if trimmed == string(s) { + return iter(operands[0]) + } + return iter(ast.StringTerm(strings.Trim(string(s), string(c)))) } @@ -472,7 +542,12 @@ func builtinTrimLeft(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term return err } - return iter(ast.StringTerm(strings.TrimLeft(string(s), string(c)))) + trimmed := strings.TrimLeft(string(s), string(c)) + if trimmed == string(s) { + return iter(operands[0]) + } + + return iter(ast.StringTerm(trimmed)) } func builtinTrimPrefix(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -486,7 +561,12 @@ func builtinTrimPrefix(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Te return err } - return iter(ast.StringTerm(strings.TrimPrefix(string(s), string(pre)))) + trimmed := strings.TrimPrefix(string(s), string(pre)) + if trimmed == string(s) { + return iter(operands[0]) + } + + return iter(ast.StringTerm(trimmed)) } func builtinTrimRight(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -500,7 +580,12 @@ func builtinTrimRight(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Ter return err } - return iter(ast.StringTerm(strings.TrimRight(string(s), string(c)))) + trimmed := strings.TrimRight(string(s), string(c)) + if trimmed == string(s) { + return iter(operands[0]) + } + + return iter(ast.StringTerm(trimmed)) } func builtinTrimSuffix(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -514,7 +599,12 @@ func builtinTrimSuffix(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Te return err } - return iter(ast.StringTerm(strings.TrimSuffix(string(s), string(suf)))) + trimmed := strings.TrimSuffix(string(s), string(suf)) + if trimmed == string(s) { + return iter(operands[0]) + } + + return iter(ast.StringTerm(trimmed)) } func builtinTrimSpace(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -523,7 +613,12 @@ func builtinTrimSpace(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Ter return err } - return iter(ast.StringTerm(strings.TrimSpace(string(s)))) + trimmed := strings.TrimSpace(string(s)) + if trimmed == string(s) { + return iter(operands[0]) + } + + return iter(ast.StringTerm(trimmed)) } func builtinSprintf(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { @@ -537,7 +632,17 @@ func builtinSprintf(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) return builtins.NewOperandTypeErr(2, operands[1].Value, "array") } - args := make([]interface{}, astArr.Len()) + // Optimized path for where sprintf is used as a "to_string" function for + // a single integer, i.e. sprintf("%d", [x]) where x is an integer. + if s == "%d" && astArr.Len() == 1 { + if n, ok := astArr.Elem(0).Value.(ast.Number); ok { + if i, ok := n.Int(); ok { + return iter(ast.StringTerm(strconv.Itoa(i))) + } + } + } + + args := make([]any, astArr.Len()) for i := range args { switch v := astArr.Elem(i).Value.(type) { @@ -571,15 +676,23 @@ func builtinReverse(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) } func reverseString(str string) string { - sRunes := []rune(str) - length := len(sRunes) - reversedRunes := make([]rune, length) + var buf []byte + var arr [255]byte + size := len(str) + + if size < 255 { + buf = arr[:size:size] + } else { + buf = make([]byte, size) + } - for index, r := range sRunes { - reversedRunes[length-index-1] = r + for start := 0; start < size; { + r, n := utf8.DecodeRuneInString(str[start:]) + start += n + utf8.EncodeRune(buf[size-start:], r) } - return string(reversedRunes) + return string(buf) } func init() { diff --git a/vendor/github.com/open-policy-agent/opa/topdown/subset.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/subset.go similarity index 82% rename from vendor/github.com/open-policy-agent/opa/topdown/subset.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/subset.go index 7b152a5ef9..29354d9730 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/subset.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/subset.go @@ -5,8 +5,8 @@ package topdown import ( - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) func bothObjects(t1, t2 *ast.Term) (bool, ast.Object, ast.Object) { @@ -88,9 +88,8 @@ func arraySet(t1, t2 *ast.Term) (bool, *ast.Array, ast.Set) { // associated with a key. func objectSubset(super ast.Object, sub ast.Object) bool { var superTerm *ast.Term - isSubset := true - sub.Until(func(key, subTerm *ast.Term) bool { + notSubset := sub.Until(func(key, subTerm *ast.Term) bool { // This really wants to be a for loop, hence the somewhat // weird internal structure. However, using Until() in this // was is a performance optimization, as it avoids performing @@ -98,10 +97,9 @@ func objectSubset(super ast.Object, sub ast.Object) bool { superTerm = super.Get(key) - // subTerm is can't be nil because we got it from Until(), so + // subTerm can't be nil because we got it from Until(), so // we only need to verify that super is non-nil. if superTerm == nil { - isSubset = false return true // break, not a subset } @@ -114,58 +112,39 @@ func objectSubset(super ast.Object, sub ast.Object) bool { // them normally. If only one term is an object, then we // do a normal comparison which will come up false. if ok, superObj, subObj := bothObjects(superTerm, subTerm); ok { - if !objectSubset(superObj, subObj) { - isSubset = false - return true // break, not a subset - } - - return false // continue + return !objectSubset(superObj, subObj) } if ok, superSet, subSet := bothSets(superTerm, subTerm); ok { - if !setSubset(superSet, subSet) { - isSubset = false - return true // break, not a subset - } - - return false // continue + return !setSubset(superSet, subSet) } if ok, superArray, subArray := bothArrays(superTerm, subTerm); ok { - if !arraySubset(superArray, subArray) { - isSubset = false - return true // break, not a subset - } - - return false // continue + return !arraySubset(superArray, subArray) } // We have already checked for exact equality, as well as for // all of the types of nested subsets we care about, so if we // get here it means this isn't a subset. - isSubset = false return true // break, not a subset }) - return isSubset + return !notSubset } // setSubset implements the subset operation on sets. // // Unlike in the object case, this is not recursive, we just compare values -// using ast.Set.Contains() because we have no well defined way to "match up" +// using ast.Set.Contains() because we have no well-defined way to "match up" // objects that are in different sets. func setSubset(super ast.Set, sub ast.Set) bool { - isSubset := true - sub.Until(func(t *ast.Term) bool { - if !super.Contains(t) { - isSubset = false - return true + for _, elem := range sub.Slice() { + if !super.Contains(elem) { + return false } - return false - }) + } - return isSubset + return true } // arraySubset implements the subset operation on arrays. @@ -197,12 +176,12 @@ func arraySubset(super, sub *ast.Array) bool { return false } - subElem := sub.Elem(subCursor) superElem := super.Elem(superCursor + subCursor) if superElem == nil { return false } + subElem := sub.Elem(subCursor) if superElem.Value.Compare(subElem.Value) == 0 { subCursor++ } else { @@ -237,22 +216,22 @@ func builtinObjectSubset(_ BuiltinContext, operands []*ast.Term, iter func(*ast. if ok, superObj, subObj := bothObjects(superTerm, subTerm); ok { // Both operands are objects. - return iter(ast.BooleanTerm(objectSubset(superObj, subObj))) + return iter(ast.InternedBooleanTerm(objectSubset(superObj, subObj))) } if ok, superSet, subSet := bothSets(superTerm, subTerm); ok { // Both operands are sets. - return iter(ast.BooleanTerm(setSubset(superSet, subSet))) + return iter(ast.InternedBooleanTerm(setSubset(superSet, subSet))) } if ok, superArray, subArray := bothArrays(superTerm, subTerm); ok { // Both operands are sets. - return iter(ast.BooleanTerm(arraySubset(superArray, subArray))) + return iter(ast.InternedBooleanTerm(arraySubset(superArray, subArray))) } if ok, superArray, subSet := arraySet(superTerm, subTerm); ok { // Super operand is array and sub operand is set - return iter(ast.BooleanTerm(arraySetSubset(superArray, subSet))) + return iter(ast.InternedBooleanTerm(arraySetSubset(superArray, subSet))) } return builtins.ErrOperand("both arguments object.subset must be of the same type or array and set") diff --git a/vendor/github.com/open-policy-agent/opa/topdown/template.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/template.go similarity index 90% rename from vendor/github.com/open-policy-agent/opa/topdown/template.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/template.go index cf42477ee8..cf4635559d 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/template.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/template.go @@ -4,8 +4,8 @@ import ( "bytes" "text/template" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) func renderTemplate(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { diff --git a/vendor/github.com/open-policy-agent/opa/topdown/time.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/time.go similarity index 93% rename from vendor/github.com/open-policy-agent/opa/topdown/time.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/time.go index ba3efc75dc..1c5ddaa6f4 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/time.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/time.go @@ -14,8 +14,8 @@ import ( "time" _ "time/tzdata" // this is needed to have LoadLocation when no filesystem tzdata is available - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) var tzCache map[string]*time.Location @@ -127,7 +127,7 @@ func builtinDate(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) er return err } year, month, day := t.Date() - result := ast.NewArray(ast.IntNumberTerm(year), ast.IntNumberTerm(int(month)), ast.IntNumberTerm(day)) + result := ast.NewArray(ast.InternedIntNumberTerm(year), ast.InternedIntNumberTerm(int(month)), ast.InternedIntNumberTerm(day)) return iter(ast.NewTerm(result)) } @@ -137,7 +137,7 @@ func builtinClock(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) e return err } hour, minute, second := t.Clock() - result := ast.NewArray(ast.IntNumberTerm(hour), ast.IntNumberTerm(minute), ast.IntNumberTerm(second)) + result := ast.NewArray(ast.InternedIntNumberTerm(hour), ast.InternedIntNumberTerm(minute), ast.InternedIntNumberTerm(second)) return iter(ast.NewTerm(result)) } @@ -238,8 +238,8 @@ func builtinDiff(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) er } // END REDISTRIBUTION FROM APACHE 2.0 LICENSED PROJECT - return iter(ast.ArrayTerm(ast.IntNumberTerm(year), ast.IntNumberTerm(month), ast.IntNumberTerm(day), - ast.IntNumberTerm(hour), ast.IntNumberTerm(min), ast.IntNumberTerm(sec))) + return iter(ast.ArrayTerm(ast.InternedIntNumberTerm(year), ast.InternedIntNumberTerm(month), ast.InternedIntNumberTerm(day), + ast.InternedIntNumberTerm(hour), ast.InternedIntNumberTerm(min), ast.InternedIntNumberTerm(sec))) } func tzTime(a ast.Value) (t time.Time, lay string, err error) { diff --git a/vendor/github.com/open-policy-agent/opa/topdown/tokens.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/tokens.go similarity index 77% rename from vendor/github.com/open-policy-agent/opa/topdown/tokens.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/tokens.go index 7457f1f15d..b44c5a253d 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/tokens.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/tokens.go @@ -21,11 +21,12 @@ import ( "math/big" "strings" - "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/internal/jwx/jwa" "github.com/open-policy-agent/opa/internal/jwx/jwk" "github.com/open-policy-agent/opa/internal/jwx/jws" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" + "github.com/open-policy-agent/opa/v1/topdown/cache" ) var ( @@ -129,8 +130,8 @@ func builtinJWTDecode(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Ter } // Implements RS256 JWT signature verification -func builtinJWTVerifyRS256(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { - result, err := builtinJWTVerifyRSA(operands[0].Value, operands[1].Value, sha256.New, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error { +func builtinJWTVerifyRS256(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + result, err := builtinJWTVerifyRSA(bctx, operands[0].Value, operands[1].Value, sha256.New, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error { return rsa.VerifyPKCS1v15( publicKey, crypto.SHA256, @@ -144,8 +145,8 @@ func builtinJWTVerifyRS256(_ BuiltinContext, operands []*ast.Term, iter func(*as } // Implements RS384 JWT signature verification -func builtinJWTVerifyRS384(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { - result, err := builtinJWTVerifyRSA(operands[0].Value, operands[1].Value, sha512.New384, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error { +func builtinJWTVerifyRS384(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + result, err := builtinJWTVerifyRSA(bctx, operands[0].Value, operands[1].Value, sha512.New384, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error { return rsa.VerifyPKCS1v15( publicKey, crypto.SHA384, @@ -159,8 +160,8 @@ func builtinJWTVerifyRS384(_ BuiltinContext, operands []*ast.Term, iter func(*as } // Implements RS512 JWT signature verification -func builtinJWTVerifyRS512(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { - result, err := builtinJWTVerifyRSA(operands[0].Value, operands[1].Value, sha512.New, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error { +func builtinJWTVerifyRS512(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + result, err := builtinJWTVerifyRSA(bctx, operands[0].Value, operands[1].Value, sha512.New, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error { return rsa.VerifyPKCS1v15( publicKey, crypto.SHA512, @@ -174,8 +175,8 @@ func builtinJWTVerifyRS512(_ BuiltinContext, operands []*ast.Term, iter func(*as } // Implements PS256 JWT signature verification -func builtinJWTVerifyPS256(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { - result, err := builtinJWTVerifyRSA(operands[0].Value, operands[1].Value, sha256.New, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error { +func builtinJWTVerifyPS256(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + result, err := builtinJWTVerifyRSA(bctx, operands[0].Value, operands[1].Value, sha256.New, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error { return rsa.VerifyPSS( publicKey, crypto.SHA256, @@ -190,8 +191,8 @@ func builtinJWTVerifyPS256(_ BuiltinContext, operands []*ast.Term, iter func(*as } // Implements PS384 JWT signature verification -func builtinJWTVerifyPS384(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { - result, err := builtinJWTVerifyRSA(operands[0].Value, operands[1].Value, sha512.New384, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error { +func builtinJWTVerifyPS384(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + result, err := builtinJWTVerifyRSA(bctx, operands[0].Value, operands[1].Value, sha512.New384, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error { return rsa.VerifyPSS( publicKey, crypto.SHA384, @@ -206,8 +207,8 @@ func builtinJWTVerifyPS384(_ BuiltinContext, operands []*ast.Term, iter func(*as } // Implements PS512 JWT signature verification -func builtinJWTVerifyPS512(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { - result, err := builtinJWTVerifyRSA(operands[0].Value, operands[1].Value, sha512.New, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error { +func builtinJWTVerifyPS512(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + result, err := builtinJWTVerifyRSA(bctx, operands[0].Value, operands[1].Value, sha512.New, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error { return rsa.VerifyPSS( publicKey, crypto.SHA512, @@ -222,8 +223,8 @@ func builtinJWTVerifyPS512(_ BuiltinContext, operands []*ast.Term, iter func(*as } // Implements RSA JWT signature verification. -func builtinJWTVerifyRSA(a ast.Value, b ast.Value, hasher func() hash.Hash, verify func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error) (ast.Value, error) { - return builtinJWTVerify(a, b, hasher, func(publicKey interface{}, digest []byte, signature []byte) error { +func builtinJWTVerifyRSA(bctx BuiltinContext, jwt ast.Value, keyStr ast.Value, hasher func() hash.Hash, verify func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error) (ast.Value, error) { + return builtinJWTVerify(bctx, jwt, keyStr, hasher, func(publicKey interface{}, digest []byte, signature []byte) error { publicKeyRsa, ok := publicKey.(*rsa.PublicKey) if !ok { return fmt.Errorf("incorrect public key type") @@ -233,8 +234,8 @@ func builtinJWTVerifyRSA(a ast.Value, b ast.Value, hasher func() hash.Hash, veri } // Implements ES256 JWT signature verification. -func builtinJWTVerifyES256(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { - result, err := builtinJWTVerify(operands[0].Value, operands[1].Value, sha256.New, verifyES) +func builtinJWTVerifyES256(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + result, err := builtinJWTVerify(bctx, operands[0].Value, operands[1].Value, sha256.New, verifyES) if err == nil { return iter(ast.NewTerm(result)) } @@ -242,8 +243,8 @@ func builtinJWTVerifyES256(_ BuiltinContext, operands []*ast.Term, iter func(*as } // Implements ES384 JWT signature verification -func builtinJWTVerifyES384(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { - result, err := builtinJWTVerify(operands[0].Value, operands[1].Value, sha512.New384, verifyES) +func builtinJWTVerifyES384(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + result, err := builtinJWTVerify(bctx, operands[0].Value, operands[1].Value, sha512.New384, verifyES) if err == nil { return iter(ast.NewTerm(result)) } @@ -251,8 +252,8 @@ func builtinJWTVerifyES384(_ BuiltinContext, operands []*ast.Term, iter func(*as } // Implements ES512 JWT signature verification -func builtinJWTVerifyES512(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { - result, err := builtinJWTVerify(operands[0].Value, operands[1].Value, sha512.New, verifyES) +func builtinJWTVerifyES512(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + result, err := builtinJWTVerify(bctx, operands[0].Value, operands[1].Value, sha512.New, verifyES) if err == nil { return iter(ast.NewTerm(result)) } @@ -345,13 +346,17 @@ func getKeyByKid(kid string, keys []verificationKey) *verificationKey { } // Implements JWT signature verification. -func builtinJWTVerify(a ast.Value, b ast.Value, hasher func() hash.Hash, verify func(publicKey interface{}, digest []byte, signature []byte) error) (ast.Value, error) { - token, err := decodeJWT(a) +func builtinJWTVerify(bctx BuiltinContext, jwt ast.Value, keyStr ast.Value, hasher func() hash.Hash, verify func(publicKey interface{}, digest []byte, signature []byte) error) (ast.Value, error) { + if found, _, _, valid := getTokenFromCache(bctx, jwt, keyStr); found { + return ast.Boolean(valid), nil + } + + token, err := decodeJWT(jwt) if err != nil { return nil, err } - s, err := builtins.StringOperand(b, 2) + s, err := builtins.StringOperand(keyStr, 2) if err != nil { return nil, err } @@ -375,6 +380,11 @@ func builtinJWTVerify(a ast.Value, b ast.Value, hasher func() hash.Hash, verify return nil, err } + done := func(valid bool) (ast.Boolean, error) { + putTokenInCache(bctx, jwt, keyStr, nil, nil, valid) + return ast.Boolean(valid), nil + } + // Validate the JWT signature // First, check if there's a matching key ID (`kid`) in both token header and key(s). @@ -383,7 +393,7 @@ func builtinJWTVerify(a ast.Value, b ast.Value, hasher func() hash.Hash, verify if key := getKeyByKid(header.kid, keys); key != nil { err = verify(key.key, getInputSHA([]byte(token.header+"."+token.payload), hasher), []byte(signature)) - return ast.Boolean(err == nil), nil + return done(err == nil) } } @@ -395,7 +405,7 @@ func builtinJWTVerify(a ast.Value, b ast.Value, hasher func() hash.Hash, verify // we'll need to verify to find out err = verify(key.key, getInputSHA([]byte(token.header+"."+token.payload), hasher), []byte(signature)) if err == nil { - return ast.Boolean(true), nil + return done(true) } } else { if header.alg != key.alg { @@ -403,48 +413,32 @@ func builtinJWTVerify(a ast.Value, b ast.Value, hasher func() hash.Hash, verify } err = verify(key.key, getInputSHA([]byte(token.header+"."+token.payload), hasher), []byte(signature)) if err == nil { - return ast.Boolean(true), nil + return done(true) } } } // None of the keys worked, return false - return ast.Boolean(false), nil + return done(false) } // Implements HS256 (secret) JWT signature verification -func builtinJWTVerifyHS256(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { - // Decode the JSON Web Token - token, err := decodeJWT(operands[0].Value) - if err != nil { - return err - } - - // Process Secret input - astSecret, err := builtins.StringOperand(operands[1].Value, 2) - if err != nil { - return err - } - secret := string(astSecret) - - mac := hmac.New(sha256.New, []byte(secret)) - _, err = mac.Write([]byte(token.header + "." + token.payload)) - if err != nil { - return err - } +func builtinJWTVerifyHS256(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + return builtinJWTVerifyHS(bctx, operands, sha256.New, iter) +} - signature, err := token.decodeSignature() - if err != nil { - return err - } +// Implements HS384 JWT signature verification +func builtinJWTVerifyHS384(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + return builtinJWTVerifyHS(bctx, operands, sha512.New384, iter) +} - return iter(ast.NewTerm(ast.Boolean(hmac.Equal([]byte(signature), mac.Sum(nil))))) +// Implements HS512 JWT signature verification +func builtinJWTVerifyHS512(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + return builtinJWTVerifyHS(bctx, operands, sha512.New, iter) } -// Implements HS384 JWT signature verification -func builtinJWTVerifyHS384(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { - // Decode the JSON Web Token - token, err := decodeJWT(operands[0].Value) +func builtinJWTVerifyHS(bctx BuiltinContext, operands []*ast.Term, hashF func() hash.Hash, iter func(*ast.Term) error) error { + jwt, err := builtins.StringOperand(operands[0].Value, 1) if err != nil { return err } @@ -454,38 +448,20 @@ func builtinJWTVerifyHS384(_ BuiltinContext, operands []*ast.Term, iter func(*as if err != nil { return err } - secret := string(astSecret) - - mac := hmac.New(sha512.New384, []byte(secret)) - _, err = mac.Write([]byte(token.header + "." + token.payload)) - if err != nil { - return err - } - signature, err := token.decodeSignature() - if err != nil { - return err + if found, _, _, valid := getTokenFromCache(bctx, jwt, astSecret); found { + return iter(ast.NewTerm(ast.Boolean(valid))) } - return iter(ast.NewTerm(ast.Boolean(hmac.Equal([]byte(signature), mac.Sum(nil))))) -} - -// Implements HS512 JWT signature verification -func builtinJWTVerifyHS512(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { // Decode the JSON Web Token - token, err := decodeJWT(operands[0].Value) + token, err := decodeJWT(jwt) if err != nil { return err } - // Process Secret input - astSecret, err := builtins.StringOperand(operands[1].Value, 2) - if err != nil { - return err - } secret := string(astSecret) - mac := hmac.New(sha512.New, []byte(secret)) + mac := hmac.New(hashF, []byte(secret)) _, err = mac.Write([]byte(token.header + "." + token.payload)) if err != nil { return err @@ -496,7 +472,11 @@ func builtinJWTVerifyHS512(_ BuiltinContext, operands []*ast.Term, iter func(*as return err } - return iter(ast.NewTerm(ast.Boolean(hmac.Equal([]byte(signature), mac.Sum(nil))))) + valid := hmac.Equal([]byte(signature), mac.Sum(nil)) + + putTokenInCache(bctx, jwt, astSecret, nil, nil, valid) + + return iter(ast.NewTerm(ast.Boolean(valid))) } // -- Full JWT verification and decoding -- @@ -1024,7 +1004,7 @@ func builtinJWTDecodeVerify(bctx BuiltinContext, operands []*ast.Term, iter func } unverified := ast.ArrayTerm( - ast.BooleanTerm(false), + ast.InternedBooleanTerm(false), ast.NewTerm(ast.NewObject()), ast.NewTerm(ast.NewObject()), ) @@ -1036,57 +1016,115 @@ func builtinJWTDecodeVerify(bctx BuiltinContext, operands []*ast.Term, iter func return err } var token *JSONWebToken - var p *ast.Term - for { - // RFC7519 7.2 #1-2 split into parts - if token, err = decodeJWT(a); err != nil { - return err - } - // RFC7519 7.2 #3, #4, #6 - if err := token.decodeHeader(); err != nil { - return err - } - // RFC7159 7.2 #5 (and RFC7159 5.2 #5) validate header fields - header, err := parseTokenHeader(token) - if err != nil { - return err - } - if !header.valid() { + var payload ast.Object + var header ast.Object + + // FIXME: optimize + k, _ := b.Filter(ast.NewObject( + ast.Item(ast.StringTerm("secret"), ast.ObjectTerm()), + ast.Item(ast.StringTerm("cert"), ast.ObjectTerm()), + )) + + if found, th, tp, validSignature := getTokenFromCache(bctx, a, k); found { + if !validSignature { + // For the given token and key(s), the signature is invalid return iter(unverified) } - // Check constraints that impact signature verification. - if constraints.alg != "" && constraints.alg != header.alg { - return iter(unverified) - } - // RFC7159 7.2 #7 verify the signature - signature, err := token.decodeSignature() - if err != nil { - return err + + if th != nil && tp != nil { + header = th + payload = tp + } else { + // Cache entry was created by one of the other built-ins that doesn't decode header/payload + + if token, err = decodeJWT(a); err != nil { + return err + } + + header = token.decodedHeader + + p, err := getResult(builtinBase64UrlDecode, ast.StringTerm(token.payload)) + if err != nil { + return fmt.Errorf("JWT payload had invalid encoding: %v", err) + } + + payload, err = extractJSONObject(string(p.Value.(ast.String))) + if err != nil { + return err + } + + putTokenInCache(bctx, a, k, header, payload, true) } - if err := constraints.verify(header.kid, header.alg, token.header, token.payload, signature); err != nil { - if err == errSignatureNotVerified { + } else { + var p *ast.Term + + for { + // RFC7519 7.2 #1-2 split into parts + if token, err = decodeJWT(a); err != nil { + return err + } + + // RFC7519 7.2 #3, #4, #6 + if err := token.decodeHeader(); err != nil { + return err + } + + // RFC7159 7.2 #5 (and RFC7159 5.2 #5) validate header fields + header, err := parseTokenHeader(token) + if err != nil { + return err + } + + if !header.valid() { return iter(unverified) } - return err + + // Check constraints that impact signature verification. + if constraints.alg != "" && constraints.alg != header.alg { + return iter(unverified) + } + + // RFC7159 7.2 #7 verify the signature + signature, err := token.decodeSignature() + if err != nil { + return err + } + + if err := constraints.verify(header.kid, header.alg, token.header, token.payload, signature); err != nil { + if err == errSignatureNotVerified { + putTokenInCache(bctx, a, k, nil, nil, false) + return iter(unverified) + } + return err + } + + // RFC7159 7.2 #9-10 decode the payload + p, err = getResult(builtinBase64UrlDecode, ast.StringTerm(token.payload)) + if err != nil { + return fmt.Errorf("JWT payload had invalid encoding: %v", err) + } + + // RFC7159 7.2 #8 and 5.2 cty + if strings.ToUpper(header.cty) == headerJwt { + // Nested JWT, go round again with payload as first argument + a = p.Value + continue + } + + // Non-nested JWT (or we've reached the bottom of the nesting). + break } - // RFC7159 7.2 #9-10 decode the payload - p, err = getResult(builtinBase64UrlDecode, ast.StringTerm(token.payload)) + + payload, err = extractJSONObject(string(p.Value.(ast.String))) if err != nil { - return fmt.Errorf("JWT payload had invalid encoding: %v", err) - } - // RFC7159 7.2 #8 and 5.2 cty - if strings.ToUpper(header.cty) == headerJwt { - // Nested JWT, go round again with payload as first argument - a = p.Value - continue + return err } - // Non-nested JWT (or we've reached the bottom of the nesting). - break - } - payload, err := extractJSONObject(string(p.Value.(ast.String))) - if err != nil { - return err + + header = token.decodedHeader + + putTokenInCache(bctx, a, k, header, payload, true) } + // Check registered claim names against constraints or environment // RFC7159 4.1.1 iss if constraints.iss != "" { @@ -1137,8 +1175,8 @@ func builtinJWTDecodeVerify(bctx BuiltinContext, operands []*ast.Term, iter func } verified := ast.ArrayTerm( - ast.BooleanTerm(true), - ast.NewTerm(token.decodedHeader), + ast.InternedBooleanTerm(true), + ast.NewTerm(header), ast.NewTerm(payload), ) return iter(verified) @@ -1226,7 +1264,63 @@ func getInputSHA(input []byte, h func() hash.Hash) []byte { return hasher.Sum(nil) } +type jwtCacheEntry struct { + payload ast.Object + header ast.Object + validSignature bool +} + +const tokenCacheName = "io_jwt" + +func getTokenFromCache(bctx BuiltinContext, serializedJwt ast.Value, publicKey ast.Value) (bool, ast.Object, ast.Object, bool) { + if bctx.InterQueryBuiltinValueCache == nil { + return false, nil, nil, false + } + + c := bctx.InterQueryBuiltinValueCache.GetCache(tokenCacheName) + if c == nil { + return false, nil, nil, false + } + + key := createTokenCacheKey(serializedJwt, publicKey) + + entry, ok := c.Get(key) + if !ok { + return false, nil, nil, false + } + + if jwtEntry, ok := entry.(jwtCacheEntry); ok { + return true, jwtEntry.header, jwtEntry.payload, jwtEntry.validSignature + } + + return false, nil, nil, false +} + +func putTokenInCache(bctx BuiltinContext, serializedJwt ast.Value, publicKey ast.Value, header ast.Object, payload ast.Object, validSignature bool) { + if bctx.InterQueryBuiltinValueCache == nil { + return + } + + c := bctx.InterQueryBuiltinValueCache.GetCache(tokenCacheName) + if c == nil { + return + } + + key := createTokenCacheKey(serializedJwt, publicKey) + + c.Insert(key, jwtCacheEntry{header: header, payload: payload, validSignature: validSignature}) +} + +func createTokenCacheKey(serializedJwt ast.Value, publicKey ast.Value) ast.Value { + // We need to create a key that is unique to the serialized JWT (for lookup) and the public key used to verify it, + // so that we don't get a misleading cached validation result for a different, invalid key. + return ast.NewArray(ast.NewTerm(serializedJwt), ast.NewTerm(publicKey)) +} + func init() { + // By default, the JWT cache is disabled. + cache.RegisterDefaultInterQueryBuiltinValueCacheConfig(tokenCacheName, nil) + RegisterBuiltinFunc(ast.JWTDecode.Name, builtinJWTDecode) RegisterBuiltinFunc(ast.JWTVerifyRS256.Name, builtinJWTVerifyRS256) RegisterBuiltinFunc(ast.JWTVerifyRS384.Name, builtinJWTVerifyRS384) diff --git a/vendor/github.com/open-policy-agent/opa/topdown/trace.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/trace.go similarity index 99% rename from vendor/github.com/open-policy-agent/opa/topdown/trace.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/trace.go index 277c94b626..1c45ef23ba 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/trace.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/trace.go @@ -13,8 +13,8 @@ import ( iStrs "github.com/open-policy-agent/opa/internal/strings" - "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) const ( @@ -537,7 +537,7 @@ func builtinTrace(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term } if !bctx.TraceEnabled { - return iter(ast.BooleanTerm(true)) + return iter(ast.InternedBooleanTerm(true)) } evt := Event{ @@ -552,7 +552,7 @@ func builtinTrace(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term bctx.QueryTracers[i].TraceEvent(evt) } - return iter(ast.BooleanTerm(true)) + return iter(ast.InternedBooleanTerm(true)) } func rewrite(event *Event) *Event { diff --git a/vendor/github.com/open-policy-agent/opa/topdown/type.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/type.go similarity index 71% rename from vendor/github.com/open-policy-agent/opa/topdown/type.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/type.go index dab5c853cd..6103fbe484 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/type.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/type.go @@ -5,69 +5,69 @@ package topdown import ( - "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/v1/ast" ) func builtinIsNumber(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { switch operands[0].Value.(type) { case ast.Number: - return iter(ast.BooleanTerm(true)) + return iter(ast.InternedBooleanTerm(true)) default: - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } } func builtinIsString(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { switch operands[0].Value.(type) { case ast.String: - return iter(ast.BooleanTerm(true)) + return iter(ast.InternedBooleanTerm(true)) default: - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } } func builtinIsBoolean(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { switch operands[0].Value.(type) { case ast.Boolean: - return iter(ast.BooleanTerm(true)) + return iter(ast.InternedBooleanTerm(true)) default: - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } } func builtinIsArray(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { switch operands[0].Value.(type) { case *ast.Array: - return iter(ast.BooleanTerm(true)) + return iter(ast.InternedBooleanTerm(true)) default: - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } } func builtinIsSet(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { switch operands[0].Value.(type) { case ast.Set: - return iter(ast.BooleanTerm(true)) + return iter(ast.InternedBooleanTerm(true)) default: - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } } func builtinIsObject(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { switch operands[0].Value.(type) { case ast.Object: - return iter(ast.BooleanTerm(true)) + return iter(ast.InternedBooleanTerm(true)) default: - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } } func builtinIsNull(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { switch operands[0].Value.(type) { case ast.Null: - return iter(ast.BooleanTerm(true)) + return iter(ast.InternedBooleanTerm(true)) default: - return iter(ast.BooleanTerm(false)) + return iter(ast.InternedBooleanTerm(false)) } } diff --git a/vendor/github.com/open-policy-agent/opa/v1/topdown/type_name.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/type_name.go new file mode 100644 index 0000000000..fc3de48793 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/type_name.go @@ -0,0 +1,46 @@ +// Copyright 2018 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package topdown + +import ( + "fmt" + + "github.com/open-policy-agent/opa/v1/ast" +) + +var ( + nullStringTerm = ast.StringTerm("null") + booleanStringTerm = ast.StringTerm("boolean") + numberStringTerm = ast.StringTerm("number") + stringStringTerm = ast.StringTerm("string") + arrayStringTerm = ast.StringTerm("array") + objectStringTerm = ast.StringTerm("object") + setStringTerm = ast.StringTerm("set") +) + +func builtinTypeName(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + switch operands[0].Value.(type) { + case ast.Null: + return iter(nullStringTerm) + case ast.Boolean: + return iter(booleanStringTerm) + case ast.Number: + return iter(numberStringTerm) + case ast.String: + return iter(stringStringTerm) + case *ast.Array: + return iter(arrayStringTerm) + case ast.Object: + return iter(objectStringTerm) + case ast.Set: + return iter(setStringTerm) + } + + return fmt.Errorf("illegal value") +} + +func init() { + RegisterBuiltinFunc(ast.TypeNameBuiltin.Name, builtinTypeName) +} diff --git a/vendor/github.com/open-policy-agent/opa/topdown/uuid.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/uuid.go similarity index 92% rename from vendor/github.com/open-policy-agent/opa/topdown/uuid.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/uuid.go index d3a7a5f900..d013df9fea 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/uuid.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/uuid.go @@ -5,9 +5,9 @@ package topdown import ( - "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/internal/uuid" - "github.com/open-policy-agent/opa/topdown/builtins" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" ) type uuidCachingKey string diff --git a/vendor/github.com/open-policy-agent/opa/topdown/walk.go b/vendor/github.com/open-policy-agent/opa/v1/topdown/walk.go similarity index 62% rename from vendor/github.com/open-policy-agent/opa/topdown/walk.go rename to vendor/github.com/open-policy-agent/opa/v1/topdown/walk.go index 0f3b3544b5..f5dcf5c9f1 100644 --- a/vendor/github.com/open-policy-agent/opa/topdown/walk.go +++ b/vendor/github.com/open-policy-agent/opa/v1/topdown/walk.go @@ -5,18 +5,20 @@ package topdown import ( - "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/v1/ast" ) +var emptyArr = ast.ArrayTerm() + func evalWalk(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { input := operands[0] if pathIsWildcard(operands) { // When the path assignment is a wildcard: walk(input, [_, value]) // we may skip the path construction entirely, and simply return - // same pointer in each iteration. This is a much more efficient + // same pointer in each iteration. This is a *much* more efficient // path when only the values are needed. - return walkNoPath(input, iter) + return walkNoPath(ast.ArrayTerm(emptyArr, input), iter) } filter := getOutputPath(operands) @@ -24,7 +26,6 @@ func evalWalk(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error } func walk(filter, path *ast.Array, input *ast.Term, iter func(*ast.Term) error) error { - if filter == nil || filter.Len() == 0 { if path == nil { path = ast.NewArray() @@ -50,57 +51,62 @@ func walk(filter, path *ast.Array, input *ast.Term, iter func(*ast.Term) error) switch v := input.Value.(type) { case *ast.Array: for i := 0; i < v.Len(); i++ { - path = pathAppend(path, ast.IntNumberTerm(i)) - if err := walk(filter, path, v.Elem(i), iter); err != nil { + if err := walk(filter, pathAppend(path, ast.InternedIntNumberTerm(i)), v.Elem(i), iter); err != nil { return err } - path = path.Slice(0, path.Len()-1) } case ast.Object: - return v.Iter(func(k, v *ast.Term) error { - path = pathAppend(path, k) - if err := walk(filter, path, v, iter); err != nil { + for _, k := range v.Keys() { + if err := walk(filter, pathAppend(path, k), v.Get(k), iter); err != nil { return err } - path = path.Slice(0, path.Len()-1) - return nil - }) + } case ast.Set: - return v.Iter(func(elem *ast.Term) error { - path = pathAppend(path, elem) - if err := walk(filter, path, elem, iter); err != nil { + for _, elem := range v.Slice() { + if err := walk(filter, pathAppend(path, elem), elem, iter); err != nil { return err } - path = path.Slice(0, path.Len()-1) - return nil - }) + } } return nil } -var emptyArr = ast.ArrayTerm() - func walkNoPath(input *ast.Term, iter func(*ast.Term) error) error { - if err := iter(ast.ArrayTerm(emptyArr, input)); err != nil { + // Note: the path array is embedded in the input from the start here + // in order to avoid an extra allocation per iteration. This leads to + // a little convoluted code below in order to extract and set the value, + // but since walk is commonly used to traverse large data structures, + // the performance gain is worth it. + if err := iter(input); err != nil { return err } - switch v := input.Value.(type) { + inputArray := input.Value.(*ast.Array) + value := inputArray.Get(ast.InternedIntNumberTerm(1)).Value + + switch v := value.(type) { case ast.Object: - return v.Iter(func(_, v *ast.Term) error { - return walkNoPath(v, iter) - }) + for _, k := range v.Keys() { + inputArray.Set(1, v.Get(k)) + if err := walkNoPath(input, iter); err != nil { + return err + } + } case *ast.Array: for i := 0; i < v.Len(); i++ { - if err := walkNoPath(v.Elem(i), iter); err != nil { + inputArray.Set(1, v.Elem(i)) + if err := walkNoPath(input, iter); err != nil { return err } } case ast.Set: - return v.Iter(func(elem *ast.Term) error { - return walkNoPath(elem, iter) - }) + for _, elem := range v.Slice() { + inputArray.Set(1, elem) + if err := walkNoPath(input, iter); err != nil { + return err + } + } } return nil diff --git a/vendor/github.com/open-policy-agent/opa/tracing/tracing.go b/vendor/github.com/open-policy-agent/opa/v1/tracing/tracing.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/tracing/tracing.go rename to vendor/github.com/open-policy-agent/opa/v1/tracing/tracing.go diff --git a/vendor/github.com/open-policy-agent/opa/types/decode.go b/vendor/github.com/open-policy-agent/opa/v1/types/decode.go similarity index 99% rename from vendor/github.com/open-policy-agent/opa/types/decode.go rename to vendor/github.com/open-policy-agent/opa/v1/types/decode.go index a6bd9ea030..3fcc01664c 100644 --- a/vendor/github.com/open-policy-agent/opa/types/decode.go +++ b/vendor/github.com/open-policy-agent/opa/v1/types/decode.go @@ -8,7 +8,7 @@ import ( "encoding/json" "fmt" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/util" ) const ( diff --git a/vendor/github.com/open-policy-agent/opa/types/types.go b/vendor/github.com/open-policy-agent/opa/v1/types/types.go similarity index 98% rename from vendor/github.com/open-policy-agent/opa/types/types.go rename to vendor/github.com/open-policy-agent/opa/v1/types/types.go index 2a050927dd..0705210875 100644 --- a/vendor/github.com/open-policy-agent/opa/types/types.go +++ b/vendor/github.com/open-policy-agent/opa/v1/types/types.go @@ -12,7 +12,7 @@ import ( "sort" "strings" - "github.com/open-policy-agent/opa/util" + "github.com/open-policy-agent/opa/v1/util" ) // Sprint returns the string representation of the type. @@ -675,7 +675,7 @@ func Arity(x Type) int { if !ok { return 0 } - return len(f.FuncArgs().Args) + return f.Arity() } // NewFunction returns a new Function object of the given argument and result types. @@ -723,6 +723,11 @@ func (t *Function) Args() []Type { return cpy } +// Arity returns the number of arguments in the function signature. +func (t *Function) Arity() int { + return len(t.args) +} + // Result returns the function's result type. func (t *Function) Result() Type { return unwrap(t.result) @@ -780,14 +785,15 @@ func (t *Function) Union(other *Function) *Function { return other } - a := t.Args() - b := other.Args() - if len(a) != len(b) { + if t.Arity() != other.Arity() { return nil } - aIsVariadic := t.FuncArgs().Variadic != nil - bIsVariadic := other.FuncArgs().Variadic != nil + tfa := t.FuncArgs() + ofa := other.FuncArgs() + + aIsVariadic := tfa.Variadic != nil + bIsVariadic := ofa.Variadic != nil if aIsVariadic && !bIsVariadic { return nil @@ -795,13 +801,16 @@ func (t *Function) Union(other *Function) *Function { return nil } + a := t.Args() + b := other.Args() + args := make([]Type, len(a)) for i := range a { args[i] = Or(a[i], b[i]) } result := NewFunction(args, Or(t.Result(), other.Result())) - result.variadic = Or(t.FuncArgs().Variadic, other.FuncArgs().Variadic) + result.variadic = Or(tfa.Variadic, ofa.Variadic) return result } diff --git a/vendor/github.com/open-policy-agent/opa/util/backoff.go b/vendor/github.com/open-policy-agent/opa/v1/util/backoff.go similarity index 80% rename from vendor/github.com/open-policy-agent/opa/util/backoff.go rename to vendor/github.com/open-policy-agent/opa/v1/util/backoff.go index 6fbf63ef77..36d57f14e2 100644 --- a/vendor/github.com/open-policy-agent/opa/util/backoff.go +++ b/vendor/github.com/open-policy-agent/opa/v1/util/backoff.go @@ -22,24 +22,24 @@ func init() { // DefaultBackoff returns a delay with an exponential backoff based on the // number of retries. -func DefaultBackoff(base, max float64, retries int) time.Duration { - return Backoff(base, max, .2, 1.6, retries) +func DefaultBackoff(base, maxNS float64, retries int) time.Duration { + return Backoff(base, maxNS, .2, 1.6, retries) } // Backoff returns a delay with an exponential backoff based on the number of // retries. Same algorithm used in gRPC. -func Backoff(base, max, jitter, factor float64, retries int) time.Duration { +func Backoff(base, maxNS, jitter, factor float64, retries int) time.Duration { if retries == 0 { return 0 } - backoff, max := base, max - for backoff < max && retries > 0 { + backoff, maxNS := base, maxNS + for backoff < maxNS && retries > 0 { backoff *= factor retries-- } - if backoff > max { - backoff = max + if backoff > maxNS { + backoff = maxNS } // Randomize backoff delays so that if a cluster of requests start at diff --git a/vendor/github.com/open-policy-agent/opa/util/close.go b/vendor/github.com/open-policy-agent/opa/v1/util/close.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/util/close.go rename to vendor/github.com/open-policy-agent/opa/v1/util/close.go diff --git a/vendor/github.com/open-policy-agent/opa/util/compare.go b/vendor/github.com/open-policy-agent/opa/v1/util/compare.go similarity index 93% rename from vendor/github.com/open-policy-agent/opa/util/compare.go rename to vendor/github.com/open-policy-agent/opa/v1/util/compare.go index 8ae7753690..8775a603dd 100644 --- a/vendor/github.com/open-policy-agent/opa/util/compare.go +++ b/vendor/github.com/open-policy-agent/opa/v1/util/compare.go @@ -8,7 +8,6 @@ import ( "encoding/json" "fmt" "math/big" - "sort" ) // Compare returns 0 if a equals b, -1 if a is less than b, and 1 if b is than a. @@ -99,16 +98,8 @@ func Compare(a, b interface{}) int { case map[string]interface{}: switch b := b.(type) { case map[string]interface{}: - var aKeys []string - for k := range a { - aKeys = append(aKeys, k) - } - var bKeys []string - for k := range b { - bKeys = append(bKeys, k) - } - sort.Strings(aKeys) - sort.Strings(bKeys) + aKeys := KeysSorted(a) + bKeys := KeysSorted(b) aLen := len(aKeys) bLen := len(bKeys) minLen := aLen diff --git a/vendor/github.com/open-policy-agent/opa/util/decoding/context.go b/vendor/github.com/open-policy-agent/opa/v1/util/decoding/context.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/util/decoding/context.go rename to vendor/github.com/open-policy-agent/opa/v1/util/decoding/context.go diff --git a/vendor/github.com/open-policy-agent/opa/util/doc.go b/vendor/github.com/open-policy-agent/opa/v1/util/doc.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/util/doc.go rename to vendor/github.com/open-policy-agent/opa/v1/util/doc.go diff --git a/vendor/github.com/open-policy-agent/opa/util/enumflag.go b/vendor/github.com/open-policy-agent/opa/v1/util/enumflag.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/util/enumflag.go rename to vendor/github.com/open-policy-agent/opa/v1/util/enumflag.go diff --git a/vendor/github.com/open-policy-agent/opa/util/graph.go b/vendor/github.com/open-policy-agent/opa/v1/util/graph.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/util/graph.go rename to vendor/github.com/open-policy-agent/opa/v1/util/graph.go diff --git a/vendor/github.com/open-policy-agent/opa/util/hashmap.go b/vendor/github.com/open-policy-agent/opa/v1/util/hashmap.go similarity index 56% rename from vendor/github.com/open-policy-agent/opa/util/hashmap.go rename to vendor/github.com/open-policy-agent/opa/v1/util/hashmap.go index 8875a6323e..a6c584c570 100644 --- a/vendor/github.com/open-policy-agent/opa/util/hashmap.go +++ b/vendor/github.com/open-policy-agent/opa/v1/util/hashmap.go @@ -12,34 +12,56 @@ import ( // T is a concise way to refer to T. type T interface{} -type hashEntry struct { - k T - v T - next *hashEntry +type hashEntry[K any, V any] struct { + k K + v V + next *hashEntry[K, V] } -// HashMap represents a key/value map. -type HashMap struct { - eq func(T, T) bool - hash func(T) int - table map[int]*hashEntry +// TypedHashMap represents a key/value map. +type TypedHashMap[K any, V any] struct { + keq func(K, K) bool + veq func(V, V) bool + khash func(K) int + vhash func(V) int + def V + table map[int]*hashEntry[K, V] size int } +// NewTypedHashMap returns a new empty TypedHashMap. +func NewTypedHashMap[K any, V any](keq func(K, K) bool, veq func(V, V) bool, khash func(K) int, vhash func(V) int, def V) *TypedHashMap[K, V] { + return &TypedHashMap[K, V]{ + keq: keq, + veq: veq, + khash: khash, + vhash: vhash, + def: def, + table: make(map[int]*hashEntry[K, V]), + size: 0, + } +} + +// HashMap represents a key/value map. +type HashMap = TypedHashMap[T, T] + // NewHashMap returns a new empty HashMap. func NewHashMap(eq func(T, T) bool, hash func(T) int) *HashMap { return &HashMap{ - eq: eq, - hash: hash, - table: make(map[int]*hashEntry), + keq: eq, + veq: eq, + khash: hash, + vhash: hash, + def: nil, + table: make(map[int]*hashEntry[T, T]), size: 0, } } // Copy returns a shallow copy of this HashMap. -func (h *HashMap) Copy() *HashMap { - cpy := NewHashMap(h.eq, h.hash) - h.Iter(func(k, v T) bool { +func (h *TypedHashMap[K, V]) Copy() *TypedHashMap[K, V] { + cpy := NewTypedHashMap[K, V](h.keq, h.veq, h.khash, h.vhash, h.def) + h.Iter(func(k K, v V) bool { cpy.Put(k, v) return false }) @@ -48,36 +70,36 @@ func (h *HashMap) Copy() *HashMap { // Equal returns true if this HashMap equals the other HashMap. // Two hash maps are equal if they contain the same key/value pairs. -func (h *HashMap) Equal(other *HashMap) bool { +func (h *TypedHashMap[K, V]) Equal(other *TypedHashMap[K, V]) bool { if h.Len() != other.Len() { return false } - return !h.Iter(func(k, v T) bool { + return !h.Iter(func(k K, v V) bool { ov, ok := other.Get(k) if !ok { return true } - return !h.eq(v, ov) + return !h.veq(v, ov) }) } // Get returns the value for k. -func (h *HashMap) Get(k T) (T, bool) { - hash := h.hash(k) +func (h *TypedHashMap[K, V]) Get(k K) (V, bool) { + hash := h.khash(k) for entry := h.table[hash]; entry != nil; entry = entry.next { - if h.eq(entry.k, k) { + if h.keq(entry.k, k) { return entry.v, true } } - return nil, false + return h.def, false } // Delete removes the key k. -func (h *HashMap) Delete(k T) { - hash := h.hash(k) - var prev *hashEntry +func (h *TypedHashMap[K, V]) Delete(k K) { + hash := h.khash(k) + var prev *hashEntry[K, V] for entry := h.table[hash]; entry != nil; entry = entry.next { - if h.eq(entry.k, k) { + if h.keq(entry.k, k) { if prev != nil { prev.next = entry.next } else { @@ -91,10 +113,10 @@ func (h *HashMap) Delete(k T) { } // Hash returns the hash code for this hash map. -func (h *HashMap) Hash() int { +func (h *TypedHashMap[K, V]) Hash() int { var hash int - h.Iter(func(k, v T) bool { - hash += h.hash(k) + h.hash(v) + h.Iter(func(k K, v V) bool { + hash += h.khash(k) + h.vhash(v) return false }) return hash @@ -104,7 +126,7 @@ func (h *HashMap) Hash() int { // If the iter function returns true, iteration stops and the return value is true. // If the iter function never returns true, iteration proceeds through all elements // and the return value is false. -func (h *HashMap) Iter(iter func(T, T) bool) bool { +func (h *TypedHashMap[K, V]) Iter(iter func(K, V) bool) bool { for _, entry := range h.table { for ; entry != nil; entry = entry.next { if iter(entry.k, entry.v) { @@ -116,28 +138,28 @@ func (h *HashMap) Iter(iter func(T, T) bool) bool { } // Len returns the current size of this HashMap. -func (h *HashMap) Len() int { +func (h *TypedHashMap[K, V]) Len() int { return h.size } // Put inserts a key/value pair into this HashMap. If the key is already present, the existing // value is overwritten. -func (h *HashMap) Put(k T, v T) { - hash := h.hash(k) +func (h *TypedHashMap[K, V]) Put(k K, v V) { + hash := h.khash(k) head := h.table[hash] for entry := head; entry != nil; entry = entry.next { - if h.eq(entry.k, k) { + if h.keq(entry.k, k) { entry.v = v return } } - h.table[hash] = &hashEntry{k: k, v: v, next: head} + h.table[hash] = &hashEntry[K, V]{k: k, v: v, next: head} h.size++ } -func (h *HashMap) String() string { +func (h *TypedHashMap[K, V]) String() string { var buf []string - h.Iter(func(k T, v T) bool { + h.Iter(func(k K, v V) bool { buf = append(buf, fmt.Sprintf("%v: %v", k, v)) return false }) @@ -147,9 +169,9 @@ func (h *HashMap) String() string { // Update returns a new HashMap with elements from the other HashMap put into this HashMap. // If the other HashMap contains elements with the same key as this HashMap, the value // from the other HashMap overwrites the value from this HashMap. -func (h *HashMap) Update(other *HashMap) *HashMap { +func (h *TypedHashMap[K, V]) Update(other *TypedHashMap[K, V]) *TypedHashMap[K, V] { updated := h.Copy() - other.Iter(func(k, v T) bool { + other.Iter(func(k K, v V) bool { updated.Put(k, v) return false }) diff --git a/vendor/github.com/open-policy-agent/opa/util/json.go b/vendor/github.com/open-policy-agent/opa/v1/util/json.go similarity index 93% rename from vendor/github.com/open-policy-agent/opa/util/json.go rename to vendor/github.com/open-policy-agent/opa/v1/util/json.go index 4f1e14513f..5a4e460b61 100644 --- a/vendor/github.com/open-policy-agent/opa/util/json.go +++ b/vendor/github.com/open-policy-agent/opa/v1/util/json.go @@ -13,7 +13,7 @@ import ( "sigs.k8s.io/yaml" - "github.com/open-policy-agent/opa/loader/extension" + "github.com/open-policy-agent/opa/v1/loader/extension" ) // UnmarshalJSON parses the JSON encoded data and stores the result in the value @@ -114,6 +114,10 @@ func Reference(x interface{}) *interface{} { // Unmarshal decodes a YAML, JSON or JSON extension value into the specified type. func Unmarshal(bs []byte, v interface{}) error { + if len(bs) > 2 && bs[0] == 0xef && bs[1] == 0xbb && bs[2] == 0xbf { + bs = bs[3:] // Strip UTF-8 BOM, see https://www.rfc-editor.org/rfc/rfc8259#section-8.1 + } + if json.Valid(bs) { return unmarshalJSON(bs, v, false) } diff --git a/vendor/github.com/open-policy-agent/opa/v1/util/maps.go b/vendor/github.com/open-policy-agent/opa/v1/util/maps.go new file mode 100644 index 0000000000..c56fbe98ac --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/v1/util/maps.go @@ -0,0 +1,34 @@ +package util + +import ( + "cmp" + "slices" +) + +// Keys returns a slice of keys from any map. +func Keys[M ~map[K]V, K comparable, V any](m M) []K { + r := make([]K, 0, len(m)) + for k := range m { + r = append(r, k) + } + return r +} + +// KeysSorted returns a slice of keys from any map, sorted in ascending order. +func KeysSorted[M ~map[K]V, K cmp.Ordered, V any](m M) []K { + r := make([]K, 0, len(m)) + for k := range m { + r = append(r, k) + } + slices.Sort(r) + return r +} + +// Values returns a slice of values from any map. Copied from golang.org/x/exp/maps. +func Values[M ~map[K]V, K comparable, V any](m M) []V { + r := make([]V, 0, len(m)) + for _, v := range m { + r = append(r, v) + } + return r +} diff --git a/vendor/github.com/open-policy-agent/opa/v1/util/performance.go b/vendor/github.com/open-policy-agent/opa/v1/util/performance.go new file mode 100644 index 0000000000..b24b49a1d7 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/v1/util/performance.go @@ -0,0 +1,64 @@ +package util + +import ( + "math" + "slices" + "unsafe" +) + +// NewPtrSlice returns a slice of pointers to T with length n, +// with only 2 allocations performed no matter the size of n. +// See: +// https://gist.github.com/CAFxX/e96e8a5c3841d152f16d266a1fe7f8bd#slices-of-pointers +func NewPtrSlice[T any](n int) []*T { + return GrowPtrSlice[T](nil, n) +} + +// GrowPtrSlice appends n elements to the slice, each pointing to +// a newly-allocated T. The resulting slice has length equal to len(s)+n. +// +// It performs at most 2 allocations, regardless of n. +func GrowPtrSlice[T any](s []*T, n int) []*T { + s = slices.Grow(s, n) + p := make([]T, n) + for i := 0; i < n; i++ { + s = append(s, &p[i]) + } + return s +} + +// Allocation free conversion from []byte to string (unsafe) +// Note that the byte slice must not be modified after conversion +func ByteSliceToString(bs []byte) string { + return unsafe.String(unsafe.SliceData(bs), len(bs)) +} + +// Allocation free conversion from ~string to []byte (unsafe) +// Note that the byte slice must not be modified after conversion +func StringToByteSlice[T ~string](s T) []byte { + return unsafe.Slice(unsafe.StringData(string(s)), len(s)) +} + +// NumDigitsInt returns the number of digits in n. +// This is useful for pre-allocating buffers for string conversion. +func NumDigitsInt(n int) int { + if n == 0 { + return 1 + } + + if n < 0 { + n = -n + } + + return int(math.Log10(float64(n))) + 1 +} + +// NumDigitsUint returns the number of digits in n. +// This is useful for pre-allocating buffers for string conversion. +func NumDigitsUint(n uint64) int { + if n == 0 { + return 1 + } + + return int(math.Log10(float64(n))) + 1 +} diff --git a/vendor/github.com/open-policy-agent/opa/util/queue.go b/vendor/github.com/open-policy-agent/opa/v1/util/queue.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/util/queue.go rename to vendor/github.com/open-policy-agent/opa/v1/util/queue.go diff --git a/vendor/github.com/open-policy-agent/opa/util/read_gzip_body.go b/vendor/github.com/open-policy-agent/opa/v1/util/read_gzip_body.go similarity index 98% rename from vendor/github.com/open-policy-agent/opa/util/read_gzip_body.go rename to vendor/github.com/open-policy-agent/opa/v1/util/read_gzip_body.go index 217638b363..74bca7263a 100644 --- a/vendor/github.com/open-policy-agent/opa/util/read_gzip_body.go +++ b/vendor/github.com/open-policy-agent/opa/v1/util/read_gzip_body.go @@ -10,7 +10,7 @@ import ( "strings" "sync" - "github.com/open-policy-agent/opa/util/decoding" + "github.com/open-policy-agent/opa/v1/util/decoding" ) var gzipReaderPool = sync.Pool{ diff --git a/vendor/github.com/open-policy-agent/opa/v1/util/time.go b/vendor/github.com/open-policy-agent/opa/v1/util/time.go new file mode 100644 index 0000000000..93ef03939a --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/v1/util/time.go @@ -0,0 +1,48 @@ +package util + +import "time" + +// TimerWithCancel exists because of memory leaks when using +// time.After in select statements. Instead, we now manually create timers, +// wait on them, and manually free them. +// +// See this for more details: +// https://www.arangodb.com/2020/09/a-story-of-a-memory-leak-in-go-how-to-properly-use-time-after/ +// +// Note: This issue is fixed in Go 1.23, but this fix helps us until then. +// +// Warning: the cancel cannot be done concurrent to reading, everything should +// work in the same goroutine. +// +// Example: +// +// for retries := 0; true; retries++ { +// +// ...main logic... +// +// timer, cancel := utils.TimerWithCancel(utils.Backoff(retries)) +// select { +// case <-ctx.Done(): +// cancel() +// return ctx.Err() +// case <-timer.C: +// continue +// } +// } +func TimerWithCancel(delay time.Duration) (*time.Timer, func()) { + timer := time.NewTimer(delay) + + return timer, func() { + // Note: The Stop function returns: + // - true: if the timer is active. (no draining required) + // - false: if the timer was already stopped or fired/expired. + // In this case the channel should be drained to prevent memory + // leaks only if it is not empty. + // This operation is safe only if the cancel function is + // used in same goroutine. Concurrent reading or canceling may + // cause deadlock. + if !timer.Stop() && len(timer.C) > 0 { + <-timer.C + } + } +} diff --git a/vendor/github.com/open-policy-agent/opa/util/wait.go b/vendor/github.com/open-policy-agent/opa/v1/util/wait.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/util/wait.go rename to vendor/github.com/open-policy-agent/opa/v1/util/wait.go diff --git a/vendor/github.com/open-policy-agent/opa/version/version.go b/vendor/github.com/open-policy-agent/opa/v1/version/version.go similarity index 97% rename from vendor/github.com/open-policy-agent/opa/version/version.go rename to vendor/github.com/open-policy-agent/opa/v1/version/version.go index 7dece01579..0af828f888 100644 --- a/vendor/github.com/open-policy-agent/opa/version/version.go +++ b/vendor/github.com/open-policy-agent/opa/v1/version/version.go @@ -11,7 +11,7 @@ import ( ) // Version is the canonical version of OPA. -var Version = "0.68.0" +var Version = "1.1.0" // GoVersion is the version of Go this was built with var GoVersion = runtime.Version() diff --git a/vendor/github.com/open-policy-agent/opa/version/wasm.go b/vendor/github.com/open-policy-agent/opa/v1/version/wasm.go similarity index 100% rename from vendor/github.com/open-policy-agent/opa/version/wasm.go rename to vendor/github.com/open-policy-agent/opa/v1/version/wasm.go diff --git a/vendor/github.com/pelletier/go-toml/v2/.goreleaser.yaml b/vendor/github.com/pelletier/go-toml/v2/.goreleaser.yaml index 1d8b69e65e..ec52857a3e 100644 --- a/vendor/github.com/pelletier/go-toml/v2/.goreleaser.yaml +++ b/vendor/github.com/pelletier/go-toml/v2/.goreleaser.yaml @@ -1,3 +1,4 @@ +version: 2 before: hooks: - go mod tidy diff --git a/vendor/github.com/pelletier/go-toml/v2/README.md b/vendor/github.com/pelletier/go-toml/v2/README.md index d964b25fe1..0755e55642 100644 --- a/vendor/github.com/pelletier/go-toml/v2/README.md +++ b/vendor/github.com/pelletier/go-toml/v2/README.md @@ -565,7 +565,7 @@ complete solutions exist out there. ## Versioning -Expect for parts explicitely marked otherwise, go-toml follows [Semantic +Expect for parts explicitly marked otherwise, go-toml follows [Semantic Versioning](https://semver.org). The supported version of [TOML](https://github.com/toml-lang/toml) is indicated at the beginning of this document. The last two major versions of Go are supported (see [Go Release diff --git a/vendor/github.com/pelletier/go-toml/v2/marshaler.go b/vendor/github.com/pelletier/go-toml/v2/marshaler.go index 7f4e20c128..161acd9343 100644 --- a/vendor/github.com/pelletier/go-toml/v2/marshaler.go +++ b/vendor/github.com/pelletier/go-toml/v2/marshaler.go @@ -8,7 +8,7 @@ import ( "io" "math" "reflect" - "sort" + "slices" "strconv" "strings" "time" @@ -280,7 +280,7 @@ func (enc *Encoder) encode(b []byte, ctx encoderCtx, v reflect.Value) ([]byte, e } hasTextMarshaler := v.Type().Implements(textMarshalerType) - if hasTextMarshaler || (v.CanAddr() && reflect.PtrTo(v.Type()).Implements(textMarshalerType)) { + if hasTextMarshaler || (v.CanAddr() && reflect.PointerTo(v.Type()).Implements(textMarshalerType)) { if !hasTextMarshaler { v = v.Addr() } @@ -631,6 +631,18 @@ func (enc *Encoder) keyToString(k reflect.Value) (string, error) { return "", fmt.Errorf("toml: error marshalling key %v from text: %w", k, err) } return string(keyB), nil + + case keyType.Kind() == reflect.Int || keyType.Kind() == reflect.Int8 || keyType.Kind() == reflect.Int16 || keyType.Kind() == reflect.Int32 || keyType.Kind() == reflect.Int64: + return strconv.FormatInt(k.Int(), 10), nil + + case keyType.Kind() == reflect.Uint || keyType.Kind() == reflect.Uint8 || keyType.Kind() == reflect.Uint16 || keyType.Kind() == reflect.Uint32 || keyType.Kind() == reflect.Uint64: + return strconv.FormatUint(k.Uint(), 10), nil + + case keyType.Kind() == reflect.Float32: + return strconv.FormatFloat(k.Float(), 'f', -1, 32), nil + + case keyType.Kind() == reflect.Float64: + return strconv.FormatFloat(k.Float(), 'f', -1, 64), nil } return "", fmt.Errorf("toml: type %s is not supported as a map key", keyType.Kind()) } @@ -668,8 +680,8 @@ func (enc *Encoder) encodeMap(b []byte, ctx encoderCtx, v reflect.Value) ([]byte } func sortEntriesByKey(e []entry) { - sort.Slice(e, func(i, j int) bool { - return e[i].Key < e[j].Key + slices.SortFunc(e, func(a, b entry) int { + return strings.Compare(a.Key, b.Key) }) } @@ -732,7 +744,7 @@ func walkStruct(ctx encoderCtx, t *table, v reflect.Value) { if fieldType.Anonymous { if fieldType.Type.Kind() == reflect.Struct { walkStruct(ctx, t, f) - } else if fieldType.Type.Kind() == reflect.Pointer && !f.IsNil() && f.Elem().Kind() == reflect.Struct { + } else if fieldType.Type.Kind() == reflect.Ptr && !f.IsNil() && f.Elem().Kind() == reflect.Struct { walkStruct(ctx, t, f.Elem()) } continue @@ -951,7 +963,7 @@ func willConvertToTable(ctx encoderCtx, v reflect.Value) bool { if !v.IsValid() { return false } - if v.Type() == timeType || v.Type().Implements(textMarshalerType) || (v.Kind() != reflect.Ptr && v.CanAddr() && reflect.PtrTo(v.Type()).Implements(textMarshalerType)) { + if v.Type() == timeType || v.Type().Implements(textMarshalerType) || (v.Kind() != reflect.Ptr && v.CanAddr() && reflect.PointerTo(v.Type()).Implements(textMarshalerType)) { return false } diff --git a/vendor/github.com/pelletier/go-toml/v2/unmarshaler.go b/vendor/github.com/pelletier/go-toml/v2/unmarshaler.go index 98231bae65..c3df8bee1c 100644 --- a/vendor/github.com/pelletier/go-toml/v2/unmarshaler.go +++ b/vendor/github.com/pelletier/go-toml/v2/unmarshaler.go @@ -5,9 +5,9 @@ import ( "errors" "fmt" "io" - "io/ioutil" "math" "reflect" + "strconv" "strings" "sync/atomic" "time" @@ -21,10 +21,8 @@ import ( // // It is a shortcut for Decoder.Decode() with the default options. func Unmarshal(data []byte, v interface{}) error { - p := unstable.Parser{} - p.Reset(data) - d := decoder{p: &p} - + d := decoder{} + d.p.Reset(data) return d.FromParser(v) } @@ -117,27 +115,25 @@ func (d *Decoder) EnableUnmarshalerInterface() *Decoder { // Inline Table -> same as Table // Array of Tables -> same as Array and Table func (d *Decoder) Decode(v interface{}) error { - b, err := ioutil.ReadAll(d.r) + b, err := io.ReadAll(d.r) if err != nil { return fmt.Errorf("toml: %w", err) } - p := unstable.Parser{} - p.Reset(b) dec := decoder{ - p: &p, strict: strict{ Enabled: d.strict, }, unmarshalerInterface: d.unmarshalerInterface, } + dec.p.Reset(b) return dec.FromParser(v) } type decoder struct { // Which parser instance in use for this decoding session. - p *unstable.Parser + p unstable.Parser // Flag indicating that the current expression is stashed. // If set to true, calling nextExpr will not actually pull a new expression @@ -1078,12 +1074,39 @@ func (d *decoder) keyFromData(keyType reflect.Type, data []byte) (reflect.Value, } return mk, nil - case reflect.PtrTo(keyType).Implements(textUnmarshalerType): + case reflect.PointerTo(keyType).Implements(textUnmarshalerType): mk := reflect.New(keyType) if err := mk.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil { return reflect.Value{}, fmt.Errorf("toml: error unmarshalling key type %s from text: %w", stringType, err) } return mk.Elem(), nil + + case keyType.Kind() == reflect.Int || keyType.Kind() == reflect.Int8 || keyType.Kind() == reflect.Int16 || keyType.Kind() == reflect.Int32 || keyType.Kind() == reflect.Int64: + key, err := strconv.ParseInt(string(data), 10, 64) + if err != nil { + return reflect.Value{}, fmt.Errorf("toml: error parsing key of type %s from integer: %w", stringType, err) + } + return reflect.ValueOf(key).Convert(keyType), nil + case keyType.Kind() == reflect.Uint || keyType.Kind() == reflect.Uint8 || keyType.Kind() == reflect.Uint16 || keyType.Kind() == reflect.Uint32 || keyType.Kind() == reflect.Uint64: + key, err := strconv.ParseUint(string(data), 10, 64) + if err != nil { + return reflect.Value{}, fmt.Errorf("toml: error parsing key of type %s from unsigned integer: %w", stringType, err) + } + return reflect.ValueOf(key).Convert(keyType), nil + + case keyType.Kind() == reflect.Float32: + key, err := strconv.ParseFloat(string(data), 32) + if err != nil { + return reflect.Value{}, fmt.Errorf("toml: error parsing key of type %s from float: %w", stringType, err) + } + return reflect.ValueOf(float32(key)), nil + + case keyType.Kind() == reflect.Float64: + key, err := strconv.ParseFloat(string(data), 64) + if err != nil { + return reflect.Value{}, fmt.Errorf("toml: error parsing key of type %s from float: %w", stringType, err) + } + return reflect.ValueOf(float64(key)), nil } return reflect.Value{}, fmt.Errorf("toml: cannot convert map key of type %s to expected type %s", stringType, keyType) } diff --git a/vendor/github.com/protocolbuffers/txtpbfmt/ast/ast.go b/vendor/github.com/protocolbuffers/txtpbfmt/ast/ast.go index 489e9b760b..e673cffa58 100644 --- a/vendor/github.com/protocolbuffers/txtpbfmt/ast/ast.go +++ b/vendor/github.com/protocolbuffers/txtpbfmt/ast/ast.go @@ -71,6 +71,12 @@ type Node struct { PostValuesComments []string // Whether the braces used for the children of this node are curly braces or angle brackets. IsAngleBracket bool + // If this is not empty, it means that formatting was disabled for this node and it contains the + // raw, unformatted node string. + Raw string + // Used when we want to break between the field name and values when a + // single-line node exceeds the requested wrap column. + PutSingleValueOnNextLine bool } // NodeLess is a sorting function that compares two *Nodes, possibly using the parent Node @@ -207,11 +213,18 @@ func (n *Node) getChildValue(field string) *Value { return nil } -// IsCommentOnly returns true if this is a comment-only node. +// IsCommentOnly returns true if this is a comment-only node. Even a node that +// only contains a blank line is considered a comment-only node in the sense +// that it has no proto content. func (n *Node) IsCommentOnly() bool { return n.Name == "" && n.Children == nil } +// IsBlankLine returns true if this is a blank line node. +func (n *Node) IsBlankLine() bool { + return n.IsCommentOnly() && len(n.PreComments) == 1 && n.PreComments[0] == "" +} + type fixData struct { inline bool } @@ -291,6 +304,13 @@ func (v *Value) fix() fixData { } } +// SortValues sorts values by their value. +func SortValues(values []*Value) { + sort.SliceStable(values, func(i, j int) bool { + return values[i].Value < values[j].Value + }) +} + // GetFromPath returns all nodes with a given string path in the parse tree. See ast_test.go for examples. func GetFromPath(nodes []*Node, path []string) []*Node { if len(path) == 0 { diff --git a/vendor/github.com/protocolbuffers/txtpbfmt/parser/parser.go b/vendor/github.com/protocolbuffers/txtpbfmt/parser/parser.go index 37c0926444..ffab187e17 100644 --- a/vendor/github.com/protocolbuffers/txtpbfmt/parser/parser.go +++ b/vendor/github.com/protocolbuffers/txtpbfmt/parser/parser.go @@ -1,6 +1,5 @@ // Package parser edits text proto files, applies standard formatting // and preserves comments. -// See also: https://github.com/golang/protobuf/blob/master/proto/text_parser.go // // To disable a specific file from getting formatted, add '# txtpbfmt: disable' // at the top of the file. @@ -74,6 +73,9 @@ type Config struct { // Should not be used with other Wrap* options. WrapStringsAfterNewlines bool + // Wrap strictly at the column instead of a word boundary. + WrapStringsWithoutWordwrap bool + // Whether angle brackets used instead of curly braces should be preserved // when outputting a formatted textproto. PreserveAngleBrackets bool @@ -206,7 +208,7 @@ func sameLineBrackets(in []byte, allowTripleQuotedStrings bool) (map[int]bool, e continue } if len(open) == 0 { - return nil, fmt.Errorf("too many '}' or '>' at index %d", i) + return nil, fmt.Errorf("too many '}' or '>' at line %d, index %d", line, i) } last := len(open) - 1 br := open[last] @@ -302,8 +304,8 @@ func removeDeleted(nodes []*ast.Node) []*ast.Node { } var ( - spaceSeparators = []byte(" \t\n") - valueSeparators = []byte(" \t\n{}:,[]<>;#") + spaceSeparators = []byte(" \t\n\r") + valueSeparators = []byte(" \t\n\r{}:,[]<>;#") ) // Parse returns a tree representation of a textproto file. @@ -342,7 +344,7 @@ func parseWithMetaCommentConfig(in []byte, c Config) ([]*ast.Node, error) { if err := wrapStrings(nodes, 0, c); err != nil { return nil, err } - if err := sortAndFilterNodes( /*parent=*/ nil, nodes, nodeSortFunction(c), nodeFilterFunction(c)); err != nil { + if err := sortAndFilterNodes( /*parent=*/ nil, nodes, nodeSortFunction(c), nodeFilterFunction(c), valuesSortFunction(c)); err != nil { return nil, err } return nodes, nil @@ -399,6 +401,10 @@ func addToConfig(metaComment string, c *Config) error { c.WrapHTMLStrings = true case "wrap_strings_after_newlines": c.WrapStringsAfterNewlines = true + case "wrap_strings_without_wordwrap": + c.WrapStringsWithoutWordwrap = true + case "on": // This doesn't change the overall config. + case "off": // This doesn't change the overall config. default: return fmt.Errorf("unrecognized MetaComment: %s", metaComment) } @@ -540,11 +546,19 @@ func (p *parser) position() ast.Position { } } +// Modifies the parser by rewinding to the given position. +// A position can be snapshotted by using the `position()` function above. +func (p *parser) rollbackPosition(pos ast.Position) { + p.index = int(pos.Byte) + p.line = int(pos.Line) + p.column = int(pos.Column) +} + func (p *parser) consumeOptionalSeparator() error { if p.index > 0 && !p.isBlankSep(p.index-1) { // If an unnamed field immediately follows non-whitespace, we require a separator character first (key_one:,:value_two instead of key_one::value_two) if p.consume(':') { - return fmt.Errorf("parser encountered unexpected : character (should be whitespace, or a ,; separator)") + return fmt.Errorf("parser encountered unexpected character ':' (should be whitespace, ',', or ';')") } } @@ -567,24 +581,33 @@ func (p *parser) parse(isRoot bool) (result []*ast.Node, endPos ast.Position, er return nil, ast.Position{}, err } + // p.parse is often invoked with the index pointing at the newline character + // after the previous item. We should still report that this item starts in + // the next line. + p.consume('\n') startPos := p.position() - if p.nextInputIs('\n') { - // p.parse is often invoked with the index pointing at the - // newline character after the previous item. - // We should still report that this item starts in the next line. - startPos.Byte++ - startPos.Line++ - startPos.Column = 1 + + fmtDisabled, err := p.readFormatterDisabledBlock() + if err != nil { + return nil, startPos, err + } + if len(fmtDisabled) > 0 { + res = append(res, &ast.Node{ + Start: startPos, + Raw: fmtDisabled, + }) + continue } // Read PreComments. comments, blankLines := p.skipWhiteSpaceAndReadComments(true /* multiLine */) // Handle blank lines. - if blankLines > 1 { + if blankLines > 0 { if p.config.infoLevel() { p.config.infof("blankLines: %v", blankLines) } + // Here we collapse the leading blank lines into one blank line. comments = append([]string{""}, comments...) } @@ -763,9 +786,7 @@ func (p *parser) parse(isRoot bool) (result []*ast.Node, endPos ast.Position, er } } else { // Rewind comments. - p.index = int(previousPos.Byte) - p.line = int(previousPos.Line) - p.column = int(previousPos.Column) + p.rollbackPosition(previousPos) // Handle Values. nd.Values, err = p.readValues() if err != nil { @@ -821,18 +842,67 @@ func (p *parser) readContinuousBlocksOfComments() []string { return preComments } +// Returns the exact text within the block flanked by "# txtpbfmt: off" and "# txtpbfmt: on". +// The 'off' directive must be on its own line, and it cannot be preceded by a comment line. Any +// preceding whitespace on this line and up to one blank line will be retained. +// The 'on' directive must followed by a line break. Only full nodes of a AST can be +// within this block. Partially disabled sections, like just the first line of a for loop without +// body or closing brace, are not supported. Value lists are not supported. No parsing happens +// within this block, and as parsing errors will be ignored, please exercise caution. +func (p *parser) readFormatterDisabledBlock() (string, error) { + previousPos := p.position() + start := p.index + for p.index < p.length && p.isBlankSep(p.index) { + if p.consume('\n') { + // Include up to one blank line before the 'off' directive. + start = p.index - 1 + } else if p.consume(' ') { + // Do nothing. Side-effect is to advance p.index. + } else if p.consume('\t') { + // Do nothing. Side-effect is to advance p.index. + } + } + offStart := p.position() + if !p.consumeString("# txtpbfmt: off") { + // Directive not found. Rollback to start. + p.rollbackPosition(previousPos) + return "", nil + } + if !p.consume('\n') { + return "", fmt.Errorf("txtpbfmt off should be followed by newline at %s", p.errorContext()) + } + for ; p.index < p.length; p.index++ { + if p.consumeString("# txtpbfmt: on") { + if !p.consume('\n') { + return "", fmt.Errorf("txtpbfmt on should be followed by newline at %s", p.errorContext()) + } + // Retain up to one blank line. + p.consume('\n') + return string(p.in[start:p.index]), nil + } + } + // We reached the end of the file without finding the 'on' directive. + p.rollbackPosition(offStart) + return "", fmt.Errorf("unterminated txtpbfmt off at %s", p.errorContext()) +} + // skipWhiteSpaceAndReadComments has multiple cases: // - (1) reading a block of comments followed by a blank line // - (2) reading a block of comments followed by non-blank content -// - (3) reading the inline comments between the current char and the end of the -// current line +// - (3) reading the inline comments between the current char and the end of +// the current line // -// Lines of comments and number of blank lines will be returned. +// In both cases (1) and (2), there can also be blank lines before the comment +// starts. +// +// Lines of comments and number of blank lines before the comment will be +// returned. If there is no comment, the returned slice will be empty. func (p *parser) skipWhiteSpaceAndReadComments(multiLine bool) ([]string, int) { i := p.index var foundComment, insideComment bool commentBegin := 0 var comments []string + // Number of blanks lines *before* the comment (if any) starts. blankLines := 0 for ; i < p.length; i++ { if p.in[i] == '#' && !insideComment { @@ -945,9 +1015,7 @@ func (p *parser) readValues() ([]*ast.Value, error) { } if previousPos != (ast.Position{}) { // Rewind comments. - p.index = int(previousPos.Byte) - p.line = int(previousPos.Line) - p.column = int(previousPos.Column) + p.rollbackPosition(previousPos) } else { i := p.index // Handle other values. @@ -1048,7 +1116,10 @@ type NodeSortFunction func(parent *ast.Node, nodes []*ast.Node) error // NodeFilterFunction filters the given nodes. type NodeFilterFunction func(nodes []*ast.Node) -func sortAndFilterNodes(parent *ast.Node, nodes []*ast.Node, sortFunction NodeSortFunction, filterFunction NodeFilterFunction) error { +// ValuesSortFunction sorts the given values. +type ValuesSortFunction func(values []*ast.Value) + +func sortAndFilterNodes(parent *ast.Node, nodes []*ast.Node, sortFunction NodeSortFunction, filterFunction NodeFilterFunction, valuesSortFunction ValuesSortFunction) error { if len(nodes) == 0 { return nil } @@ -1056,10 +1127,13 @@ func sortAndFilterNodes(parent *ast.Node, nodes []*ast.Node, sortFunction NodeSo filterFunction(nodes) } for _, nd := range nodes { - err := sortAndFilterNodes(nd, nd.Children, sortFunction, filterFunction) + err := sortAndFilterNodes(nd, nd.Children, sortFunction, filterFunction, valuesSortFunction) if err != nil { return err } + if valuesSortFunction != nil && nd.ValuesAsList { + valuesSortFunction(nd.Values) + } } if sortFunction != nil { return sortFunction(parent, nodes) @@ -1074,7 +1148,7 @@ func RemoveDuplicates(nodes []*ast.Node) { } seen := make(map[nameAndValue]bool) for _, nd := range nodes { - if seen != nil && len(nd.Values) == 1 { + if len(nd.Values) == 1 { key := nameAndValue{nd.Name, nd.Values[0].Value} if _, value := seen[key]; value { // Name-Value pair found in the same nesting level, deleting. @@ -1134,7 +1208,7 @@ func needsWrappingAtColumn(nd *ast.Node, depth int, c Config) bool { // Only wrap strings return false } - if len(v.Value) > maxLength { + if len(v.Value) > maxLength || c.WrapStringsWithoutWordwrap { return true } } @@ -1148,17 +1222,41 @@ func wrapLinesAtColumn(nd *ast.Node, depth int, c Config) error { // This function looks at the unquoted ast.Value.Value string (i.e., with each Value's wrapping // quote chars removed). We need to remove these quotes, since otherwise they'll be re-flowed into // the body of the text. - lengthBuffer := 4 // Even at depth 0 we have a 2-space indent and a pair of quotes + const lengthBuffer = 4 // Even at depth 0 we have a 2-space indent and a pair of quotes maxLength := c.WrapStringsAtColumn - lengthBuffer - (depth * len(indentSpaces)) - str, err := unquote.Raw(nd) + str, quote, err := unquote.Raw(nd) if err != nil { return fmt.Errorf("skipping string wrapping on node %q (error unquoting string): %v", nd.Name, err) } - // Remove one from the max length since a trailing space may be added below. - wrappedStr := wordwrap.WrapString(str, uint(maxLength)-1) - lines := strings.Split(wrappedStr, "\n") + var lines []string + if c.WrapStringsWithoutWordwrap { + // https://protobuf.dev/reference/protobuf/textformat-spec/#string. + // String literals can contain octal, hex, unicode, and C-style escape + // sequences: \a \b \f \n \r \t \v \? \' \"\ ? \\ + re := regexp.MustCompile(`\\[abfnrtv?\\'"]` + + `|\\[0-7]{1,3}` + + `|\\x[0-9a-fA-F]{1,2}` + + `|\\u[0-9a-fA-F]{4}` + + `|\\U000[0-9a-fA-F]{5}` + + `|\\U0010[0-9a-fA-F]{4}` + + `|.`) + var line strings.Builder + for _, t := range re.FindAllString(str, -1) { + if line.Len()+len(t) > maxLength { + lines = append(lines, line.String()) + line.Reset() + } + line.WriteString(t) + } + lines = append(lines, line.String()) + } else { + // Remove one from the max length since a trailing space may be added below. + wrappedStr := wordwrap.WrapString(str, uint(maxLength)-1) + lines = strings.Split(wrappedStr, "\n") + } + newValues := make([]*ast.Value, 0, len(lines)) // The Value objects have more than just the string in them. They also have any leading and // trailing comments. To maintain these comments we recycle the existing Value objects if @@ -1172,10 +1270,34 @@ func wrapLinesAtColumn(nd *ast.Node, depth int, c Config) error { } else { v = &ast.Value{} } - if i < len(lines)-1 { + + if !c.WrapStringsWithoutWordwrap && i < len(lines)-1 { line = line + " " } - v.Value = fmt.Sprintf(`"%s"`, line) + + if c.WrapStringsWithoutWordwrap { + var lineLength = len(line) + if v.InlineComment != "" { + lineLength += len(indentSpaces) + len(v.InlineComment) + } + // field name and field value are inlined for single strings, adjust for that. + if i == 0 && len(lines) == 1 { + lineLength += len(nd.Name) + } + if lineLength > maxLength { + // If there's an inline comment, promote it to a pre-comment which will + // emit a newline. + if v.InlineComment != "" { + v.PreComments = append(v.PreComments, v.InlineComment) + v.InlineComment = "" + } else if i == 0 && len(v.PreComments) == 0 { + // It's too long and we don't have any comments. + nd.PutSingleValueOnNextLine = true + } + } + } + + v.Value = fmt.Sprintf(`%c%s%c`, quote, line, quote) newValues = append(newValues, v) } @@ -1215,7 +1337,7 @@ func needsWrappingAfterNewlines(nd *ast.Node, c Config) bool { // then wrap the string so each line ends with a newline. // Wraps only the current Node (does not recurse into Children). func wrapLinesAfterNewlines(nd *ast.Node, c Config) error { - str, err := unquote.Raw(nd) + str, quote, err := unquote.Raw(nd) if err != nil { return fmt.Errorf("skipping string wrapping on node %q (error unquoting string): %v", nd.Name, err) } @@ -1237,7 +1359,7 @@ func wrapLinesAfterNewlines(nd *ast.Node, c Config) error { } else { v = &ast.Value{} } - v.Value = fmt.Sprintf(`"%s"`, line) + v.Value = fmt.Sprintf(`%c%s%c`, quote, line, quote) newValues = append(newValues, v) } @@ -1422,6 +1544,13 @@ func nodeFilterFunction(c Config) NodeFilterFunction { return nil } +func valuesSortFunction(c Config) ValuesSortFunction { + if c.SortRepeatedFieldsByContent { + return ast.SortValues + } + return nil +} + func getNodePriorityForByFieldOrder(parent, node *ast.Node, name string, priorities map[string]int, unsortedCollector UnsortedFieldCollectorFunc) *int { if parent != nil && parent.Name != name { return nil @@ -1494,6 +1623,10 @@ func (f formatter) writeNodes(nodes []*ast.Node, depth int, isSameLine, asListIt } for index, nd := range nodes { + if len(nd.Raw) > 0 { + f.WriteString(nd.Raw) + continue + } for _, comment := range nd.PreComments { if len(comment) == 0 { if !(depth == 0 && index == 0) { @@ -1527,7 +1660,11 @@ func (f formatter) writeNodes(nodes []*ast.Node, depth int, isSameLine, asListIt // metadata: { ... } // In other cases, there is a newline right after the colon, so no space required. if nd.Children != nil || (len(nd.Values) == 1 && len(nd.Values[0].PreComments) == 0) || nd.ValuesAsList { - f.WriteString(" ") + if nd.PutSingleValueOnNextLine { + f.WriteString("\n" + indent + indentSpaces) + } else { + f.WriteString(" ") + } } } @@ -1536,6 +1673,7 @@ func (f formatter) writeNodes(nodes []*ast.Node, depth int, isSameLine, asListIt } else if len(nd.Values) > 0 { f.writeValues(nd, nd.Values, indent+indentSpaces) } + if nd.Children != nil { // Also for 0 Children. if nd.ChildrenAsList { f.writeChildrenAsListItems(nd.Children, depth+1, isSameLine || nd.ChildrenSameLine) diff --git a/vendor/github.com/protocolbuffers/txtpbfmt/unquote/unquote.go b/vendor/github.com/protocolbuffers/txtpbfmt/unquote/unquote.go index 2f6b85bb9a..1a59436d35 100644 --- a/vendor/github.com/protocolbuffers/txtpbfmt/unquote/unquote.go +++ b/vendor/github.com/protocolbuffers/txtpbfmt/unquote/unquote.go @@ -11,28 +11,33 @@ import ( "github.com/protocolbuffers/txtpbfmt/ast" ) -// Unquote returns the value of the string node. +// Unquote returns the value of the string node and the rune used to quote it. // Calling Unquote on non-string node doesn't panic, but is otherwise undefined. -func Unquote(n *ast.Node) (string, error) { +func Unquote(n *ast.Node) (string, rune, error) { return unquoteValues(n.Values, unquote) } -// Raw returns the raw value of the string node, with string escapes left in place. +// Raw returns the raw value of the string node and the rune used to quote it, with string escapes +// left in place. // Calling UnquoteRaw on non-string node doesn't panic, but is otherwise undefined. -func Raw(n *ast.Node) (string, error) { +func Raw(n *ast.Node) (string, rune, error) { return unquoteValues(n.Values, unquoteRaw) } -func unquoteValues(values []*ast.Value, unquoter func(string) (string, error)) (string, error) { +func unquoteValues(values []*ast.Value, unquoter func(string) (string, rune, error)) (string, rune, error) { var ret strings.Builder + firstQuote := rune(0) for _, v := range values { - uq, err := unquoter(v.Value) + uq, quote, err := unquoter(v.Value) + if firstQuote == rune(0) { + firstQuote = quote + } if err != nil { - return "", err + return "", rune(0), err } ret.WriteString(uq) } - return ret.String(), nil + return ret.String(), firstQuote, nil } // Returns the quote rune used in the given string (' or "). Returns an error if the string doesn't @@ -51,20 +56,21 @@ func quoteRune(s string) (rune, error) { return rune(quote), nil } -func unquote(s string) (string, error) { +func unquote(s string) (string, rune, error) { quote, err := quoteRune(s) if err != nil { - return "", err + return "", rune(0), err } - return unquoteC(s[1:len(s)-1], quote) + unquoted, err := unquoteC(s[1:len(s)-1], quote) + return unquoted, quote, err } -func unquoteRaw(s string) (string, error) { - _, err := quoteRune(s) // Trigger validation, which guarantees this is a quote-wrapped string. +func unquoteRaw(s string) (string, rune, error) { + quote, err := quoteRune(s) // Trigger validation, which guarantees this is a quote-wrapped string. if err != nil { - return "", err + return "", rune(0), err } - return s[1 : len(s)-1], nil + return s[1 : len(s)-1], quote, nil } var ( diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/fulcio/fulcio.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/fulcio/fulcio.go index cc3e12ca9b..4a6d753cc8 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/fulcio/fulcio.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/fulcio/fulcio.go @@ -24,6 +24,7 @@ import ( "os" "strings" + "github.com/go-jose/go-jose/v3/jwt" "github.com/sigstore/cosign/v2/cmd/cosign/cli/options" "github.com/sigstore/cosign/v2/cmd/cosign/cli/sign/privacy" "github.com/sigstore/cosign/v2/internal/pkg/cosign/fulcio/fulcioroots" @@ -33,7 +34,6 @@ import ( "github.com/sigstore/sigstore/pkg/cryptoutils" "github.com/sigstore/sigstore/pkg/oauthflow" "github.com/sigstore/sigstore/pkg/signature" - "go.step.sm/crypto/jose" "golang.org/x/term" ) @@ -209,7 +209,7 @@ func NewClient(fulcioURL string) (api.LegacyClient, error) { // or a path to an identity token via the --identity-token flag func idToken(s string) (string, error) { // If this is a valid raw token or is empty, just return it - if _, err := jose.ParseSigned(s); err == nil || s == "" { + if _, err := jwt.ParseSigned(s); err == nil || s == "" { return s, nil } diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/attach.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/attach.go index cb7b9a2ceb..17174305d1 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/attach.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/attach.go @@ -80,7 +80,7 @@ func (o *AttachSBOMOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.SBOM, "sbom", "", "path to the sbom, or {-} for stdin") - _ = cmd.Flags().SetAnnotation("sbom", cobra.BashCompFilenameExt, []string{}) + _ = cmd.MarkFlagFilename("sbom", sbomExts...) cmd.Flags().StringVar(&o.SBOMType, "type", "spdx", "type of sbom (spdx|cyclonedx|syft)") diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/attest.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/attest.go index 8139cddaef..eca2c93d49 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/attest.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/attest.go @@ -54,18 +54,18 @@ func (o *AttestOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.Key, "key", "", "path to the private key file, KMS URI or Kubernetes Secret") - _ = cmd.Flags().SetAnnotation("key", cobra.BashCompFilenameExt, []string{"key"}) + _ = cmd.MarkFlagFilename("key", privateKeyExts...) cmd.Flags().StringVar(&o.Cert, "certificate", "", "path to the X.509 certificate in PEM format to include in the OCI Signature") - _ = cmd.Flags().SetAnnotation("certificate", cobra.BashCompFilenameExt, []string{"cert"}) + _ = cmd.MarkFlagFilename("certificate", certificateExts...) cmd.Flags().StringVar(&o.CertChain, "certificate-chain", "", "path to a list of CA X.509 certificates in PEM format which will be needed "+ "when building the certificate chain for the signing certificate. "+ "Must start with the parent intermediate CA certificate of the "+ "signing certificate and end with the root certificate. Included in the OCI Signature") - _ = cmd.Flags().SetAnnotation("certificate-chain", cobra.BashCompFilenameExt, []string{"cert"}) + _ = cmd.MarkFlagFilename("certificate-chain", certificateExts...) cmd.Flags().BoolVar(&o.NoUpload, "no-upload", false, "do not upload the generated attestation") diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/attest_blob.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/attest_blob.go index b6f48b4967..b641c5b328 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/attest_blob.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/attest_blob.go @@ -58,33 +58,34 @@ func (o *AttestBlobOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.Key, "key", "", "path to the private key file, KMS URI or Kubernetes Secret") - _ = cmd.Flags().SetAnnotation("key", cobra.BashCompFilenameExt, []string{"key"}) + _ = cmd.MarkFlagFilename("key", privateKeyExts...) cmd.Flags().StringVar(&o.Cert, "certificate", "", "path to the X.509 certificate in PEM format to include in the OCI Signature") - _ = cmd.Flags().SetAnnotation("certificate", cobra.BashCompFilenameExt, []string{"cert"}) + _ = cmd.MarkFlagFilename("certificate", certificateExts...) cmd.Flags().StringVar(&o.CertChain, "certificate-chain", "", "path to a list of CA X.509 certificates in PEM format which will be needed "+ "when building the certificate chain for the signing certificate. "+ "Must start with the parent intermediate CA certificate of the "+ "signing certificate and end with the root certificate. Included in the OCI Signature") - _ = cmd.Flags().SetAnnotation("certificate-chain", cobra.BashCompFilenameExt, []string{"cert"}) + _ = cmd.MarkFlagFilename("certificate-chain", certificateExts...) cmd.Flags().StringVar(&o.OutputSignature, "output-signature", "", "write the signature to FILE") - _ = cmd.Flags().SetAnnotation("output-signature", cobra.BashCompFilenameExt, []string{}) + _ = cmd.MarkFlagFilename("output-signature", signatureExts...) cmd.Flags().StringVar(&o.OutputAttestation, "output-attestation", "", "write the attestation to FILE") + // _ = cmd.MarkFlagFilename("output-attestation") // no typical extensions cmd.Flags().StringVar(&o.OutputCertificate, "output-certificate", "", "write the certificate to FILE") - _ = cmd.Flags().SetAnnotation("key", cobra.BashCompFilenameExt, []string{}) + _ = cmd.MarkFlagFilename("key", certificateExts...) cmd.Flags().StringVar(&o.BundlePath, "bundle", "", "write everything required to verify the blob to a FILE") - _ = cmd.Flags().SetAnnotation("bundle", cobra.BashCompFilenameExt, []string{}) + _ = cmd.MarkFlagFilename("bundle", bundleExts...) // TODO: have this default to true as a breaking change cmd.Flags().BoolVar(&o.NewBundleFormat, "new-bundle-format", false, @@ -107,5 +108,5 @@ func (o *AttestBlobOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.RFC3161TimestampPath, "rfc3161-timestamp-bundle", "", "path to an RFC 3161 timestamp bundle FILE") - _ = cmd.Flags().SetAnnotation("rfc3161-timestamp-bundle", cobra.BashCompFilenameExt, []string{}) + // _ = cmd.MarkFlagFilename("rfc3161-timestamp-bundle") // no typical extensions } diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/bundle.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/bundle.go new file mode 100644 index 0000000000..a8a090d4c2 --- /dev/null +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/bundle.go @@ -0,0 +1,87 @@ +// +// Copyright 2024 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package options + +import ( + "github.com/spf13/cobra" +) + +type BundleCreateOptions struct { + Artifact string + AttestationPath string + BundlePath string + CertificatePath string + IgnoreTlog bool + KeyRef string + Out string + RekorURL string + RFC3161TimestampPath string + SignaturePath string + Sk bool + Slot string +} + +var _ Interface = (*BundleCreateOptions)(nil) + +func (o *BundleCreateOptions) AddFlags(cmd *cobra.Command) { + cmd.Flags().StringVar(&o.Artifact, "artifact", "", + "path to artifact FILE") + // _ = cmd.MarkFlagFilename("artifact") // no typical extensions + + cmd.Flags().StringVar(&o.AttestationPath, "attestation", "", + "path to attestation FILE") + // _ = cmd.MarkFlagFilename("attestation") // no typical extensions + + cmd.Flags().StringVar(&o.BundlePath, "bundle", "", + "path to old format bundle FILE") + _ = cmd.MarkFlagFilename("bundle", bundleExts...) + + cmd.Flags().StringVar(&o.CertificatePath, "certificate", "", + "path to the signing certificate, likely from Fulco.") + _ = cmd.MarkFlagFilename("certificate", certificateExts...) + + cmd.Flags().BoolVar(&o.IgnoreTlog, "ignore-tlog", false, + "ignore transparency log verification, to be used when an artifact "+ + "signature has not been uploaded to the transparency log.") + + cmd.Flags().StringVar(&o.KeyRef, "key", "", + "path to the public key file, KMS URI or Kubernetes Secret") + _ = cmd.MarkFlagFilename("key", publicKeyExts...) + + cmd.Flags().StringVar(&o.Out, "out", "", "path to output bundle") + _ = cmd.MarkFlagFilename("out", bundleExts...) + + cmd.Flags().StringVar(&o.RekorURL, "rekor-url", "https://rekor.sigstore.dev", + "address of rekor STL server") + + cmd.Flags().StringVar(&o.RFC3161TimestampPath, "rfc3161-timestamp", "", + "path to RFC3161 timestamp FILE") + // _ = cmd.MarkFlagFilename("rfc3161-timestamp") // no typical extensions + + cmd.Flags().StringVar(&o.SignaturePath, "signature", "", + "path to base64-encoded signature over attestation in DSSE format") + _ = cmd.MarkFlagFilename("signature", signatureExts...) + + cmd.Flags().BoolVar(&o.Sk, "sk", false, + "whether to use a hardware security key") + + cmd.Flags().StringVar(&o.Slot, "slot", "", + "security key slot to use for generated key (default: signature) "+ + "(authentication|signature|card-authentication|key-management)") + + cmd.MarkFlagsMutuallyExclusive("bundle", "certificate") + cmd.MarkFlagsMutuallyExclusive("bundle", "signature") +} diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/certificate.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/certificate.go index 3df7b4b962..b14d408fe2 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/certificate.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/certificate.go @@ -46,7 +46,7 @@ var _ Interface = (*RekorOptions)(nil) func (o *CertVerifyOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.Cert, "certificate", "", "path to the public certificate. The certificate will be verified against the Fulcio roots if the --certificate-chain option is not passed.") - _ = cmd.Flags().SetAnnotation("certificate", cobra.BashCompFilenameExt, []string{"cert"}) + _ = cmd.MarkFlagFilename("certificate", certificateExts...) cmd.Flags().StringVar(&o.CertIdentity, "certificate-identity", "", "The identity expected in a valid Fulcio certificate. Valid values include email address, DNS names, IP addresses, and URIs. Either --certificate-identity or --certificate-identity-regexp must be set for keyless flows.") @@ -82,24 +82,25 @@ func (o *CertVerifyOptions) AddFlags(cmd *cobra.Command) { "when building the certificate chains for the signing certificate. "+ "The flag is optional and must be used together with --ca-roots, conflicts with "+ "--certificate-chain.") - _ = cmd.Flags().SetAnnotation("ca-intermediates", cobra.BashCompFilenameExt, []string{"cert"}) + _ = cmd.MarkFlagFilename("ca-intermediates", certificateExts...) cmd.Flags().StringVar(&o.CARoots, "ca-roots", "", "path to a bundle file of CA certificates in PEM format which will be needed "+ "when building the certificate chains for the signing certificate. Conflicts with --certificate-chain.") - _ = cmd.Flags().SetAnnotation("ca-roots", cobra.BashCompFilenameExt, []string{"cert"}) + _ = cmd.MarkFlagFilename("ca-roots", certificateExts...) cmd.Flags().StringVar(&o.CertChain, "certificate-chain", "", "path to a list of CA certificates in PEM format which will be needed "+ "when building the certificate chain for the signing certificate. "+ "Must start with the parent intermediate CA certificate of the "+ "signing certificate and end with the root certificate. Conflicts with --ca-roots and --ca-intermediates.") - _ = cmd.Flags().SetAnnotation("certificate-chain", cobra.BashCompFilenameExt, []string{"cert"}) + _ = cmd.MarkFlagFilename("certificate-chain", certificateExts...) cmd.MarkFlagsMutuallyExclusive("ca-roots", "certificate-chain") cmd.MarkFlagsMutuallyExclusive("ca-intermediates", "certificate-chain") cmd.Flags().StringVar(&o.SCT, "sct", "", "path to a detached Signed Certificate Timestamp, formatted as a RFC6962 AddChainResponse struct. "+ "If a certificate contains an SCT, verification will check both the detached and embedded SCTs.") + // _ = cmd.MarkFlagFilename("sct") // no typical extensions cmd.Flags().BoolVar(&o.IgnoreSCT, "insecure-ignore-sct", false, "when set, verification will not check that a certificate contains an embedded SCT, a proof of "+ "inclusion in a certificate transparency log") diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/copy.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/copy.go index 7f4d5f373c..1beafcbabc 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/copy.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/copy.go @@ -21,7 +21,7 @@ import ( // CopyOptions is the top level wrapper for the copy command. type CopyOptions struct { - CopyOnly string + CopyOnly []string SignatureOnly bool Force bool Platform string @@ -34,8 +34,8 @@ var _ Interface = (*CopyOptions)(nil) func (o *CopyOptions) AddFlags(cmd *cobra.Command) { o.Registry.AddFlags(cmd) - cmd.Flags().StringVar(&o.CopyOnly, "only", "", - "custom string array to only copy specific items, this flag is comma delimited. ex: --only=sbom,sign,att") + cmd.Flags().StringSliceVar(&o.CopyOnly, "only", []string{}, + "custom string array to only copy specific items, this flag is comma delimited. ex: --only=sig,att,sbom") cmd.Flags().BoolVar(&o.SignatureOnly, "sig-only", false, "[DEPRECATED] only copy the image signature") diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/deprecate.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/deprecate.go index 76084afa17..39900375f9 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/deprecate.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/deprecate.go @@ -19,3 +19,8 @@ const SBOMAttachmentDeprecation = "WARNING: SBOM attachments are deprecated " + "and support will be removed in a Cosign release soon after 2024-02-22 " + "(see https://github.com/sigstore/cosign/issues/2755). " + "Instead, please use SBOM attestations." + +const RootWithoutChecksumDeprecation = "WARNING: Fetching initial root from URL " + + "without providing its checksum is deprecated and will be disallowed in " + + "a future Cosign release. Please provide the initial root checksum " + + "via the --root-checksum argument." diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/files.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/files.go index 0467ac1c62..1d3bde17c2 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/files.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/files.go @@ -54,5 +54,5 @@ func (o *FilesOptions) String() string { func (o *FilesOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringSliceVarP(&o.Files, "files", "f", nil, ":[platform/arch]") - _ = cmd.Flags().SetAnnotation("files", cobra.BashCompFilenameExt, []string{}) + // _ = cmd.MarkFlagFilename("files") // no typical extensions } diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/fulcio.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/fulcio.go index 139731a77c..e30d6b6381 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/fulcio.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/fulcio.go @@ -39,6 +39,7 @@ func (o *FulcioOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.IdentityToken, "identity-token", "", "identity token to use for certificate from fulcio. the token or a path to a file containing the token is accepted.") + // _ = cmd.MarkFlagFilename("identity-token") // no typical extensions cmd.Flags().StringVar(&o.AuthFlow, "fulcio-auth-flow", "", "fulcio interactive oauth2 flow to use for certificate from fulcio. Defaults to determining the flow based on the runtime environment. (options) normal|device|token|client_credentials") diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/import_key_pair.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/import_key_pair.go index 9c645fed0a..55e66c226a 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/import_key_pair.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/import_key_pair.go @@ -36,11 +36,11 @@ var _ Interface = (*ImportKeyPairOptions)(nil) func (o *ImportKeyPairOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVarP(&o.Key, "key", "k", "", "import key pair to use for signing") - _ = cmd.Flags().SetAnnotation("key", cobra.BashCompFilenameExt, []string{}) + _ = cmd.MarkFlagFilename("key", privateKeyExts...) cmd.Flags().StringVarP(&o.OutputKeyPrefix, "output-key-prefix", "o", "import-cosign", "name used for outputted key pairs") - _ = cmd.Flags().SetAnnotation("output-key-prefix", cobra.BashCompFilenameExt, []string{}) + // _ = cmd.MarkFlagFilename("output-key-prefix") // no typical extensions cmd.Flags().BoolVarP(&o.SkipConfirmation, "yes", "y", false, "skip confirmation prompts for overwriting existing key") diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/initialize.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/initialize.go index ab91955ee7..d5eed5346a 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/initialize.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/initialize.go @@ -22,8 +22,9 @@ import ( // InitializeOptions is the top level wrapper for the initialize command. type InitializeOptions struct { - Mirror string - Root string + Mirror string + Root string + RootChecksum string } var _ Interface = (*InitializeOptions)(nil) @@ -35,5 +36,8 @@ func (o *InitializeOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.Root, "root", "", "path to trusted initial root. defaults to embedded root") - _ = cmd.Flags().SetAnnotation("root", cobra.BashCompSubdirsInDir, []string{}) + _ = cmd.MarkFlagDirname("root") + + cmd.Flags().StringVar(&o.RootChecksum, "root-checksum", "", + "checksum of the initial root, required if root is downloaded via http(s). expects sha256 by default, can be changed to sha512 by providing sha512:") } diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/load.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/load.go index 167361d087..c2c54abc0f 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/load.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/load.go @@ -32,6 +32,6 @@ func (o *LoadOptions) AddFlags(cmd *cobra.Command) { o.Registry.AddFlags(cmd) cmd.Flags().StringVar(&o.Directory, "dir", "", "path to directory where the signed image is stored on disk") - _ = cmd.Flags().SetAnnotation("dir", cobra.BashCompSubdirsInDir, []string{}) + _ = cmd.MarkFlagDirname("dir") _ = cmd.MarkFlagRequired("dir") } diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/oidc.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/oidc.go index c68421be60..b62e2d14db 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/oidc.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/oidc.go @@ -64,7 +64,7 @@ func (o *OIDCOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.clientSecretFile, "oidc-client-secret-file", "", "Path to file containing OIDC client secret for application") - _ = cmd.Flags().SetAnnotation("oidc-client-secret-file", cobra.BashCompFilenameExt, []string{}) + // _ = cmd.MarkFlagFilename("oidc-client-secret-file") // no typical extensions cmd.Flags().StringVar(&o.RedirectURL, "oidc-redirect-url", "", "OIDC redirect URL (Optional). The default oidc-redirect-url is 'http://localhost:0/auth/callback'.") diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/options.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/options.go index f69d8309e2..014348549d 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/options.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/options.go @@ -21,3 +21,37 @@ type Interface interface { // AddFlags adds this options' flags to the cobra command. AddFlags(cmd *cobra.Command) } + +var bundleExts = []string{ + "bundle", +} +var certificateExts = []string{ + "cert", + "crt", + "pem", +} +var logExts = []string{ + "log", +} +var moduleExts = []string{ + "dll", + "dylib", + "so", +} +var privateKeyExts = []string{ + "key", +} +var publicKeyExts = []string{ + "pub", +} +var sbomExts = []string{ + "json", + "xml", + "spdx", +} +var signatureExts = []string{ + "sig", +} +var wasmExts = []string{ + "wasm", +} diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/pkcs11_tool.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/pkcs11_tool.go index e673184e2d..c391e9de7b 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/pkcs11_tool.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/pkcs11_tool.go @@ -31,7 +31,7 @@ var _ Interface = (*PKCS11ToolListTokensOptions)(nil) func (o *PKCS11ToolListTokensOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.ModulePath, "module-path", env.Getenv(env.VariablePKCS11ModulePath), "absolute path to the PKCS11 module") - _ = cmd.Flags().SetAnnotation("module-path", cobra.BashCompFilenameExt, []string{}) + _ = cmd.MarkFlagFilename("module-path", moduleExts...) } // PKCS11ToolListKeysUrisOptions is the wrapper for `pkcs11-tool list-keys-uris` related options. @@ -47,7 +47,7 @@ var _ Interface = (*PKCS11ToolListKeysUrisOptions)(nil) func (o *PKCS11ToolListKeysUrisOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.ModulePath, "module-path", env.Getenv(env.VariablePKCS11ModulePath), "absolute path to the PKCS11 module") - _ = cmd.Flags().SetAnnotation("module-path", cobra.BashCompFilenameExt, []string{}) + _ = cmd.MarkFlagFilename("module-path", moduleExts...) cmd.Flags().UintVar(&o.SlotID, "slot-id", 0, "id of the PKCS11 slot, uses 0 if empty") diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/predicate.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/predicate.go index af05ce4695..b5a01f7cfa 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/predicate.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/predicate.go @@ -94,6 +94,7 @@ func (o *PredicateLocalOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.Path, "predicate", "", "path to the predicate file.") + _ = cmd.MarkFlagFilename("predicate", sbomExts...) _ = cmd.MarkFlagRequired("predicate") } diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/public_key.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/public_key.go index e3c7341a31..2297360a67 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/public_key.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/public_key.go @@ -34,9 +34,9 @@ func (o *PublicKeyOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.Key, "key", "", "path to the private key file, KMS URI or Kubernetes Secret") - _ = cmd.Flags().SetAnnotation("key", cobra.BashCompFilenameExt, []string{}) + _ = cmd.MarkFlagFilename("key", privateKeyExts...) cmd.Flags().StringVar(&o.OutFile, "outfile", "", "path to a payload file to use rather than generating one") - _ = cmd.Flags().SetAnnotation("outfile", cobra.BashCompFilenameExt, []string{}) + _ = cmd.MarkFlagFilename("outfile", publicKeyExts...) } diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/registry.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/registry.go index 61edb47d48..6840d53297 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/registry.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/registry.go @@ -17,10 +17,12 @@ package options import ( "context" "crypto/tls" + "crypto/x509" "errors" "fmt" "io" "net/http" + "os" ecr "github.com/awslabs/amazon-ecr-credential-helper/ecr-login" "github.com/chrismellard/docker-credential-acr-env/pkg/credhelper" @@ -45,6 +47,10 @@ type RegistryOptions struct { RefOpts ReferenceOptions Keychain Keychain AuthConfig authn.AuthConfig + RegistryCACert string + RegistryClientCert string + RegistryClientKey string + RegistryServerName string // RegistryClientOpts allows overriding the result of GetRegistryClientOpts. RegistryClientOpts []remote.Option @@ -72,6 +78,21 @@ func (o *RegistryOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.AuthConfig.RegistryToken, "registry-token", "", "registry bearer auth token") + cmd.Flags().StringVar(&o.RegistryCACert, "registry-cacert", "", + "path to the X.509 CA certificate file in PEM format to be used for the connection to the registry") + _ = cmd.MarkFlagFilename("registry-cacert", certificateExts...) + + cmd.Flags().StringVar(&o.RegistryClientCert, "registry-client-cert", "", + "path to the X.509 certificate file in PEM format to be used for the connection to the registry") + _ = cmd.MarkFlagFilename("registry-client-cert", certificateExts...) + + cmd.Flags().StringVar(&o.RegistryClientKey, "registry-client-key", "", + "path to the X.509 private key file in PEM format to be used, together with the 'registry-client-cert' value, for the connection to the registry") + _ = cmd.MarkFlagFilename("registry-client-key", privateKeyExts...) + + cmd.Flags().StringVar(&o.RegistryServerName, "registry-server-name", "", + "SAN name to use as the 'ServerName' tls.Config field to verify the mTLS connection to the registry") + o.RefOpts.AddFlags(cmd) } @@ -131,8 +152,11 @@ func (o *RegistryOptions) GetRegistryClientOpts(ctx context.Context) []remote.Op opts = append(opts, remote.WithAuthFromKeychain(authn.DefaultKeychain)) } - if o.AllowInsecure { - opts = append(opts, remote.WithTransport(&http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}})) // #nosec G402 + tlsConfig, err := o.getTLSConfig() + if err == nil { + tr := http.DefaultTransport.(*http.Transport).Clone() + tr.TLSClientConfig = tlsConfig + opts = append(opts, remote.WithTransport(tr)) } // Reuse a remote.Pusher and a remote.Puller for all operations that use these opts. @@ -193,3 +217,41 @@ func (o *RegistryExperimentalOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().Var(&o.RegistryReferrersMode, "registry-referrers-mode", "mode for fetching references from the registry. allowed: legacy, oci-1-1") } + +func (o *RegistryOptions) getTLSConfig() (*tls.Config, error) { + var tlsConfig tls.Config + + if o.RegistryCACert != "" { + f, err := os.Open(o.RegistryCACert) + if err != nil { + return nil, err + } + defer f.Close() + caCertBytes, err := io.ReadAll(f) + if err != nil { + return nil, fmt.Errorf("unable to read CA certs from %s: %w", o.RegistryCACert, err) + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(caCertBytes) { + return nil, fmt.Errorf("no valid CA certs found in %s", o.RegistryCACert) + } + tlsConfig.RootCAs = pool + } + + if o.RegistryClientCert != "" && o.RegistryClientKey != "" { + cert, err := tls.LoadX509KeyPair(o.RegistryClientCert, o.RegistryClientKey) + if err != nil { + return nil, fmt.Errorf("unable to read client certs from cert %s, key %s: %w", + o.RegistryClientCert, o.RegistryClientKey, err) + } + tlsConfig.Certificates = []tls.Certificate{cert} + } + + if o.RegistryServerName != "" { + tlsConfig.ServerName = o.RegistryServerName + } + + tlsConfig.InsecureSkipVerify = o.AllowInsecure // #nosec G402 + + return &tlsConfig, nil +} diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/root.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/root.go index cb15af0dc3..92bb01e6a9 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/root.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/root.go @@ -44,7 +44,7 @@ var _ Interface = (*RootOptions)(nil) func (o *RootOptions) AddFlags(cmd *cobra.Command) { cmd.PersistentFlags().StringVar(&o.OutputFile, "output-file", "", "log output to a file") - _ = cmd.Flags().SetAnnotation("output-file", cobra.BashCompFilenameExt, []string{}) + _ = cmd.MarkFlagFilename("output-file", logExts...) cmd.PersistentFlags().BoolVarP(&o.Verbose, "verbose", "d", false, "log debug output") diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/save.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/save.go index 7c4f623de6..761d4bb42e 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/save.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/save.go @@ -32,6 +32,6 @@ func (o *SaveOptions) AddFlags(cmd *cobra.Command) { o.Registry.AddFlags(cmd) cmd.Flags().StringVar(&o.Directory, "dir", "", "path to dir where the signed image should be stored on disk") - _ = cmd.Flags().SetAnnotation("dir", cobra.BashCompSubdirsInDir, []string{}) + _ = cmd.MarkFlagDirname("dir") _ = cmd.MarkFlagRequired("dir") } diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/sign.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/sign.go index 70ec9acab6..bcacfd7e63 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/sign.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/sign.go @@ -66,42 +66,43 @@ func (o *SignOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.Key, "key", "", "path to the private key file, KMS URI or Kubernetes Secret") - _ = cmd.Flags().SetAnnotation("key", cobra.BashCompFilenameExt, []string{}) + _ = cmd.MarkFlagFilename("key", privateKeyExts...) cmd.Flags().StringVar(&o.Cert, "certificate", "", "path to the X.509 certificate in PEM format to include in the OCI Signature") - _ = cmd.Flags().SetAnnotation("certificate", cobra.BashCompFilenameExt, []string{"cert"}) + _ = cmd.MarkFlagFilename("certificate", certificateExts...) cmd.Flags().StringVar(&o.CertChain, "certificate-chain", "", "path to a list of CA X.509 certificates in PEM format which will be needed "+ "when building the certificate chain for the signing certificate. "+ "Must start with the parent intermediate CA certificate of the "+ "signing certificate and end with the root certificate. Included in the OCI Signature") - _ = cmd.Flags().SetAnnotation("certificate-chain", cobra.BashCompFilenameExt, []string{"cert"}) + _ = cmd.MarkFlagFilename("certificate-chain", certificateExts...) cmd.Flags().BoolVar(&o.Upload, "upload", true, "whether to upload the signature") cmd.Flags().StringVar(&o.OutputSignature, "output-signature", "", "write the signature to FILE") - _ = cmd.Flags().SetAnnotation("output-signature", cobra.BashCompFilenameExt, []string{}) + _ = cmd.MarkFlagFilename("output-signature", signatureExts...) cmd.Flags().StringVar(&o.OutputPayload, "output-payload", "", "write the signed payload to FILE") - _ = cmd.Flags().SetAnnotation("output-payload", cobra.BashCompFilenameExt, []string{}) + // _ = cmd.MarkFlagFilename("output-payload") // no typical extensions cmd.Flags().StringVar(&o.OutputCertificate, "output-certificate", "", "write the certificate to FILE") - _ = cmd.Flags().SetAnnotation("output-certificate", cobra.BashCompFilenameExt, []string{}) + _ = cmd.MarkFlagFilename("output-certificate", certificateExts...) cmd.Flags().StringVar(&o.PayloadPath, "payload", "", "path to a payload file to use rather than generating one") - _ = cmd.Flags().SetAnnotation("payload", cobra.BashCompFilenameExt, []string{}) + // _ = cmd.MarkFlagFilename("payload") // no typical extensions cmd.Flags().BoolVarP(&o.Recursive, "recursive", "r", false, "if a multi-arch image is specified, additionally sign each discrete image") cmd.Flags().StringVar(&o.Attachment, "attachment", "", "DEPRECATED, related image attachment to sign (sbom), default none") + _ = cmd.MarkFlagFilename("attachment", sbomExts...) cmd.Flags().BoolVarP(&o.SkipConfirmation, "yes", "y", false, "skip confirmation prompts for non-destructive operations") @@ -111,12 +112,15 @@ func (o *SignOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.TSAClientCACert, "timestamp-client-cacert", "", "path to the X.509 CA certificate file in PEM format to be used for the connection to the TSA Server") + _ = cmd.MarkFlagFilename("timestamp-client-cacert", certificateExts...) cmd.Flags().StringVar(&o.TSAClientCert, "timestamp-client-cert", "", "path to the X.509 certificate file in PEM format to be used for the connection to the TSA Server") + _ = cmd.MarkFlagFilename("timestamp-client-cert", certificateExts...) cmd.Flags().StringVar(&o.TSAClientKey, "timestamp-client-key", "", "path to the X.509 private key file in PEM format to be used, together with the 'timestamp-client-cert' value, for the connection to the TSA Server") + _ = cmd.MarkFlagFilename("timestamp-client-key", privateKeyExts...) cmd.Flags().StringVar(&o.TSAServerName, "timestamp-server-name", "", "SAN name to use as the 'ServerName' tls.Config field to verify the mTLS connection to the TSA Server") @@ -124,7 +128,7 @@ func (o *SignOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.TSAServerURL, "timestamp-server-url", "", "url to the Timestamp RFC3161 server, default none. Must be the path to the API to request timestamp responses, e.g. https://freetsa.org/tsr") - _ = cmd.Flags().SetAnnotation("certificate", cobra.BashCompFilenameExt, []string{"cert"}) + _ = cmd.MarkFlagFilename("certificate", certificateExts...) cmd.Flags().BoolVar(&o.IssueCertificate, "issue-certificate", false, "issue a code signing certificate from Fulcio, even if a key is provided") diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/signblob.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/signblob.go index d632669068..db08489c2a 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/signblob.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/signblob.go @@ -56,25 +56,26 @@ func (o *SignBlobOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.Key, "key", "", "path to the private key file, KMS URI or Kubernetes Secret") - _ = cmd.Flags().SetAnnotation("key", cobra.BashCompFilenameExt, []string{}) + _ = cmd.MarkFlagFilename("key", privateKeyExts...) cmd.Flags().BoolVar(&o.Base64Output, "b64", true, "whether to base64 encode the output") cmd.Flags().StringVar(&o.OutputSignature, "output-signature", "", "write the signature to FILE") - _ = cmd.Flags().SetAnnotation("output-signature", cobra.BashCompFilenameExt, []string{}) + _ = cmd.MarkFlagFilename("output-signature", signatureExts...) // TODO: remove when output flag is fully deprecated cmd.Flags().StringVar(&o.Output, "output", "", "write the signature to FILE") + _ = cmd.MarkFlagFilename("output", signatureExts...) cmd.Flags().StringVar(&o.OutputCertificate, "output-certificate", "", "write the certificate to FILE") - _ = cmd.Flags().SetAnnotation("key", cobra.BashCompFilenameExt, []string{}) + _ = cmd.MarkFlagFilename("output-certificate", certificateExts...) cmd.Flags().StringVar(&o.BundlePath, "bundle", "", "write everything required to verify the blob to a FILE") - _ = cmd.Flags().SetAnnotation("bundle", cobra.BashCompFilenameExt, []string{}) + _ = cmd.MarkFlagFilename("bundle", bundleExts...) // TODO: have this default to true as a breaking change cmd.Flags().BoolVar(&o.NewBundleFormat, "new-bundle-format", false, @@ -88,12 +89,15 @@ func (o *SignBlobOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.TSAClientCACert, "timestamp-client-cacert", "", "path to the X.509 CA certificate file in PEM format to be used for the connection to the TSA Server") + _ = cmd.MarkFlagFilename("timestamp-client-cacert", certificateExts...) cmd.Flags().StringVar(&o.TSAClientCert, "timestamp-client-cert", "", "path to the X.509 certificate file in PEM format to be used for the connection to the TSA Server") + _ = cmd.MarkFlagFilename("timestamp-client-cert", certificateExts...) cmd.Flags().StringVar(&o.TSAClientKey, "timestamp-client-key", "", "path to the X.509 private key file in PEM format to be used, together with the 'timestamp-client-cert' value, for the connection to the TSA Server") + _ = cmd.MarkFlagFilename("timestamp-client-key", privateKeyExts...) cmd.Flags().StringVar(&o.TSAServerName, "timestamp-server-name", "", "SAN name to use as the 'ServerName' tls.Config field to verify the mTLS connection to the TSA Server") @@ -103,7 +107,7 @@ func (o *SignBlobOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.RFC3161TimestampPath, "rfc3161-timestamp", "", "write the RFC3161 timestamp to a file") - _ = cmd.Flags().SetAnnotation("rfc3161-timestamp", cobra.BashCompFilenameExt, []string{}) + // _ = cmd.MarkFlagFilename("rfc3161-timestamp") // no typical extensions cmd.Flags().BoolVar(&o.IssueCertificate, "issue-certificate", false, "issue a code signing certificate from Fulcio, even if a key is provided") diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/trustedroot.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/trustedroot.go new file mode 100644 index 0000000000..21561aa527 --- /dev/null +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/trustedroot.go @@ -0,0 +1,66 @@ +// +// Copyright 2024 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package options + +import ( + "github.com/spf13/cobra" +) + +type TrustedRootCreateOptions struct { + CertChain []string + CtfeKeyPath []string + CtfeStartTime []string + Out string + RekorKeyPath []string + RekorStartTime []string + TSACertChainPath []string +} + +var _ Interface = (*TrustedRootCreateOptions)(nil) + +func (o *TrustedRootCreateOptions) AddFlags(cmd *cobra.Command) { + cmd.Flags().StringArrayVar(&o.CertChain, "certificate-chain", nil, + "path to a list of CA certificates in PEM format which will be needed "+ + "when building the certificate chain for the signing certificate. "+ + "Must start with the parent intermediate CA certificate of the "+ + "signing certificate and end with the root certificate.") + _ = cmd.MarkFlagFilename("certificate-chain", certificateExts...) + + cmd.Flags().StringArrayVar(&o.CtfeKeyPath, "ctfe-key", nil, + "path to a PEM-encoded public key used by certificate authority for "+ + "certificate transparency log.") + _ = cmd.MarkFlagFilename("ctfe-key", publicKeyExts...) + + cmd.Flags().StringArrayVar(&o.CtfeStartTime, "ctfe-start-time", nil, + "RFC 3339 string describing validity start time for key use by "+ + "certificate transparency log.") + + cmd.Flags().StringVar(&o.Out, "out", "", "path to output trusted root") + // _ = cmd.MarkFlagFilename("output") // no typical extensions + + cmd.Flags().StringArrayVar(&o.RekorKeyPath, "rekor-key", nil, + "path to a PEM-encoded public key used by transparency log like Rekor.") + _ = cmd.MarkFlagFilename("rekor-key", publicKeyExts...) + + cmd.Flags().StringArrayVar(&o.RekorStartTime, "rekor-start-time", nil, + "RFC 3339 string describing validity start time for key use by "+ + "transparency log like Rekor.") + + cmd.Flags().StringArrayVar(&o.TSACertChainPath, "timestamp-certificate-chain", nil, + "path to PEM-encoded certificate chain file for the RFC3161 timestamp authority. Must contain the root CA certificate. "+ + "Optionally may contain intermediate CA certificates") + _ = cmd.MarkFlagFilename("timestamp-certificate-chain", certificateExts...) +} diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/upload.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/upload.go index 9ef6a0b72f..37c928b884 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/upload.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/upload.go @@ -54,6 +54,6 @@ func (o *UploadWASMOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVarP(&o.File, "file", "f", "", "path to the wasm file to upload") - _ = cmd.Flags().SetAnnotation("file", cobra.BashCompFilenameExt, []string{}) + _ = cmd.MarkFlagFilename("file", wasmExts...) _ = cmd.MarkFlagRequired("file") } diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/verify.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/verify.go index 3cdbb0e8a6..6ab0d7ca86 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/verify.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/options/verify.go @@ -92,22 +92,25 @@ func (o *VerifyOptions) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.Key, "key", "", "path to the public key file, KMS URI or Kubernetes Secret") - _ = cmd.Flags().SetAnnotation("key", cobra.BashCompFilenameExt, []string{}) + _ = cmd.MarkFlagFilename("key", publicKeyExts...) cmd.Flags().BoolVar(&o.CheckClaims, "check-claims", true, "whether to check the claims found") cmd.Flags().StringVar(&o.Attachment, "attachment", "", "DEPRECATED, related image attachment to verify (sbom), default none") + _ = cmd.MarkFlagFilename("attachment", sbomExts...) cmd.Flags().StringVarP(&o.Output, "output", "o", "json", "output format for the signing image information (json|text)") cmd.Flags().StringVar(&o.SignatureRef, "signature", "", "signature content or path or remote URL") + _ = cmd.MarkFlagFilename("signature", signatureExts...) cmd.Flags().StringVar(&o.PayloadRef, "payload", "", "payload path or remote URL") + // _ = cmd.MarkFlagFilename("payload") // no typical extensions cmd.Flags().BoolVar(&o.LocalImage, "local-image", false, "whether the specified image is a path to an image saved locally via 'cosign save'") diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/verify/verify.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/verify/verify.go index 17fd63e833..f5fc86bfdd 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/verify/verify.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/verify/verify.go @@ -84,17 +84,6 @@ type VerifyCommand struct { ExperimentalOCI11 bool } -func (c *VerifyCommand) loadTSACertificates(ctx context.Context) (*cosign.TSACertificates, error) { - if c.TSACertChainPath == "" && !c.UseSignedTimestamps { - return nil, fmt.Errorf("TSA certificate chain path not provided and use-signed-timestamps not set") - } - tsaCertificates, err := cosign.GetTSACerts(ctx, c.TSACertChainPath, cosign.GetTufTargets) - if err != nil { - return nil, fmt.Errorf("unable to load TSA certificates: %w", err) - } - return tsaCertificates, nil -} - // Exec runs the verification command func (c *VerifyCommand) Exec(ctx context.Context, images []string) (err error) { if len(images) == 0 { @@ -144,13 +133,15 @@ func (c *VerifyCommand) Exec(ctx context.Context, images []string) (err error) { IgnoreTlog: c.IgnoreTlog, MaxWorkers: c.MaxWorkers, ExperimentalOCI11: c.ExperimentalOCI11, + UseSignedTimestamps: c.TSACertChainPath != "" || c.UseSignedTimestamps, } if c.CheckClaims { co.ClaimVerifier = cosign.SimpleClaimVerifier } - if c.TSACertChainPath != "" || c.UseSignedTimestamps { - tsaCertificates, err := c.loadTSACertificates(ctx) + // If we are using signed timestamps, we need to load the TSA certificates + if co.UseSignedTimestamps { + tsaCertificates, err := cosign.GetTSACerts(ctx, c.TSACertChainPath, cosign.GetTufTargets) if err != nil { return fmt.Errorf("unable to load TSA certificates: %w", err) } diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/verify/verify_attestation.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/verify/verify_attestation.go index 93c2769045..bf25cbb467 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/verify/verify_attestation.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/verify/verify_attestation.go @@ -72,17 +72,6 @@ type VerifyAttestationCommand struct { UseSignedTimestamps bool } -func (c *VerifyAttestationCommand) loadTSACertificates(ctx context.Context) (*cosign.TSACertificates, error) { - if c.TSACertChainPath == "" && !c.UseSignedTimestamps { - return nil, fmt.Errorf("TSA certificate chain path not provided and use-signed-timestamps not set") - } - tsaCertificates, err := cosign.GetTSACerts(ctx, c.TSACertChainPath, cosign.GetTufTargets) - if err != nil { - return nil, fmt.Errorf("unable to load TSA certificates: %w", err) - } - return tsaCertificates, nil -} - // Exec runs the verification command func (c *VerifyAttestationCommand) Exec(ctx context.Context, images []string) (err error) { if len(images) == 0 { @@ -119,6 +108,7 @@ func (c *VerifyAttestationCommand) Exec(ctx context.Context, images []string) (e Offline: c.Offline, IgnoreTlog: c.IgnoreTlog, MaxWorkers: c.MaxWorkers, + UseSignedTimestamps: c.TSACertChainPath != "" || c.UseSignedTimestamps, } if c.CheckClaims { co.ClaimVerifier = cosign.IntotoSubjectClaimVerifier @@ -131,8 +121,9 @@ func (c *VerifyAttestationCommand) Exec(ctx context.Context, images []string) (e } } - if c.TSACertChainPath != "" || c.UseSignedTimestamps { - tsaCertificates, err := c.loadTSACertificates(ctx) + // If we are using signed timestamps, we need to load the TSA certificates + if co.UseSignedTimestamps { + tsaCertificates, err := cosign.GetTSACerts(ctx, c.TSACertChainPath, cosign.GetTufTargets) if err != nil { return fmt.Errorf("unable to load TSA certificates: %w", err) } diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/verify/verify_blob.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/verify/verify_blob.go index 79475c90d8..25932f43f8 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/verify/verify_blob.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/verify/verify_blob.go @@ -16,10 +16,12 @@ package verify import ( + "bytes" "context" "crypto" "crypto/x509" "encoding/base64" + "encoding/hex" "encoding/json" "errors" "fmt" @@ -27,6 +29,7 @@ import ( "io/fs" "os" "path/filepath" + "strings" "github.com/sigstore/cosign/v2/cmd/cosign/cli/options" "github.com/sigstore/cosign/v2/cmd/cosign/cli/rekor" @@ -38,6 +41,9 @@ import ( "github.com/sigstore/cosign/v2/pkg/cosign/pkcs11key" "github.com/sigstore/cosign/v2/pkg/oci/static" sigs "github.com/sigstore/cosign/v2/pkg/signature" + sgbundle "github.com/sigstore/sigstore-go/pkg/bundle" + "github.com/sigstore/sigstore-go/pkg/root" + sgverify "github.com/sigstore/sigstore-go/pkg/verify" "github.com/sigstore/sigstore/pkg/cryptoutils" ) @@ -69,17 +75,6 @@ type VerifyBlobCmd struct { IgnoreTlog bool } -func (c *VerifyBlobCmd) loadTSACertificates(ctx context.Context) (*cosign.TSACertificates, error) { - if c.TSACertChainPath == "" && !c.UseSignedTimestamps { - return nil, fmt.Errorf("either TSA certificate chain path must be provided or use-signed-timestamps must be set") - } - tsaCertificates, err := cosign.GetTSACerts(ctx, c.TSACertChainPath, cosign.GetTufTargets) - if err != nil { - return nil, fmt.Errorf("unable to load TSA certificates: %w", err) - } - return tsaCertificates, nil -} - // nolint func (c *VerifyBlobCmd) Exec(ctx context.Context, blobRef string) error { // Require a certificate/key OR a local bundle file that has the cert. @@ -92,22 +87,6 @@ func (c *VerifyBlobCmd) Exec(ctx context.Context, blobRef string) error { return &options.PubKeyParseError{} } - if c.KeyOpts.NewBundleFormat { - if options.NOf(c.RFC3161TimestampPath, c.TSACertChainPath, c.RekorURL, c.CertChain, c.CARoots, c.CAIntermediates, c.CertRef, c.SigRef, c.SCTRef) > 1 { - return fmt.Errorf("when using --new-bundle-format, please supply signed content with --bundle and verification content with --trusted-root") - } - err := verifyNewBundle(ctx, c.BundlePath, c.TrustedRootPath, c.KeyRef, c.Slot, c.CertVerifyOptions.CertOidcIssuer, c.CertVerifyOptions.CertOidcIssuerRegexp, c.CertVerifyOptions.CertIdentity, c.CertVerifyOptions.CertIdentityRegexp, c.CertGithubWorkflowTrigger, c.CertGithubWorkflowSHA, c.CertGithubWorkflowName, c.CertGithubWorkflowRepository, c.CertGithubWorkflowRef, blobRef, c.Sk, c.IgnoreTlog, c.UseSignedTimestamps, c.IgnoreSCT) - if err == nil { - ui.Infof(ctx, "Verified OK") - } - return err - } else if c.TrustedRootPath != "" { - return fmt.Errorf("--trusted-root only supported with --new-bundle-format") - } - - var cert *x509.Certificate - opts := make([]static.Option, 0) - var identities []cosign.Identity var err error if c.KeyRef == "" { @@ -117,16 +96,6 @@ func (c *VerifyBlobCmd) Exec(ctx context.Context, blobRef string) error { } } - sig, err := base64signature(c.SigRef, c.BundlePath) - if err != nil { - return err - } - - blobBytes, err := payloadBytes(blobRef) - if err != nil { - return err - } - co := &cosign.CheckOpts{ CertGithubWorkflowTrigger: c.CertGithubWorkflowTrigger, CertGithubWorkflowSha: c.CertGithubWorkflowSHA, @@ -137,15 +106,96 @@ func (c *VerifyBlobCmd) Exec(ctx context.Context, blobRef string) error { Identities: identities, Offline: c.Offline, IgnoreTlog: c.IgnoreTlog, + UseSignedTimestamps: c.TSACertChainPath != "" || c.UseSignedTimestamps, + NewBundleFormat: c.KeyOpts.NewBundleFormat || checkNewBundle(c.BundlePath), } - if c.RFC3161TimestampPath != "" && !(c.TSACertChainPath != "" || c.UseSignedTimestamps) { - return fmt.Errorf("either TSA certificate chain path must be provided or use-signed-timestamps must be set when using RFC3161 timestamp path") + + // Keys are optional! + var cert *x509.Certificate + opts := make([]static.Option, 0) + switch { + case c.KeyRef != "": + co.SigVerifier, err = sigs.PublicKeyFromKeyRef(ctx, c.KeyRef) + if err != nil { + return fmt.Errorf("loading public key: %w", err) + } + pkcs11Key, ok := co.SigVerifier.(*pkcs11key.Key) + if ok { + defer pkcs11Key.Close() + } + case c.Sk: + sk, err := pivkey.GetKeyWithSlot(c.Slot) + if err != nil { + return fmt.Errorf("opening piv token: %w", err) + } + defer sk.Close() + co.SigVerifier, err = sk.Verifier() + if err != nil { + return fmt.Errorf("loading public key from token: %w", err) + } + case c.CertRef != "": + cert, err = loadCertFromFileOrURL(c.CertRef) + if err != nil { + return err + } } - if c.TSACertChainPath != "" || c.UseSignedTimestamps { - tsaCertificates, err := c.loadTSACertificates(ctx) + + if co.NewBundleFormat { + if options.NOf(c.RFC3161TimestampPath, c.TSACertChainPath, c.CertChain, c.CARoots, c.CAIntermediates, c.CertRef, c.SigRef, c.SCTRef) > 0 { + return fmt.Errorf("when using --new-bundle-format, please supply signed content with --bundle and verification content with --trusted-root") + } + + if co.TrustedMaterial == nil { + co.TrustedMaterial, err = loadTrustedRoot(ctx, c.TrustedRootPath) + if err != nil { + return err + } + } + + bundle, err := sgbundle.LoadJSONFromPath(c.BundlePath) if err != nil { return err } + + var artifactPolicyOption sgverify.ArtifactPolicyOption + blobBytes, err := payloadBytes(blobRef) + if err != nil { + alg, digest, payloadDigestError := payloadDigest(blobRef) + if payloadDigestError != nil { + return err + } + artifactPolicyOption = sgverify.WithArtifactDigest(alg, digest) + } else { + artifactPolicyOption = sgverify.WithArtifact(bytes.NewReader(blobBytes)) + } + + _, err = cosign.VerifyNewBundle(ctx, co, artifactPolicyOption, bundle) + if err != nil { + return err + } + + ui.Infof(ctx, "Verified OK") + return nil + } + + blobBytes, err := payloadBytes(blobRef) + if err != nil { + return err + } + + if c.TrustedRootPath != "" { + return fmt.Errorf("--trusted-root only supported with --new-bundle-format") + } + if c.RFC3161TimestampPath != "" && !co.UseSignedTimestamps { + return fmt.Errorf("when specifying --rfc3161-timestamp-path, you must also specify --use-signed-timestamps or --timestamp-certificate-chain") + } else if c.RFC3161TimestampPath == "" && co.UseSignedTimestamps { + return fmt.Errorf("when specifying --use-signed-timestamps or --timestamp-certificate-chain, you must also specify --rfc3161-timestamp-path") + } + if co.UseSignedTimestamps { + tsaCertificates, err := cosign.GetTSACerts(ctx, c.TSACertChainPath, cosign.GetTufTargets) + if err != nil { + return fmt.Errorf("unable to load TSA certificates: %w", err) + } co.TSACertificate = tsaCertificates.LeafCert co.TSARootCertificates = tsaCertificates.RootCert co.TSAIntermediateCertificates = tsaCertificates.IntermediateCerts @@ -172,34 +222,6 @@ func (c *VerifyBlobCmd) Exec(ctx context.Context, blobRef string) error { return err } } - - // Keys are optional! - switch { - case c.KeyRef != "": - co.SigVerifier, err = sigs.PublicKeyFromKeyRef(ctx, c.KeyRef) - if err != nil { - return fmt.Errorf("loading public key: %w", err) - } - pkcs11Key, ok := co.SigVerifier.(*pkcs11key.Key) - if ok { - defer pkcs11Key.Close() - } - case c.Sk: - sk, err := pivkey.GetKeyWithSlot(c.Slot) - if err != nil { - return fmt.Errorf("opening piv token: %w", err) - } - defer sk.Close() - co.SigVerifier, err = sk.Verifier() - if err != nil { - return fmt.Errorf("loading public key from token: %w", err) - } - case c.CertRef != "": - cert, err = loadCertFromFileOrURL(c.CertRef) - if err != nil { - return err - } - } if c.BundlePath != "" { b, err := cosign.FetchLocalSignedPayloadFromPath(c.BundlePath) if err != nil { @@ -300,6 +322,10 @@ func (c *VerifyBlobCmd) Exec(ctx context.Context, blobRef string) error { } } + sig, err := base64signature(c.SigRef, c.BundlePath) + if err != nil { + return err + } signature, err := static.NewSignature(blobBytes, sig, opts...) if err != nil { return err @@ -355,3 +381,24 @@ func payloadBytes(blobRef string) ([]byte, error) { } return blobBytes, nil } + +func payloadDigest(blobRef string) (string, []byte, error) { + hexAlg, hexDigest, ok := strings.Cut(blobRef, ":") + if !ok { + return "", nil, fmt.Errorf("invalid digest format") + } + digestBytes, err := hex.DecodeString(hexDigest) + if err != nil { + return "", nil, err + } + return hexAlg, digestBytes, nil +} + +func loadTrustedRoot(_ context.Context, trustedRootPath string) (*root.TrustedRoot, error) { + if trustedRootPath != "" { + return root.NewTrustedRootFromPath(trustedRootPath) + } + // Assume we're using public good instance; fetch via TUF + // TODO: allow custom TUF settings + return root.FetchTrustedRoot() +} diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/verify/verify_blob_attestation.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/verify/verify_blob_attestation.go index 3f2c33cc63..3d52db7137 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/verify/verify_blob_attestation.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/verify/verify_blob_attestation.go @@ -34,6 +34,7 @@ import ( "github.com/sigstore/cosign/v2/cmd/cosign/cli/rekor" internal "github.com/sigstore/cosign/v2/internal/pkg/cosign" payloadsize "github.com/sigstore/cosign/v2/internal/pkg/cosign/payload/size" + "github.com/sigstore/cosign/v2/internal/ui" "github.com/sigstore/cosign/v2/pkg/blob" "github.com/sigstore/cosign/v2/pkg/cosign" "github.com/sigstore/cosign/v2/pkg/cosign/bundle" @@ -42,6 +43,8 @@ import ( "github.com/sigstore/cosign/v2/pkg/oci/static" "github.com/sigstore/cosign/v2/pkg/policy" sigs "github.com/sigstore/cosign/v2/pkg/signature" + sgbundle "github.com/sigstore/sigstore-go/pkg/bundle" + sgverify "github.com/sigstore/sigstore-go/pkg/verify" "github.com/sigstore/sigstore/pkg/cryptoutils" ) @@ -92,19 +95,6 @@ func (c *VerifyBlobAttestationCommand) Exec(ctx context.Context, artifactPath st return &options.KeyParseError{} } - if c.KeyOpts.NewBundleFormat { - if options.NOf(c.RFC3161TimestampPath, c.TSACertChainPath, c.RekorURL, c.CertChain, c.CARoots, c.CAIntermediates, c.CertRef, c.SCTRef) > 1 { - return fmt.Errorf("when using --new-bundle-format, please supply signed content with --bundle and verification content with --trusted-root") - } - err = verifyNewBundle(ctx, c.BundlePath, c.TrustedRootPath, c.KeyRef, c.Slot, c.CertVerifyOptions.CertOidcIssuer, c.CertVerifyOptions.CertOidcIssuerRegexp, c.CertVerifyOptions.CertIdentity, c.CertVerifyOptions.CertIdentityRegexp, c.CertGithubWorkflowTrigger, c.CertGithubWorkflowSHA, c.CertGithubWorkflowName, c.CertGithubWorkflowRepository, c.CertGithubWorkflowRef, artifactPath, c.Sk, c.IgnoreTlog, c.UseSignedTimestamps, c.IgnoreSCT) - if err == nil { - fmt.Fprintln(os.Stderr, "Verified OK") - } - return err - } else if c.TrustedRootPath != "" { - return fmt.Errorf("--trusted-root only supported with --new-bundle-format") - } - var identities []cosign.Identity if c.KeyRef == "" { identities, err = c.Identities() @@ -123,8 +113,45 @@ func (c *VerifyBlobAttestationCommand) Exec(ctx context.Context, artifactPath st IgnoreSCT: c.IgnoreSCT, Offline: c.Offline, IgnoreTlog: c.IgnoreTlog, + UseSignedTimestamps: c.TSACertChainPath != "" || c.UseSignedTimestamps, + NewBundleFormat: c.KeyOpts.NewBundleFormat || checkNewBundle(c.BundlePath), + } + + // Keys are optional! + var cert *x509.Certificate + opts := make([]static.Option, 0) + switch { + case c.KeyRef != "": + co.SigVerifier, err = sigs.PublicKeyFromKeyRef(ctx, c.KeyRef) + if err != nil { + return fmt.Errorf("loading public key: %w", err) + } + pkcs11Key, ok := co.SigVerifier.(*pkcs11key.Key) + if ok { + defer pkcs11Key.Close() + } + case c.Sk: + sk, err := pivkey.GetKeyWithSlot(c.Slot) + if err != nil { + return fmt.Errorf("opening piv token: %w", err) + } + defer sk.Close() + co.SigVerifier, err = sk.Verifier() + if err != nil { + return fmt.Errorf("loading public key from token: %w", err) + } + case c.CertRef != "": + cert, err = loadCertFromFileOrURL(c.CertRef) + if err != nil { + return err + } + case c.CARoots != "": + // CA roots + possible intermediates are already loaded into co.RootCerts with the call to + // loadCertsKeylessVerification above. } + var h v1.Hash + var digest []byte if c.CheckClaims { // Get the actual digest of the blob var payload internal.HashReader @@ -146,7 +173,7 @@ func (c *VerifyBlobAttestationCommand) Exec(ctx context.Context, artifactPath st if _, err := io.ReadAll(&payload); err != nil { return err } - digest := payload.Sum(nil) + digest = payload.Sum(nil) h = v1.Hash{ Hex: hex.EncodeToString(digest), Algorithm: "sha256", @@ -154,15 +181,44 @@ func (c *VerifyBlobAttestationCommand) Exec(ctx context.Context, artifactPath st co.ClaimVerifier = cosign.IntotoSubjectClaimVerifier } - // Set up TSA, Fulcio roots and tlog public keys and clients. - if c.RFC3161TimestampPath != "" && !(c.TSACertChainPath != "" || c.UseSignedTimestamps) { - return fmt.Errorf("either TSA certificate chain path must be provided or use-signed-timestamps must be set when using RFC3161 timestamp path") + if co.NewBundleFormat { + if options.NOf(c.RFC3161TimestampPath, c.TSACertChainPath, c.CertChain, c.CARoots, c.CAIntermediates, c.CertRef, c.SCTRef) > 0 { + return fmt.Errorf("when using --new-bundle-format, please supply signed content with --bundle and verification content with --trusted-root") + } + + if co.TrustedMaterial == nil { + co.TrustedMaterial, err = loadTrustedRoot(ctx, c.TrustedRootPath) + if err != nil { + return err + } + } + + bundle, err := sgbundle.LoadJSONFromPath(c.BundlePath) + if err != nil { + return err + } + + _, err = cosign.VerifyNewBundle(ctx, co, sgverify.WithArtifactDigest(h.Algorithm, digest), bundle) + if err != nil { + return err + } + + ui.Infof(ctx, "Verified OK") + return nil } - if c.TSACertChainPath != "" || c.UseSignedTimestamps { + if c.TrustedRootPath != "" { + return fmt.Errorf("--trusted-root only supported with --new-bundle-format") + } + if c.RFC3161TimestampPath != "" && !co.UseSignedTimestamps { + return fmt.Errorf("when specifying --rfc3161-timestamp-path, you must also specify --use-signed-timestamps or --timestamp-certificate-chain") + } else if c.RFC3161TimestampPath == "" && co.UseSignedTimestamps { + return fmt.Errorf("when specifying --use-signed-timestamps or --timestamp-certificate-chain, you must also specify --rfc3161-timestamp-path") + } + if co.UseSignedTimestamps { tsaCertificates, err := cosign.GetTSACerts(ctx, c.TSACertChainPath, cosign.GetTufTargets) if err != nil { - return fmt.Errorf("unable to load or get TSA certificates: %w", err) + return fmt.Errorf("unable to load TSA certificates: %w", err) } co.TSACertificate = tsaCertificates.LeafCert co.TSARootCertificates = tsaCertificates.RootCert @@ -206,38 +262,6 @@ func (c *VerifyBlobAttestationCommand) Exec(ctx context.Context, artifactPath st } } - // Keys are optional! - var cert *x509.Certificate - opts := make([]static.Option, 0) - switch { - case c.KeyRef != "": - co.SigVerifier, err = sigs.PublicKeyFromKeyRef(ctx, c.KeyRef) - if err != nil { - return fmt.Errorf("loading public key: %w", err) - } - pkcs11Key, ok := co.SigVerifier.(*pkcs11key.Key) - if ok { - defer pkcs11Key.Close() - } - case c.Sk: - sk, err := pivkey.GetKeyWithSlot(c.Slot) - if err != nil { - return fmt.Errorf("opening piv token: %w", err) - } - defer sk.Close() - co.SigVerifier, err = sk.Verifier() - if err != nil { - return fmt.Errorf("loading public key from token: %w", err) - } - case c.CertRef != "": - cert, err = loadCertFromFileOrURL(c.CertRef) - if err != nil { - return err - } - case c.CARoots != "": - // CA roots + possible intermediates are already loaded into co.RootCerts with the call to - // loadCertsKeylessVerification above. - } if c.BundlePath != "" { b, err := cosign.FetchLocalSignedPayloadFromPath(c.BundlePath) if err != nil { diff --git a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/verify/verify_bundle.go b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/verify/verify_bundle.go index 01921be7ff..3d876f9a5c 100644 --- a/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/verify/verify_bundle.go +++ b/vendor/github.com/sigstore/cosign/v2/cmd/cosign/cli/verify/verify_bundle.go @@ -18,146 +18,165 @@ package verify import ( "bytes" "context" + "crypto/sha256" + "crypto/x509" + "encoding/base64" + "encoding/json" "fmt" - "time" + "github.com/secure-systems-lab/go-securesystemslib/dsse" + protobundle "github.com/sigstore/protobuf-specs/gen/pb-go/bundle/v1" + protocommon "github.com/sigstore/protobuf-specs/gen/pb-go/common/v1" + protodsse "github.com/sigstore/protobuf-specs/gen/pb-go/dsse" + protorekor "github.com/sigstore/protobuf-specs/gen/pb-go/rekor/v1" + "github.com/sigstore/rekor/pkg/generated/client" + "github.com/sigstore/rekor/pkg/tle" sgbundle "github.com/sigstore/sigstore-go/pkg/bundle" - "github.com/sigstore/sigstore-go/pkg/fulcio/certificate" - "github.com/sigstore/sigstore-go/pkg/root" - "github.com/sigstore/sigstore-go/pkg/verify" + "github.com/sigstore/sigstore/pkg/cryptoutils" + "github.com/sigstore/sigstore/pkg/signature" - "github.com/sigstore/cosign/v2/pkg/cosign/pivkey" - sigs "github.com/sigstore/cosign/v2/pkg/signature" + "github.com/sigstore/cosign/v2/pkg/cosign" ) -type verifyTrustedMaterial struct { - root.TrustedMaterial - keyTrustedMaterial root.TrustedMaterial +func checkNewBundle(bundlePath string) bool { + _, err := sgbundle.LoadJSONFromPath(bundlePath) + return err == nil } -func (v *verifyTrustedMaterial) PublicKeyVerifier(hint string) (root.TimeConstrainedVerifier, error) { - return v.keyTrustedMaterial.PublicKeyVerifier(hint) -} - -func verifyNewBundle(ctx context.Context, bundlePath, trustedRootPath, keyRef, slot, certOIDCIssuer, certOIDCIssuerRegex, certIdentity, certIdentityRegexp, githubWorkflowTrigger, githubWorkflowSHA, githubWorkflowName, githubWorkflowRepository, githubWorkflowRef, artifactRef string, sk, ignoreTlog, useSignedTimestamps, ignoreSCT bool) error { - bundle, err := sgbundle.LoadJSONFromPath(bundlePath) +func AssembleNewBundle(ctx context.Context, sigBytes, signedTimestamp []byte, envelope *dsse.Envelope, artifactRef string, cert *x509.Certificate, ignoreTlog bool, sigVerifier signature.Verifier, pkOpts []signature.PublicKeyOption, rekorClient *client.Rekor) (*sgbundle.Bundle, error) { + payload, err := payloadBytes(artifactRef) if err != nil { - return err + return nil, err } + buf := bytes.NewBuffer(payload) + digest := sha256.Sum256(buf.Bytes()) - var trustedroot *root.TrustedRoot + pb := &protobundle.Bundle{ + MediaType: "application/vnd.dev.sigstore.bundle+json;version=0.3", + VerificationMaterial: &protobundle.VerificationMaterial{}, + } - if trustedRootPath == "" { - // Assume we're using public good instance; fetch via TUF - trustedroot, err = root.FetchTrustedRoot() + if envelope != nil && len(envelope.Signatures) > 0 { + sigDecode, err := base64.StdEncoding.DecodeString(envelope.Signatures[0].Sig) if err != nil { - return err + return nil, err } - } else { - trustedroot, err = root.NewTrustedRootFromPath(trustedRootPath) - if err != nil { - return err - } - } - trustedmaterial := &verifyTrustedMaterial{TrustedMaterial: trustedroot} + sig := &protodsse.Signature{ + Sig: sigDecode, + } - // See if we need to wrap trusted root with provided key - if keyRef != "" { - signatureVerifier, err := sigs.PublicKeyFromKeyRef(ctx, keyRef) + payloadDecode, err := base64.StdEncoding.DecodeString(envelope.Payload) if err != nil { - return err + return nil, err } - newExpiringKey := root.NewExpiringKey(signatureVerifier, time.Time{}, time.Time{}) - trustedmaterial.keyTrustedMaterial = root.NewTrustedPublicKeyMaterial(func(_ string) (root.TimeConstrainedVerifier, error) { - return newExpiringKey, nil - }) - } else if sk { - s, err := pivkey.GetKeyWithSlot(slot) + pb.Content = &protobundle.Bundle_DsseEnvelope{ + DsseEnvelope: &protodsse.Envelope{ + Payload: payloadDecode, + PayloadType: envelope.PayloadType, + Signatures: []*protodsse.Signature{sig}, + }, + } + } else { + pb.Content = &protobundle.Bundle_MessageSignature{ + MessageSignature: &protocommon.MessageSignature{ + MessageDigest: &protocommon.HashOutput{ + Algorithm: protocommon.HashAlgorithm_SHA2_256, + Digest: digest[:], + }, + Signature: sigBytes, + }, + } + } + + if cert != nil { + pb.VerificationMaterial.Content = &protobundle.VerificationMaterial_Certificate{ + Certificate: &protocommon.X509Certificate{ + RawBytes: cert.Raw, + }, + } + } else if sigVerifier != nil { + pub, err := sigVerifier.PublicKey(pkOpts...) if err != nil { - return fmt.Errorf("opening piv token: %w", err) + return nil, err } - defer s.Close() - signatureVerifier, err := s.Verifier() + pubKeyBytes, err := x509.MarshalPKIXPublicKey(pub) if err != nil { - return fmt.Errorf("loading public key from token: %w", err) + return nil, err } + hashedBytes := sha256.Sum256(pubKeyBytes) - newExpiringKey := root.NewExpiringKey(signatureVerifier, time.Time{}, time.Time{}) - trustedmaterial.keyTrustedMaterial = root.NewTrustedPublicKeyMaterial(func(_ string) (root.TimeConstrainedVerifier, error) { - return newExpiringKey, nil - }) + pb.VerificationMaterial.Content = &protobundle.VerificationMaterial_PublicKey{ + PublicKey: &protocommon.PublicKeyIdentifier{ + Hint: base64.StdEncoding.EncodeToString(hashedBytes[:]), + }, + } } - identityPolicies := []verify.PolicyOption{} - - verificationMaterial := bundle.GetVerificationMaterial() + if len(signedTimestamp) > 0 { + ts := &protocommon.RFC3161SignedTimestamp{ + SignedTimestamp: signedTimestamp, + } - if verificationMaterial == nil { - return fmt.Errorf("no verification material in bundle") + pb.VerificationMaterial.TimestampVerificationData = &protobundle.TimestampVerificationData{ + Rfc3161Timestamps: []*protocommon.RFC3161SignedTimestamp{ts}, + } } - if verificationMaterial.GetPublicKey() != nil { - identityPolicies = append(identityPolicies, verify.WithKey()) - } else { - sanMatcher, err := verify.NewSANMatcher(certIdentity, certIdentityRegexp) - if err != nil { - return err + if !ignoreTlog { + var pem []byte + var err error + if cert != nil { + pem, err = cryptoutils.MarshalCertificateToPEM(cert) + if err != nil { + return nil, err + } + } else if sigVerifier != nil { + pub, err := sigVerifier.PublicKey(pkOpts...) + if err != nil { + return nil, err + } + pem, err = cryptoutils.MarshalPublicKeyToPEM(pub) + if err != nil { + return nil, err + } + } + var sigB64 string + var payload []byte + if envelope != nil && len(envelope.Signatures) > 0 { + payload, err = json.Marshal(*envelope) + if err != nil { + return nil, err + } + } else { + sigB64 = base64.StdEncoding.EncodeToString(sigBytes) + payload = buf.Bytes() } - issuerMatcher, err := verify.NewIssuerMatcher(certOIDCIssuer, certOIDCIssuerRegex) + tlogEntries, err := cosign.FindTlogEntry(ctx, rekorClient, sigB64, payload, pem) if err != nil { - return err + return nil, err } - - extensions := certificate.Extensions{ - GithubWorkflowTrigger: githubWorkflowTrigger, - GithubWorkflowSHA: githubWorkflowSHA, - GithubWorkflowName: githubWorkflowName, - GithubWorkflowRepository: githubWorkflowRepository, - GithubWorkflowRef: githubWorkflowRef, + if len(tlogEntries) == 0 { + return nil, fmt.Errorf("unable to find tlog entry") + } + if len(tlogEntries) > 1 { + return nil, fmt.Errorf("too many tlog entries; should only have 1") } - certIdentity, err := verify.NewCertificateIdentity(sanMatcher, issuerMatcher, extensions) + tlogEntry, err := tle.GenerateTransparencyLogEntry(tlogEntries[0]) if err != nil { - return err + return nil, err } - identityPolicies = append(identityPolicies, verify.WithCertificateIdentity(certIdentity)) - } - - // Make some educated guesses about verification policy - verifierConfig := []verify.VerifierOption{} - - if len(trustedroot.RekorLogs()) > 0 && !ignoreTlog { - verifierConfig = append(verifierConfig, verify.WithTransparencyLog(1), verify.WithIntegratedTimestamps(1)) - } - - if len(trustedroot.TimestampingAuthorities()) > 0 && useSignedTimestamps { - verifierConfig = append(verifierConfig, verify.WithSignedTimestamps(1)) + pb.VerificationMaterial.TlogEntries = []*protorekor.TransparencyLogEntry{tlogEntry} } - if !ignoreSCT { - verifierConfig = append(verifierConfig, verify.WithSignedCertificateTimestamps(1)) - } - - if ignoreTlog && !useSignedTimestamps { - verifierConfig = append(verifierConfig, verify.WithoutAnyObserverTimestampsUnsafe()) - } - - // Perform verification - payload, err := payloadBytes(artifactRef) - if err != nil { - return err - } - buf := bytes.NewBuffer(payload) - - sev, err := verify.NewSignedEntityVerifier(trustedmaterial, verifierConfig...) + b, err := sgbundle.NewBundle(pb) if err != nil { - return err + return nil, err } - _, err = sev.Verify(bundle, verify.NewPolicy(verify.WithArtifact(buf), identityPolicies...)) - return err + return b, nil } diff --git a/vendor/github.com/sigstore/cosign/v2/internal/pkg/cosign/tsa/client/client.go b/vendor/github.com/sigstore/cosign/v2/internal/pkg/cosign/tsa/client/client.go index b50531834e..52aa11b998 100644 --- a/vendor/github.com/sigstore/cosign/v2/internal/pkg/cosign/tsa/client/client.go +++ b/vendor/github.com/sigstore/cosign/v2/internal/pkg/cosign/tsa/client/client.go @@ -26,7 +26,6 @@ import ( "time" "github.com/digitorus/timestamp" - "github.com/pkg/errors" ) // TimestampAuthorityClient should be implemented by clients that want to request timestamp responses @@ -133,13 +132,13 @@ func (t *TimestampAuthorityClientImpl) GetTimestampResponse(tsq []byte) ([]byte, req, err := http.NewRequest("POST", t.URL, bytes.NewReader(tsq)) if err != nil { - return nil, errors.Wrap(err, "error creating HTTP request") + return nil, fmt.Errorf("error creating HTTP request: %w", err) } req.Header.Set("Content-Type", "application/timestamp-query") tsr, err := client.Do(req) if err != nil { - return nil, errors.Wrap(err, "error making request to timestamp authority") + return nil, fmt.Errorf("error making request to timestamp authority: %w", err) } if tsr.StatusCode != 200 && tsr.StatusCode != 201 { return nil, fmt.Errorf("request to timestamp authority failed with status code %d", tsr.StatusCode) @@ -147,7 +146,7 @@ func (t *TimestampAuthorityClientImpl) GetTimestampResponse(tsq []byte) ([]byte, resp, err := io.ReadAll(tsr.Body) if err != nil { - return nil, errors.Wrap(err, "error reading timestamp response") + return nil, fmt.Errorf("error reading timestamp response: %w", err) } // validate that the timestamp response is parseable diff --git a/vendor/github.com/sigstore/cosign/v2/internal/pkg/cosign/tsa/signer.go b/vendor/github.com/sigstore/cosign/v2/internal/pkg/cosign/tsa/signer.go index 99c0540215..9fb0b66b40 100644 --- a/vendor/github.com/sigstore/cosign/v2/internal/pkg/cosign/tsa/signer.go +++ b/vendor/github.com/sigstore/cosign/v2/internal/pkg/cosign/tsa/signer.go @@ -18,12 +18,12 @@ import ( "bytes" "context" "crypto" + "fmt" "io" "strconv" "strings" "github.com/digitorus/timestamp" - "github.com/pkg/errors" "github.com/sigstore/cosign/v2/internal/pkg/cosign" "github.com/sigstore/cosign/v2/internal/pkg/cosign/tsa/client" "github.com/sigstore/cosign/v2/pkg/cosign/bundle" @@ -38,7 +38,7 @@ import ( func GetTimestampedSignature(sigBytes []byte, tsaClient client.TimestampAuthorityClient) ([]byte, error) { requestBytes, err := createTimestampAuthorityRequest(sigBytes, crypto.SHA256, "") if err != nil { - return nil, errors.Wrap(err, "error creating timestamp request") + return nil, fmt.Errorf("error creating timestamp request: %w", err) } return tsaClient.GetTimestampResponse(requestBytes) diff --git a/vendor/github.com/sigstore/cosign/v2/pkg/blob/load.go b/vendor/github.com/sigstore/cosign/v2/pkg/blob/load.go index 543af56fac..8ee624e93a 100644 --- a/vendor/github.com/sigstore/cosign/v2/pkg/blob/load.go +++ b/vendor/github.com/sigstore/cosign/v2/pkg/blob/load.go @@ -15,6 +15,9 @@ package blob import ( + "crypto/sha256" + "crypto/sha512" + "encoding/hex" "fmt" "io" "net/http" @@ -72,3 +75,35 @@ func LoadFileOrURL(fileRef string) ([]byte, error) { } return raw, nil } + +func LoadFileOrURLWithChecksum(fileRef string, checksum string) ([]byte, error) { + checksumParts := strings.Split(checksum, ":") + if len(checksumParts) >= 3 { + return nil, fmt.Errorf("wrong checksum input format, must have at most 1 colon: %s", checksum) + } + + checksumAlgo := sha256.New() + checksumValue := checksumParts[len(checksumParts)-1] + if len(checksumParts) == 2 { + switch checksumParts[0] { + case "sha256": // the default set above + case "sha512": + checksumAlgo = sha512.New() + default: + return nil, fmt.Errorf("unsupported checksum algorithm: %s", checksumParts[0]) + } + } + + fileContent, err := LoadFileOrURL(fileRef) + if err != nil { + return nil, err + } + + checksumAlgo.Write(fileContent) + computedChecksum := hex.EncodeToString(checksumAlgo.Sum(nil)) + if computedChecksum != checksumValue { + return nil, fmt.Errorf("incorrect checksum for file %s: expected %s but got %s", fileRef, checksumValue, computedChecksum) + } + + return fileContent, nil +} diff --git a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/attestation/attestation.go b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/attestation/attestation.go index f5a8e9ebe3..e675088d58 100644 --- a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/attestation/attestation.go +++ b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/attestation/attestation.go @@ -23,10 +23,9 @@ import ( "strings" "time" + "github.com/in-toto/in-toto-golang/in_toto" slsa02 "github.com/in-toto/in-toto-golang/in_toto/slsa_provenance/v0.2" slsa1 "github.com/in-toto/in-toto-golang/in_toto/slsa_provenance/v1" - - "github.com/in-toto/in-toto-golang/in_toto" ) const ( diff --git a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/fetch.go b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/fetch.go index ff81be227b..709333ac77 100644 --- a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/fetch.go +++ b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/fetch.go @@ -74,8 +74,15 @@ func FetchSignaturesForReference(_ context.Context, ref name.Reference, opts ... if err != nil { return nil, err } + sigs, err := FetchSignatures(simg) + if err != nil { + return nil, fmt.Errorf("%s: %w", ref, err) + } + return sigs, nil +} - sigs, err := simg.Signatures() +func FetchSignatures(se oci.SignedEntity) ([]SignedPayload, error) { + sigs, err := se.Signatures() if err != nil { return nil, fmt.Errorf("remote image: %w", err) } @@ -84,7 +91,7 @@ func FetchSignaturesForReference(_ context.Context, ref name.Reference, opts ... return nil, fmt.Errorf("fetching signatures: %w", err) } if len(l) == 0 { - return nil, fmt.Errorf("no signatures associated with %s", ref) + return nil, errors.New("no signatures associated") } if len(l) > maxAllowedSigsOrAtts { return nil, fmt.Errorf("maximum number of signatures on an image is %d, found %d", maxAllowedSigsOrAtts, len(l)) diff --git a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/git/gitlab/gitlab.go b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/git/gitlab/gitlab.go index 6703635a09..b124691321 100644 --- a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/git/gitlab/gitlab.go +++ b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/git/gitlab/gitlab.go @@ -24,7 +24,7 @@ import ( "github.com/sigstore/cosign/v2/internal/ui" "github.com/sigstore/cosign/v2/pkg/cosign" "github.com/sigstore/cosign/v2/pkg/cosign/env" - "github.com/xanzy/go-gitlab" + gitlab "gitlab.com/gitlab-org/api/client-go" ) const ( diff --git a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/kubernetes/client.go b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/kubernetes/client.go index c89a4e0b45..5c0f59b958 100644 --- a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/kubernetes/client.go +++ b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/kubernetes/client.go @@ -17,9 +17,9 @@ package kubernetes import ( "fmt" + utilversion "k8s.io/apimachinery/pkg/util/version" "k8s.io/client-go/kubernetes" - utilversion "k8s.io/apimachinery/pkg/util/version" // Initialize all known client auth plugins _ "k8s.io/client-go/plugin/pkg/client/auth" "k8s.io/client-go/rest" diff --git a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/kubernetes/secret.go b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/kubernetes/secret.go index b05c235e41..1128988819 100644 --- a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/kubernetes/secret.go +++ b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/kubernetes/secret.go @@ -21,12 +21,11 @@ import ( "os" "strings" + "github.com/sigstore/cosign/v2/pkg/cosign" v1 "k8s.io/api/core/v1" k8serrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/utils/ptr" - - "github.com/sigstore/cosign/v2/pkg/cosign" ) const ( diff --git a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/pivkey/pivkey.go b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/pivkey/pivkey.go index d179e301a6..4f765bbc51 100644 --- a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/pivkey/pivkey.go +++ b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/pivkey/pivkey.go @@ -31,10 +31,9 @@ import ( "os" "syscall" - "github.com/go-piv/piv-go/piv" - "golang.org/x/term" - + "github.com/go-piv/piv-go/v2/piv" "github.com/sigstore/sigstore/pkg/signature" + "golang.org/x/term" ) var ( @@ -113,7 +112,7 @@ func (k *Key) GetAttestationCertificate() (*x509.Certificate, error) { return k.card.AttestationCertificate() } -func (k *Key) SetManagementKey(old, new [24]byte) error { +func (k *Key) SetManagementKey(old, new []byte) error { if k.card == nil { return KeyNotInitialized } @@ -153,7 +152,7 @@ func (k *Key) Unblock(puk, newPIN string) error { return k.card.Unblock(puk, newPIN) } -func (k *Key) GenerateKey(mgmtKey [24]byte, slot piv.Slot, opts piv.Key) (crypto.PublicKey, error) { +func (k *Key) GenerateKey(mgmtKey []byte, slot piv.Slot, opts piv.Key) (crypto.PublicKey, error) { if k.card == nil { return nil, KeyNotInitialized } diff --git a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/pivkey/util.go b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/pivkey/util.go index a323716e6b..cb5c4b0a07 100644 --- a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/pivkey/util.go +++ b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/pivkey/util.go @@ -18,7 +18,7 @@ package pivkey import ( - "github.com/go-piv/piv-go/piv" + "github.com/go-piv/piv-go/v2/piv" ) func SlotForName(slotName string) *piv.Slot { diff --git a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/rego/rego.go b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/rego/rego.go index 3d99115fb6..ccc58ec467 100644 --- a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/rego/rego.go +++ b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/rego/rego.go @@ -22,7 +22,8 @@ import ( "errors" "fmt" - "github.com/open-policy-agent/opa/rego" + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/rego" ) // The query below should meet the following requirements: @@ -48,7 +49,9 @@ func ValidateJSON(jsonBody []byte, entrypoints []string) []error { r := rego.New( rego.Query(QUERY), - rego.Load(entrypoints, nil)) + rego.Load(entrypoints, nil), + rego.SetRegoVersion(ast.RegoV0), + ) query, err := r.PrepareForEval(ctx) if err != nil { @@ -97,7 +100,9 @@ func ValidateJSONWithModuleInput(jsonBody []byte, moduleInput string) (warnings r := rego.New( rego.Query(query), - rego.Module(module, moduleInput)) + rego.Module(module, moduleInput), + rego.SetRegoVersion(ast.RegoV0), + ) evalQuery, err := r.PrepareForEval(ctx) if err != nil { @@ -130,8 +135,8 @@ func ValidateJSONWithModuleInput(jsonBody []byte, moduleInput string) (warnings return nil, fmt.Errorf("policy is not compliant for query '%s'", query) } -func evaluateRegoEvalMapResult(query string, response []interface{}) (warning error, error error) { - error = fmt.Errorf("policy is not compliant for query %q", query) //nolint: revive +func evaluateRegoEvalMapResult(query string, response []interface{}) (warning error, retErr error) { + retErr = fmt.Errorf("policy is not compliant for query %q", query) //nolint: revive for _, r := range response { rMap := r.(map[string]interface{}) mapBytes, err := json.Marshal(rMap) @@ -152,7 +157,7 @@ func evaluateRegoEvalMapResult(query string, response []interface{}) (warning er return fmt.Errorf("warning: %s", resultObject.Warning), nil } warning = errors.New(resultObject.Warning) - error = fmt.Errorf("policy is not compliant for query '%s' with errors: %s", query, resultObject.Error) //nolint: revive + retErr = fmt.Errorf("policy is not compliant for query '%s' with errors: %s", query, resultObject.Error) //nolint: revive } - return warning, error + return warning, retErr } diff --git a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/tlog.go b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/tlog.go index 83d6f61f17..a9379ba941 100644 --- a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/tlog.go +++ b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/tlog.go @@ -32,9 +32,6 @@ import ( "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" - "github.com/transparency-dev/merkle/proof" - "github.com/transparency-dev/merkle/rfc6962" - "github.com/sigstore/cosign/v2/internal/ui" "github.com/sigstore/cosign/v2/pkg/cosign/bundle" "github.com/sigstore/cosign/v2/pkg/cosign/env" @@ -49,6 +46,8 @@ import ( intoto_v001 "github.com/sigstore/rekor/pkg/types/intoto/v0.0.1" "github.com/sigstore/sigstore/pkg/cryptoutils" "github.com/sigstore/sigstore/pkg/tuf" + "github.com/transparency-dev/merkle/proof" + "github.com/transparency-dev/merkle/rfc6962" ) // This is the rekor transparency log public key target name diff --git a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/tsa.go b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/tsa.go index 9d1c17a333..c2032f396e 100644 --- a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/tsa.go +++ b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/tsa.go @@ -74,7 +74,7 @@ func isTufTargetExist(ctx context.Context, name string) (bool, error) { // TUF root. If expired, makes a network call to retrieve the updated targets. // By default, the certificates come from TUF, but you can override this for test // purposes by using an env variable `SIGSTORE_TSA_CERTIFICATE_FILE` or a file path -// specified in `TSACertChainPath`. If using an alternate, the file should be in PEM format. +// specified in `certChainPath`. If using an alternate, the file should be in PEM format. func GetTSACerts(ctx context.Context, certChainPath string, fn GetTargetStub) (*TSACertificates, error) { altTSACert := env.Getenv(env.VariableSigstoreTSACertificateFile) diff --git a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/verify.go b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/verify.go index 3ab5d76026..e565052d6b 100644 --- a/vendor/github.com/sigstore/cosign/v2/pkg/cosign/verify.go +++ b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/verify.go @@ -26,6 +26,7 @@ import ( "encoding/hex" "encoding/json" "encoding/pem" + "errors" "fmt" "io/fs" "net/http" @@ -34,29 +35,24 @@ import ( "strings" "time" - "github.com/pkg/errors" - + "github.com/cyberphone/json-canonicalization/go/src/webpki.org/jsoncanonicalizer" "github.com/digitorus/timestamp" "github.com/go-openapi/runtime" - "github.com/nozzle/throttler" - - "github.com/sigstore/cosign/v2/internal/pkg/cosign" - "github.com/sigstore/cosign/v2/pkg/blob" - cbundle "github.com/sigstore/cosign/v2/pkg/cosign/bundle" - "github.com/sigstore/cosign/v2/pkg/oci/static" - "github.com/sigstore/cosign/v2/pkg/types" - - "github.com/cyberphone/json-canonicalization/go/src/webpki.org/jsoncanonicalizer" "github.com/google/go-containerregistry/pkg/name" v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/remote/transport" - + "github.com/nozzle/throttler" ssldsse "github.com/secure-systems-lab/go-securesystemslib/dsse" + "github.com/sigstore/cosign/v2/internal/pkg/cosign" ociexperimental "github.com/sigstore/cosign/v2/internal/pkg/oci/remote" "github.com/sigstore/cosign/v2/internal/ui" + "github.com/sigstore/cosign/v2/pkg/blob" + cbundle "github.com/sigstore/cosign/v2/pkg/cosign/bundle" "github.com/sigstore/cosign/v2/pkg/oci" "github.com/sigstore/cosign/v2/pkg/oci/layout" ociremote "github.com/sigstore/cosign/v2/pkg/oci/remote" + "github.com/sigstore/cosign/v2/pkg/oci/static" + "github.com/sigstore/cosign/v2/pkg/types" "github.com/sigstore/rekor/pkg/generated/client" "github.com/sigstore/rekor/pkg/generated/models" rekor_types "github.com/sigstore/rekor/pkg/types" @@ -65,6 +61,9 @@ import ( intoto_v001 "github.com/sigstore/rekor/pkg/types/intoto/v0.0.1" intoto_v002 "github.com/sigstore/rekor/pkg/types/intoto/v0.0.2" rekord_v001 "github.com/sigstore/rekor/pkg/types/rekord/v0.0.1" + "github.com/sigstore/sigstore-go/pkg/fulcio/certificate" + "github.com/sigstore/sigstore-go/pkg/root" + "github.com/sigstore/sigstore-go/pkg/verify" "github.com/sigstore/sigstore/pkg/cryptoutils" "github.com/sigstore/sigstore/pkg/signature" "github.com/sigstore/sigstore/pkg/signature/dsse" @@ -152,6 +151,8 @@ type CheckOpts struct { TSARootCertificates []*x509.Certificate // TSAIntermediateCertificates are the set of intermediates for chain building TSAIntermediateCertificates []*x509.Certificate + // UseSignedTimestamps enables timestamp verification using a TSA + UseSignedTimestamps bool // IgnoreTlog skip tlog verification IgnoreTlog bool @@ -163,6 +164,89 @@ type CheckOpts struct { // Should the experimental OCI 1.1 behaviour be enabled or not. // Defaults to false. ExperimentalOCI11 bool + + // NewBundleFormat enables the new bundle format (Cosign Bundle Spec) and the new verifier. + NewBundleFormat bool + + // TrustedMaterial is the trusted material to use for verification. + // Currently, this is only applicable when NewBundleFormat is true. + TrustedMaterial root.TrustedMaterial +} + +type verifyTrustedMaterial struct { + root.TrustedMaterial + keyTrustedMaterial root.TrustedMaterial +} + +func (v *verifyTrustedMaterial) PublicKeyVerifier(hint string) (root.TimeConstrainedVerifier, error) { + return v.keyTrustedMaterial.PublicKeyVerifier(hint) +} + +// verificationOptions returns the verification options for verifying with sigstore-go. +func (co *CheckOpts) verificationOptions() (trustedMaterial root.TrustedMaterial, verifierOptions []verify.VerifierOption, policyOptions []verify.PolicyOption, err error) { + policyOptions = make([]verify.PolicyOption, 0) + + if len(co.Identities) > 0 { + var sanMatcher verify.SubjectAlternativeNameMatcher + var issuerMatcher verify.IssuerMatcher + if len(co.Identities) > 1 { + return nil, nil, nil, fmt.Errorf("unsupported: multiple identities are not supported at this time") + } + sanMatcher, err = verify.NewSANMatcher(co.Identities[0].Subject, co.Identities[0].SubjectRegExp) + if err != nil { + return nil, nil, nil, err + } + + issuerMatcher, err = verify.NewIssuerMatcher(co.Identities[0].Issuer, co.Identities[0].IssuerRegExp) + if err != nil { + return nil, nil, nil, err + } + + extensions := certificate.Extensions{ + GithubWorkflowTrigger: co.CertGithubWorkflowTrigger, + GithubWorkflowSHA: co.CertGithubWorkflowSha, + GithubWorkflowName: co.CertGithubWorkflowName, + GithubWorkflowRepository: co.CertGithubWorkflowRepository, + GithubWorkflowRef: co.CertGithubWorkflowRef, + } + + certificateIdentities, err := verify.NewCertificateIdentity(sanMatcher, issuerMatcher, extensions) + if err != nil { + return nil, nil, nil, err + } + policyOptions = []verify.PolicyOption{verify.WithCertificateIdentity(certificateIdentities)} + } + + // Wrap TrustedMaterial + vTrustedMaterial := &verifyTrustedMaterial{TrustedMaterial: co.TrustedMaterial} + + verifierOptions = make([]verify.VerifierOption, 0) + + if co.SigVerifier != nil { + // We are verifying with a public key + policyOptions = append(policyOptions, verify.WithKey()) + newExpiringKey := root.NewExpiringKey(co.SigVerifier, time.Time{}, time.Time{}) + vTrustedMaterial.keyTrustedMaterial = root.NewTrustedPublicKeyMaterial(func(_ string) (root.TimeConstrainedVerifier, error) { + return newExpiringKey, nil + }) + } else { //nolint:gocritic + // We are verifying with a certificate + if !co.IgnoreSCT { + verifierOptions = append(verifierOptions, verify.WithSignedCertificateTimestamps(1)) + } + } + + if !co.IgnoreTlog { + verifierOptions = append(verifierOptions, verify.WithTransparencyLog(1), verify.WithIntegratedTimestamps(1)) + } + if co.UseSignedTimestamps { + verifierOptions = append(verifierOptions, verify.WithSignedTimestamps(1)) + } + if co.IgnoreTlog && !co.UseSignedTimestamps { + verifierOptions = append(verifierOptions, verify.WithCurrentTime()) + } + + return vTrustedMaterial, verifierOptions, policyOptions, nil } // This is a substitutable signature verification function that can be used for verifying @@ -660,18 +744,21 @@ func verifySignatures(ctx context.Context, sigs oci.Signatures, h v1.Hash, co *C // a. Verifies the Rekor entry in the bundle, if provided. This works offline OR // b. If we don't have a Rekor entry retrieved via cert, do an online lookup (assuming // we are in experimental mode). -// 3. If a certificate is provided, check it's expiration using the transparency log timestamp. +// 3. If a certificate is provided, check its expiration using the transparency log timestamp. func verifyInternal(ctx context.Context, sig oci.Signature, h v1.Hash, verifyFn signatureVerificationFn, co *CheckOpts) ( bundleVerified bool, err error) { var acceptableRFC3161Time, acceptableRekorBundleTime *time.Time // Timestamps for the signature we accept, or nil if not applicable. - acceptableRFC3161Timestamp, err := VerifyRFC3161Timestamp(sig, co) - if err != nil { - return false, fmt.Errorf("unable to verify RFC3161 timestamp bundle: %w", err) - } - if acceptableRFC3161Timestamp != nil { - acceptableRFC3161Time = &acceptableRFC3161Timestamp.Time + var acceptableRFC3161Timestamp *timestamp.Timestamp + if co.UseSignedTimestamps { + acceptableRFC3161Timestamp, err = VerifyRFC3161Timestamp(sig, co) + if err != nil { + return false, fmt.Errorf("unable to verify RFC3161 timestamp bundle: %w", err) + } + if acceptableRFC3161Timestamp != nil { + acceptableRFC3161Time = &acceptableRFC3161Timestamp.Time + } } if !co.IgnoreTlog { diff --git a/vendor/github.com/xanzy/go-gitlab/pages.go b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/verify_bundle.go similarity index 51% rename from vendor/github.com/xanzy/go-gitlab/pages.go rename to vendor/github.com/sigstore/cosign/v2/pkg/cosign/verify_bundle.go index 617b0ba4b9..85a9a66028 100644 --- a/vendor/github.com/xanzy/go-gitlab/pages.go +++ b/vendor/github.com/sigstore/cosign/v2/pkg/cosign/verify_bundle.go @@ -1,5 +1,5 @@ // -// Copyright 2021, Sander van Harmelen +// Copyright 2025 The Sigstore Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,34 +12,24 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// -package gitlab +package cosign import ( - "fmt" - "net/http" -) + "context" -type PagesService struct { - client *Client -} + "github.com/sigstore/sigstore-go/pkg/verify" +) -// UnpublishPages unpublished pages. The user must have admin privileges. -// -// GitLab API docs: -// https://docs.gitlab.com/ee/api/pages.html#unpublish-pages -func (s *PagesService) UnpublishPages(gid interface{}, options ...RequestOptionFunc) (*Response, error) { - page, err := parseID(gid) +// VerifyNewBundle verifies a SigstoreBundle with the given parameters +func VerifyNewBundle(_ context.Context, co *CheckOpts, artifactPolicyOption verify.ArtifactPolicyOption, bundle verify.SignedEntity) (*verify.VerificationResult, error) { + trustedMaterial, verifierOptions, policyOptions, err := co.verificationOptions() if err != nil { return nil, err } - u := fmt.Sprintf("projects/%s/pages", PathEscape(page)) - - req, err := s.client.NewRequest(http.MethodDelete, u, nil, options) + verifier, err := verify.NewSignedEntityVerifier(trustedMaterial, verifierOptions...) if err != nil { return nil, err } - - return s.client.Do(req, nil) + return verifier.Verify(bundle, verify.NewPolicy(artifactPolicyOption, policyOptions...)) } diff --git a/vendor/github.com/sigstore/cosign/v2/pkg/oci/remote/options.go b/vendor/github.com/sigstore/cosign/v2/pkg/oci/remote/options.go index 0a7f23842b..6eeaadd010 100644 --- a/vendor/github.com/sigstore/cosign/v2/pkg/oci/remote/options.go +++ b/vendor/github.com/sigstore/cosign/v2/pkg/oci/remote/options.go @@ -113,6 +113,14 @@ func WithRemoteOptions(opts ...remote.Option) Option { } } +// WithMoreRemoteOptions is a functional option for adding to the default +// remote options already specified +func WithMoreRemoteOptions(opts ...remote.Option) Option { + return func(o *options) { + o.ROpt = append(o.ROpt, opts...) + } +} + // WithTargetRepository is a functional option for overriding the default // target repository hosting the signature and attestation tags. func WithTargetRepository(repo name.Repository) Option { diff --git a/vendor/github.com/sigstore/cosign/v2/pkg/policy/attestation.go b/vendor/github.com/sigstore/cosign/v2/pkg/policy/attestation.go index 1fa82bf8a6..63377d4422 100644 --- a/vendor/github.com/sigstore/cosign/v2/pkg/policy/attestation.go +++ b/vendor/github.com/sigstore/cosign/v2/pkg/policy/attestation.go @@ -23,10 +23,9 @@ import ( "fmt" "github.com/in-toto/in-toto-golang/in_toto" - "github.com/sigstore/cosign/v2/pkg/oci" - "github.com/sigstore/cosign/v2/cmd/cosign/cli/options" "github.com/sigstore/cosign/v2/pkg/cosign/attestation" + "github.com/sigstore/cosign/v2/pkg/oci" ) // PayloadProvider is a subset of oci.Signature that only provides the diff --git a/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/bundle/v1/sigstore_bundle.pb.go b/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/bundle/v1/sigstore_bundle.pb.go index b3f44d1f9f..80198530de 100644 --- a/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/bundle/v1/sigstore_bundle.pb.go +++ b/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/bundle/v1/sigstore_bundle.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.6 +// protoc-gen-go v1.36.3 +// protoc v5.29.3 // source: sigstore_bundle.proto package v1 @@ -42,25 +42,22 @@ const ( // Currently only RFC3161 signatures are provided. More formats may be added // in the future. type TimestampVerificationData struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // A list of RFC3161 signed timestamps provided by the user. // This can be used when the entry has not been stored on a // transparency log, or in conjunction for a stronger trust model. // Clients MUST verify the hashed message in the message imprint // against the signature in the bundle. Rfc3161Timestamps []*v1.RFC3161SignedTimestamp `protobuf:"bytes,1,rep,name=rfc3161_timestamps,json=rfc3161Timestamps,proto3" json:"rfc3161_timestamps,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *TimestampVerificationData) Reset() { *x = TimestampVerificationData{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_bundle_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_bundle_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *TimestampVerificationData) String() string { @@ -71,7 +68,7 @@ func (*TimestampVerificationData) ProtoMessage() {} func (x *TimestampVerificationData) ProtoReflect() protoreflect.Message { mi := &file_sigstore_bundle_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -103,10 +100,7 @@ func (x *TimestampVerificationData) GetRfc3161Timestamps() []*v1.RFC3161SignedTi // the key identifier, it MUST match the `keyid` field of the signature the // extension is attached to. type VerificationMaterial struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The key material for verification purposes. // // This allows key material to be conveyed in one of three forms: @@ -141,7 +135,7 @@ type VerificationMaterial struct { // When used in a `0.3` bundle with the PGI and "keyless" signing, // form (3) MUST be used. // - // Types that are assignable to Content: + // Types that are valid to be assigned to Content: // // *VerificationMaterial_PublicKey // *VerificationMaterial_X509CertificateChain @@ -158,15 +152,15 @@ type VerificationMaterial struct { // Timestamp may also come from // tlog_entries.inclusion_promise.signed_entry_timestamp. TimestampVerificationData *TimestampVerificationData `protobuf:"bytes,4,opt,name=timestamp_verification_data,json=timestampVerificationData,proto3" json:"timestamp_verification_data,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *VerificationMaterial) Reset() { *x = VerificationMaterial{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_bundle_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_bundle_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *VerificationMaterial) String() string { @@ -177,7 +171,7 @@ func (*VerificationMaterial) ProtoMessage() {} func (x *VerificationMaterial) ProtoReflect() protoreflect.Message { mi := &file_sigstore_bundle_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -192,30 +186,36 @@ func (*VerificationMaterial) Descriptor() ([]byte, []int) { return file_sigstore_bundle_proto_rawDescGZIP(), []int{1} } -func (m *VerificationMaterial) GetContent() isVerificationMaterial_Content { - if m != nil { - return m.Content +func (x *VerificationMaterial) GetContent() isVerificationMaterial_Content { + if x != nil { + return x.Content } return nil } func (x *VerificationMaterial) GetPublicKey() *v1.PublicKeyIdentifier { - if x, ok := x.GetContent().(*VerificationMaterial_PublicKey); ok { - return x.PublicKey + if x != nil { + if x, ok := x.Content.(*VerificationMaterial_PublicKey); ok { + return x.PublicKey + } } return nil } func (x *VerificationMaterial) GetX509CertificateChain() *v1.X509CertificateChain { - if x, ok := x.GetContent().(*VerificationMaterial_X509CertificateChain); ok { - return x.X509CertificateChain + if x != nil { + if x, ok := x.Content.(*VerificationMaterial_X509CertificateChain); ok { + return x.X509CertificateChain + } } return nil } func (x *VerificationMaterial) GetCertificate() *v1.X509Certificate { - if x, ok := x.GetContent().(*VerificationMaterial_Certificate); ok { - return x.Certificate + if x != nil { + if x, ok := x.Content.(*VerificationMaterial_Certificate); ok { + return x.Certificate + } } return nil } @@ -257,10 +257,7 @@ func (*VerificationMaterial_X509CertificateChain) isVerificationMaterial_Content func (*VerificationMaterial_Certificate) isVerificationMaterial_Content() {} type Bundle struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // MUST be application/vnd.dev.sigstore.bundle.v0.3+json when // when encoded as JSON. // Clients must to be able to accept media type using the previously @@ -279,20 +276,20 @@ type Bundle struct { // MUST be exactly the same in the verification material and in the // DSSE envelope. VerificationMaterial *VerificationMaterial `protobuf:"bytes,2,opt,name=verification_material,json=verificationMaterial,proto3" json:"verification_material,omitempty"` - // Types that are assignable to Content: + // Types that are valid to be assigned to Content: // // *Bundle_MessageSignature // *Bundle_DsseEnvelope - Content isBundle_Content `protobuf_oneof:"content"` + Content isBundle_Content `protobuf_oneof:"content"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Bundle) Reset() { *x = Bundle{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_bundle_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_bundle_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *Bundle) String() string { @@ -303,7 +300,7 @@ func (*Bundle) ProtoMessage() {} func (x *Bundle) ProtoReflect() protoreflect.Message { mi := &file_sigstore_bundle_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -332,23 +329,27 @@ func (x *Bundle) GetVerificationMaterial() *VerificationMaterial { return nil } -func (m *Bundle) GetContent() isBundle_Content { - if m != nil { - return m.Content +func (x *Bundle) GetContent() isBundle_Content { + if x != nil { + return x.Content } return nil } func (x *Bundle) GetMessageSignature() *v1.MessageSignature { - if x, ok := x.GetContent().(*Bundle_MessageSignature); ok { - return x.MessageSignature + if x != nil { + if x, ok := x.Content.(*Bundle_MessageSignature); ok { + return x.MessageSignature + } } return nil } func (x *Bundle) GetDsseEnvelope() *dsse.Envelope { - if x, ok := x.GetContent().(*Bundle_DsseEnvelope); ok { - return x.DsseEnvelope + if x != nil { + if x, ok := x.Content.(*Bundle_DsseEnvelope); ok { + return x.DsseEnvelope + } } return nil } @@ -367,10 +368,10 @@ type Bundle_DsseEnvelope struct { // supported and expected type. This is part of the DSSE // protocol which is defined here: // - // DSSE envelopes in a bundle MUST have exactly one signture. + // DSSE envelopes in a bundle MUST have exactly one signature. // This is a limitation from the DSSE spec, as it can contain // multiple signatures. There are two primary reasons: - // 1. It simplfies the verification logic and policy + // 1. It simplifies the verification logic and policy // 2. The bundle (currently) can only contain a single // instance of the required verification materials // @@ -478,7 +479,7 @@ func file_sigstore_bundle_proto_rawDescGZIP() []byte { } var file_sigstore_bundle_proto_msgTypes = make([]protoimpl.MessageInfo, 3) -var file_sigstore_bundle_proto_goTypes = []interface{}{ +var file_sigstore_bundle_proto_goTypes = []any{ (*TimestampVerificationData)(nil), // 0: dev.sigstore.bundle.v1.TimestampVerificationData (*VerificationMaterial)(nil), // 1: dev.sigstore.bundle.v1.VerificationMaterial (*Bundle)(nil), // 2: dev.sigstore.bundle.v1.Bundle @@ -512,50 +513,12 @@ func file_sigstore_bundle_proto_init() { if File_sigstore_bundle_proto != nil { return } - if !protoimpl.UnsafeEnabled { - file_sigstore_bundle_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*TimestampVerificationData); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_bundle_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*VerificationMaterial); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_bundle_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Bundle); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - file_sigstore_bundle_proto_msgTypes[1].OneofWrappers = []interface{}{ + file_sigstore_bundle_proto_msgTypes[1].OneofWrappers = []any{ (*VerificationMaterial_PublicKey)(nil), (*VerificationMaterial_X509CertificateChain)(nil), (*VerificationMaterial_Certificate)(nil), } - file_sigstore_bundle_proto_msgTypes[2].OneofWrappers = []interface{}{ + file_sigstore_bundle_proto_msgTypes[2].OneofWrappers = []any{ (*Bundle_MessageSignature)(nil), (*Bundle_DsseEnvelope)(nil), } diff --git a/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/common/v1/sigstore_common.pb.go b/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/common/v1/sigstore_common.pb.go index 0982c674c7..2c5c99efde 100644 --- a/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/common/v1/sigstore_common.pb.go +++ b/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/common/v1/sigstore_common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.6 +// protoc-gen-go v1.36.3 +// protoc v5.29.3 // source: sigstore_common.proto package v1 @@ -123,13 +123,13 @@ const ( PublicKeyDetails_PUBLIC_KEY_DETAILS_UNSPECIFIED PublicKeyDetails = 0 // RSA // - // Deprecated: Do not use. + // Deprecated: Marked as deprecated in sigstore_common.proto. PublicKeyDetails_PKCS1_RSA_PKCS1V5 PublicKeyDetails = 1 // See RFC8017 - // Deprecated: Do not use. + // Deprecated: Marked as deprecated in sigstore_common.proto. PublicKeyDetails_PKCS1_RSA_PSS PublicKeyDetails = 2 // See RFC8017 - // Deprecated: Do not use. + // Deprecated: Marked as deprecated in sigstore_common.proto. PublicKeyDetails_PKIX_RSA_PKCS1V5 PublicKeyDetails = 3 - // Deprecated: Do not use. + // Deprecated: Marked as deprecated in sigstore_common.proto. PublicKeyDetails_PKIX_RSA_PSS PublicKeyDetails = 4 // RSA public key in PKIX format, PKCS#1v1.5 signature PublicKeyDetails_PKIX_RSA_PKCS1V15_2048_SHA256 PublicKeyDetails = 9 @@ -141,7 +141,7 @@ const ( PublicKeyDetails_PKIX_RSA_PSS_4096_SHA256 PublicKeyDetails = 18 // ECDSA // - // Deprecated: Do not use. + // Deprecated: Marked as deprecated in sigstore_common.proto. PublicKeyDetails_PKIX_ECDSA_P256_HMAC_SHA_256 PublicKeyDetails = 6 // See RFC6979 PublicKeyDetails_PKIX_ECDSA_P256_SHA_256 PublicKeyDetails = 5 // See NIST FIPS 186-4 PublicKeyDetails_PKIX_ECDSA_P384_SHA_384 PublicKeyDetails = 12 @@ -297,23 +297,20 @@ func (SubjectAlternativeNameType) EnumDescriptor() ([]byte, []int) { // HashOutput captures a digest of a 'message' (generic octet sequence) // and the corresponding hash algorithm used. type HashOutput struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Algorithm HashAlgorithm `protobuf:"varint,1,opt,name=algorithm,proto3,enum=dev.sigstore.common.v1.HashAlgorithm" json:"algorithm,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + Algorithm HashAlgorithm `protobuf:"varint,1,opt,name=algorithm,proto3,enum=dev.sigstore.common.v1.HashAlgorithm" json:"algorithm,omitempty"` // This is the raw octets of the message digest as computed by // the hash algorithm. - Digest []byte `protobuf:"bytes,2,opt,name=digest,proto3" json:"digest,omitempty"` + Digest []byte `protobuf:"bytes,2,opt,name=digest,proto3" json:"digest,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *HashOutput) Reset() { *x = HashOutput{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_common_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_common_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *HashOutput) String() string { @@ -324,7 +321,7 @@ func (*HashOutput) ProtoMessage() {} func (x *HashOutput) ProtoReflect() protoreflect.Message { mi := &file_sigstore_common_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -355,10 +352,7 @@ func (x *HashOutput) GetDigest() []byte { // MessageSignature stores the computed signature over a message. type MessageSignature struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // Message digest can be used to identify the artifact. // Clients MUST NOT attempt to use this digest to verify the associated // signature; it is intended solely for identification. @@ -371,16 +365,16 @@ type MessageSignature struct { // algorithm. // When using a key pair, the algorithm MUST be part of the public // key, which MUST be communicated out-of-band. - Signature []byte `protobuf:"bytes,2,opt,name=signature,proto3" json:"signature,omitempty"` + Signature []byte `protobuf:"bytes,2,opt,name=signature,proto3" json:"signature,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *MessageSignature) Reset() { *x = MessageSignature{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_common_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_common_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *MessageSignature) String() string { @@ -391,7 +385,7 @@ func (*MessageSignature) ProtoMessage() {} func (x *MessageSignature) ProtoReflect() protoreflect.Message { mi := &file_sigstore_common_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -422,21 +416,18 @@ func (x *MessageSignature) GetSignature() []byte { // LogId captures the identity of a transparency log. type LogId struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The unique identity of the log, represented by its public key. - KeyId []byte `protobuf:"bytes,1,opt,name=key_id,json=keyId,proto3" json:"key_id,omitempty"` + KeyId []byte `protobuf:"bytes,1,opt,name=key_id,json=keyId,proto3" json:"key_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *LogId) Reset() { *x = LogId{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_common_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_common_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *LogId) String() string { @@ -447,7 +438,7 @@ func (*LogId) ProtoMessage() {} func (x *LogId) ProtoReflect() protoreflect.Message { mi := &file_sigstore_common_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -471,22 +462,19 @@ func (x *LogId) GetKeyId() []byte { // This message holds a RFC 3161 timestamp. type RFC3161SignedTimestamp struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // Signed timestamp is the DER encoded TimeStampResponse. // See https://www.rfc-editor.org/rfc/rfc3161.html#section-2.4.2 SignedTimestamp []byte `protobuf:"bytes,1,opt,name=signed_timestamp,json=signedTimestamp,proto3" json:"signed_timestamp,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *RFC3161SignedTimestamp) Reset() { *x = RFC3161SignedTimestamp{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_common_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_common_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *RFC3161SignedTimestamp) String() string { @@ -497,7 +485,7 @@ func (*RFC3161SignedTimestamp) ProtoMessage() {} func (x *RFC3161SignedTimestamp) ProtoReflect() protoreflect.Message { mi := &file_sigstore_common_proto_msgTypes[3] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -520,26 +508,23 @@ func (x *RFC3161SignedTimestamp) GetSignedTimestamp() []byte { } type PublicKey struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // DER-encoded public key, encoding method is specified by the // key_details attribute. RawBytes []byte `protobuf:"bytes,1,opt,name=raw_bytes,json=rawBytes,proto3,oneof" json:"raw_bytes,omitempty"` // Key encoding and signature algorithm to use for this key. KeyDetails PublicKeyDetails `protobuf:"varint,2,opt,name=key_details,json=keyDetails,proto3,enum=dev.sigstore.common.v1.PublicKeyDetails" json:"key_details,omitempty"` // Optional validity period for this key, *inclusive* of the endpoints. - ValidFor *TimeRange `protobuf:"bytes,3,opt,name=valid_for,json=validFor,proto3,oneof" json:"valid_for,omitempty"` + ValidFor *TimeRange `protobuf:"bytes,3,opt,name=valid_for,json=validFor,proto3,oneof" json:"valid_for,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *PublicKey) Reset() { *x = PublicKey{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_common_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_common_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *PublicKey) String() string { @@ -550,7 +535,7 @@ func (*PublicKey) ProtoMessage() {} func (x *PublicKey) ProtoReflect() protoreflect.Message { mi := &file_sigstore_common_proto_msgTypes[4] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -589,10 +574,7 @@ func (x *PublicKey) GetValidFor() *TimeRange { // PublicKeyIdentifier can be used to identify an (out of band) delivered // key, to verify a signature. type PublicKeyIdentifier struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // Optional unauthenticated hint on which key to use. // The format of the hint must be agreed upon out of band by the // signer and the verifiers, and so is not subject to this @@ -602,16 +584,16 @@ type PublicKeyIdentifier struct { // Implementors are RECOMMENDED to derive the value from the public // key as described in RFC 6962. // See: - Hint string `protobuf:"bytes,1,opt,name=hint,proto3" json:"hint,omitempty"` + Hint string `protobuf:"bytes,1,opt,name=hint,proto3" json:"hint,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *PublicKeyIdentifier) Reset() { *x = PublicKeyIdentifier{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_common_proto_msgTypes[5] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_common_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *PublicKeyIdentifier) String() string { @@ -622,7 +604,7 @@ func (*PublicKeyIdentifier) ProtoMessage() {} func (x *PublicKeyIdentifier) ProtoReflect() protoreflect.Message { mi := &file_sigstore_common_proto_msgTypes[5] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -646,20 +628,17 @@ func (x *PublicKeyIdentifier) GetHint() string { // An ASN.1 OBJECT IDENTIFIER type ObjectIdentifier struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache + state protoimpl.MessageState `protogen:"open.v1"` + Id []int32 `protobuf:"varint,1,rep,packed,name=id,proto3" json:"id,omitempty"` unknownFields protoimpl.UnknownFields - - Id []int32 `protobuf:"varint,1,rep,packed,name=id,proto3" json:"id,omitempty"` + sizeCache protoimpl.SizeCache } func (x *ObjectIdentifier) Reset() { *x = ObjectIdentifier{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_common_proto_msgTypes[6] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_common_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ObjectIdentifier) String() string { @@ -670,7 +649,7 @@ func (*ObjectIdentifier) ProtoMessage() {} func (x *ObjectIdentifier) ProtoReflect() protoreflect.Message { mi := &file_sigstore_common_proto_msgTypes[6] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -694,21 +673,18 @@ func (x *ObjectIdentifier) GetId() []int32 { // An OID and the corresponding (byte) value. type ObjectIdentifierValuePair struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache + state protoimpl.MessageState `protogen:"open.v1"` + Oid *ObjectIdentifier `protobuf:"bytes,1,opt,name=oid,proto3" json:"oid,omitempty"` + Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` unknownFields protoimpl.UnknownFields - - Oid *ObjectIdentifier `protobuf:"bytes,1,opt,name=oid,proto3" json:"oid,omitempty"` - Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` + sizeCache protoimpl.SizeCache } func (x *ObjectIdentifierValuePair) Reset() { *x = ObjectIdentifierValuePair{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_common_proto_msgTypes[7] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_common_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ObjectIdentifierValuePair) String() string { @@ -719,7 +695,7 @@ func (*ObjectIdentifierValuePair) ProtoMessage() {} func (x *ObjectIdentifierValuePair) ProtoReflect() protoreflect.Message { mi := &file_sigstore_common_proto_msgTypes[7] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -749,21 +725,18 @@ func (x *ObjectIdentifierValuePair) GetValue() []byte { } type DistinguishedName struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache + state protoimpl.MessageState `protogen:"open.v1"` + Organization string `protobuf:"bytes,1,opt,name=organization,proto3" json:"organization,omitempty"` + CommonName string `protobuf:"bytes,2,opt,name=common_name,json=commonName,proto3" json:"common_name,omitempty"` unknownFields protoimpl.UnknownFields - - Organization string `protobuf:"bytes,1,opt,name=organization,proto3" json:"organization,omitempty"` - CommonName string `protobuf:"bytes,2,opt,name=common_name,json=commonName,proto3" json:"common_name,omitempty"` + sizeCache protoimpl.SizeCache } func (x *DistinguishedName) Reset() { *x = DistinguishedName{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_common_proto_msgTypes[8] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_common_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *DistinguishedName) String() string { @@ -774,7 +747,7 @@ func (*DistinguishedName) ProtoMessage() {} func (x *DistinguishedName) ProtoReflect() protoreflect.Message { mi := &file_sigstore_common_proto_msgTypes[8] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -804,21 +777,18 @@ func (x *DistinguishedName) GetCommonName() string { } type X509Certificate struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // DER-encoded X.509 certificate. - RawBytes []byte `protobuf:"bytes,1,opt,name=raw_bytes,json=rawBytes,proto3" json:"raw_bytes,omitempty"` + RawBytes []byte `protobuf:"bytes,1,opt,name=raw_bytes,json=rawBytes,proto3" json:"raw_bytes,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *X509Certificate) Reset() { *x = X509Certificate{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_common_proto_msgTypes[9] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_common_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *X509Certificate) String() string { @@ -829,7 +799,7 @@ func (*X509Certificate) ProtoMessage() {} func (x *X509Certificate) ProtoReflect() protoreflect.Message { mi := &file_sigstore_common_proto_msgTypes[9] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -852,25 +822,22 @@ func (x *X509Certificate) GetRawBytes() []byte { } type SubjectAlternativeName struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Type SubjectAlternativeNameType `protobuf:"varint,1,opt,name=type,proto3,enum=dev.sigstore.common.v1.SubjectAlternativeNameType" json:"type,omitempty"` - // Types that are assignable to Identity: + state protoimpl.MessageState `protogen:"open.v1"` + Type SubjectAlternativeNameType `protobuf:"varint,1,opt,name=type,proto3,enum=dev.sigstore.common.v1.SubjectAlternativeNameType" json:"type,omitempty"` + // Types that are valid to be assigned to Identity: // // *SubjectAlternativeName_Regexp // *SubjectAlternativeName_Value - Identity isSubjectAlternativeName_Identity `protobuf_oneof:"identity"` + Identity isSubjectAlternativeName_Identity `protobuf_oneof:"identity"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *SubjectAlternativeName) Reset() { *x = SubjectAlternativeName{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_common_proto_msgTypes[10] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_common_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *SubjectAlternativeName) String() string { @@ -881,7 +848,7 @@ func (*SubjectAlternativeName) ProtoMessage() {} func (x *SubjectAlternativeName) ProtoReflect() protoreflect.Message { mi := &file_sigstore_common_proto_msgTypes[10] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -903,23 +870,27 @@ func (x *SubjectAlternativeName) GetType() SubjectAlternativeNameType { return SubjectAlternativeNameType_SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED } -func (m *SubjectAlternativeName) GetIdentity() isSubjectAlternativeName_Identity { - if m != nil { - return m.Identity +func (x *SubjectAlternativeName) GetIdentity() isSubjectAlternativeName_Identity { + if x != nil { + return x.Identity } return nil } func (x *SubjectAlternativeName) GetRegexp() string { - if x, ok := x.GetIdentity().(*SubjectAlternativeName_Regexp); ok { - return x.Regexp + if x != nil { + if x, ok := x.Identity.(*SubjectAlternativeName_Regexp); ok { + return x.Regexp + } } return "" } func (x *SubjectAlternativeName) GetValue() string { - if x, ok := x.GetIdentity().(*SubjectAlternativeName_Value); ok { - return x.Value + if x != nil { + if x, ok := x.Identity.(*SubjectAlternativeName_Value); ok { + return x.Value + } } return "" } @@ -949,25 +920,22 @@ func (*SubjectAlternativeName_Value) isSubjectAlternativeName_Identity() {} // certificate within a TUF root of trust or multiple untrusted certificates for // the purpose of chain building. type X509CertificateChain struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // One or more DER-encoded certificates. // // In some contexts (such as `VerificationMaterial.x509_certificate_chain`), this sequence // has an imposed order. Unless explicitly specified, there is otherwise no // guaranteed order. - Certificates []*X509Certificate `protobuf:"bytes,1,rep,name=certificates,proto3" json:"certificates,omitempty"` + Certificates []*X509Certificate `protobuf:"bytes,1,rep,name=certificates,proto3" json:"certificates,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *X509CertificateChain) Reset() { *x = X509CertificateChain{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_common_proto_msgTypes[11] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_common_proto_msgTypes[11] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *X509CertificateChain) String() string { @@ -978,7 +946,7 @@ func (*X509CertificateChain) ProtoMessage() {} func (x *X509CertificateChain) ProtoReflect() protoreflect.Message { mi := &file_sigstore_common_proto_msgTypes[11] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -1005,21 +973,18 @@ func (x *X509CertificateChain) GetCertificates() []*X509Certificate { // End is optional to be able to capture a period that has started but // has no known end. type TimeRange struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache + state protoimpl.MessageState `protogen:"open.v1"` + Start *timestamppb.Timestamp `protobuf:"bytes,1,opt,name=start,proto3" json:"start,omitempty"` + End *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=end,proto3,oneof" json:"end,omitempty"` unknownFields protoimpl.UnknownFields - - Start *timestamppb.Timestamp `protobuf:"bytes,1,opt,name=start,proto3" json:"start,omitempty"` - End *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=end,proto3,oneof" json:"end,omitempty"` + sizeCache protoimpl.SizeCache } func (x *TimeRange) Reset() { *x = TimeRange{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_common_proto_msgTypes[12] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_common_proto_msgTypes[12] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *TimeRange) String() string { @@ -1030,7 +995,7 @@ func (*TimeRange) ProtoMessage() {} func (x *TimeRange) ProtoReflect() protoreflect.Message { mi := &file_sigstore_common_proto_msgTypes[12] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -1224,7 +1189,7 @@ func file_sigstore_common_proto_rawDescGZIP() []byte { var file_sigstore_common_proto_enumTypes = make([]protoimpl.EnumInfo, 3) var file_sigstore_common_proto_msgTypes = make([]protoimpl.MessageInfo, 13) -var file_sigstore_common_proto_goTypes = []interface{}{ +var file_sigstore_common_proto_goTypes = []any{ (HashAlgorithm)(0), // 0: dev.sigstore.common.v1.HashAlgorithm (PublicKeyDetails)(0), // 1: dev.sigstore.common.v1.PublicKeyDetails (SubjectAlternativeNameType)(0), // 2: dev.sigstore.common.v1.SubjectAlternativeNameType @@ -1265,170 +1230,12 @@ func file_sigstore_common_proto_init() { if File_sigstore_common_proto != nil { return } - if !protoimpl.UnsafeEnabled { - file_sigstore_common_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*HashOutput); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_common_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*MessageSignature); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_common_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*LogId); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_common_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*RFC3161SignedTimestamp); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_common_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*PublicKey); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_common_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*PublicKeyIdentifier); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_common_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ObjectIdentifier); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_common_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ObjectIdentifierValuePair); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_common_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*DistinguishedName); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_common_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*X509Certificate); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_common_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SubjectAlternativeName); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_common_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*X509CertificateChain); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_common_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*TimeRange); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - file_sigstore_common_proto_msgTypes[4].OneofWrappers = []interface{}{} - file_sigstore_common_proto_msgTypes[10].OneofWrappers = []interface{}{ + file_sigstore_common_proto_msgTypes[4].OneofWrappers = []any{} + file_sigstore_common_proto_msgTypes[10].OneofWrappers = []any{ (*SubjectAlternativeName_Regexp)(nil), (*SubjectAlternativeName_Value)(nil), } - file_sigstore_common_proto_msgTypes[12].OneofWrappers = []interface{}{} + file_sigstore_common_proto_msgTypes[12].OneofWrappers = []any{} type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ diff --git a/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/dsse/envelope.pb.go b/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/dsse/envelope.pb.go index 01008e9980..16e581ebe0 100644 --- a/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/dsse/envelope.pb.go +++ b/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/dsse/envelope.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.6 +// protoc-gen-go v1.36.3 +// protoc v5.29.3 // source: envelope.proto package dsse @@ -36,10 +36,7 @@ const ( // An authenticated message of arbitrary type. type Envelope struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // Message to be signed. (In JSON, this is encoded as base64.) // REQUIRED. Payload []byte `protobuf:"bytes,1,opt,name=payload,proto3" json:"payload,omitempty"` @@ -57,16 +54,16 @@ type Envelope struct { // "DSSEv1" = ASCII [0x44, 0x53, 0x53, 0x45, 0x76, 0x31] // LEN(s) = ASCII decimal encoding of the byte length of s, with no leading zeros // REQUIRED (length >= 1). - Signatures []*Signature `protobuf:"bytes,3,rep,name=signatures,proto3" json:"signatures,omitempty"` + Signatures []*Signature `protobuf:"bytes,3,rep,name=signatures,proto3" json:"signatures,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Envelope) Reset() { *x = Envelope{} - if protoimpl.UnsafeEnabled { - mi := &file_envelope_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_envelope_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *Envelope) String() string { @@ -77,7 +74,7 @@ func (*Envelope) ProtoMessage() {} func (x *Envelope) ProtoReflect() protoreflect.Message { mi := &file_envelope_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -114,25 +111,22 @@ func (x *Envelope) GetSignatures() []*Signature { } type Signature struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // Signature itself. (In JSON, this is encoded as base64.) // REQUIRED. Sig []byte `protobuf:"bytes,1,opt,name=sig,proto3" json:"sig,omitempty"` // *Unauthenticated* hint identifying which public key was used. // OPTIONAL. - Keyid string `protobuf:"bytes,2,opt,name=keyid,proto3" json:"keyid,omitempty"` + Keyid string `protobuf:"bytes,2,opt,name=keyid,proto3" json:"keyid,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Signature) Reset() { *x = Signature{} - if protoimpl.UnsafeEnabled { - mi := &file_envelope_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_envelope_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *Signature) String() string { @@ -143,7 +137,7 @@ func (*Signature) ProtoMessage() {} func (x *Signature) ProtoReflect() protoreflect.Message { mi := &file_envelope_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -208,7 +202,7 @@ func file_envelope_proto_rawDescGZIP() []byte { } var file_envelope_proto_msgTypes = make([]protoimpl.MessageInfo, 2) -var file_envelope_proto_goTypes = []interface{}{ +var file_envelope_proto_goTypes = []any{ (*Envelope)(nil), // 0: io.intoto.Envelope (*Signature)(nil), // 1: io.intoto.Signature } @@ -226,32 +220,6 @@ func file_envelope_proto_init() { if File_envelope_proto != nil { return } - if !protoimpl.UnsafeEnabled { - file_envelope_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Envelope); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_envelope_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Signature); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ diff --git a/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/rekor/v1/sigstore_rekor.pb.go b/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/rekor/v1/sigstore_rekor.pb.go index 17deda7c0e..5874bc29eb 100644 --- a/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/rekor/v1/sigstore_rekor.pb.go +++ b/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/rekor/v1/sigstore_rekor.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.6 +// protoc-gen-go v1.36.3 +// protoc v5.29.3 // source: sigstore_rekor.proto package v1 @@ -38,24 +38,21 @@ const ( // KindVersion contains the entry's kind and api version. type KindVersion struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // Kind is the type of entry being stored in the log. // See here for a list: https://github.com/sigstore/rekor/tree/main/pkg/types Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"` // The specific api version of the type. - Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"` + Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *KindVersion) Reset() { *x = KindVersion{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_rekor_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_rekor_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *KindVersion) String() string { @@ -66,7 +63,7 @@ func (*KindVersion) ProtoMessage() {} func (x *KindVersion) ProtoReflect() protoreflect.Message { mi := &file_sigstore_rekor_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -106,20 +103,17 @@ func (x *KindVersion) GetVersion() string { // and https://github.com/C2SP/C2SP/blob/main/tlog-checkpoint.md. // An example implementation can be found in https://github.com/sigstore/rekor/blob/main/pkg/util/signed_note.go type Checkpoint struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache + state protoimpl.MessageState `protogen:"open.v1"` + Envelope string `protobuf:"bytes,1,opt,name=envelope,proto3" json:"envelope,omitempty"` unknownFields protoimpl.UnknownFields - - Envelope string `protobuf:"bytes,1,opt,name=envelope,proto3" json:"envelope,omitempty"` + sizeCache protoimpl.SizeCache } func (x *Checkpoint) Reset() { *x = Checkpoint{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_rekor_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_rekor_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *Checkpoint) String() string { @@ -130,7 +124,7 @@ func (*Checkpoint) ProtoMessage() {} func (x *Checkpoint) ProtoReflect() protoreflect.Message { mi := &file_sigstore_rekor_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -155,10 +149,7 @@ func (x *Checkpoint) GetEnvelope() string { // InclusionProof is the proof returned from the transparency log. Can // be used for offline or online verification against the log. type InclusionProof struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The index of the entry in the tree it was written to. LogIndex int64 `protobuf:"varint,1,opt,name=log_index,json=logIndex,proto3" json:"log_index,omitempty"` // The hash digest stored at the root of the merkle tree at the time @@ -174,16 +165,16 @@ type InclusionProof struct { Hashes [][]byte `protobuf:"bytes,4,rep,name=hashes,proto3" json:"hashes,omitempty"` // Signature of the tree head, as of the time of this proof was // generated. See above info on 'Checkpoint' for more details. - Checkpoint *Checkpoint `protobuf:"bytes,5,opt,name=checkpoint,proto3" json:"checkpoint,omitempty"` + Checkpoint *Checkpoint `protobuf:"bytes,5,opt,name=checkpoint,proto3" json:"checkpoint,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *InclusionProof) Reset() { *x = InclusionProof{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_rekor_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_rekor_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *InclusionProof) String() string { @@ -194,7 +185,7 @@ func (*InclusionProof) ProtoMessage() {} func (x *InclusionProof) ProtoReflect() protoreflect.Message { mi := &file_sigstore_rekor_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -255,20 +246,17 @@ func (x *InclusionProof) GetCheckpoint() *Checkpoint { // This is used to verify the integration timestamp's value and that the log // has promised to include the entry. type InclusionPromise struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - SignedEntryTimestamp []byte `protobuf:"bytes,1,opt,name=signed_entry_timestamp,json=signedEntryTimestamp,proto3" json:"signed_entry_timestamp,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + SignedEntryTimestamp []byte `protobuf:"bytes,1,opt,name=signed_entry_timestamp,json=signedEntryTimestamp,proto3" json:"signed_entry_timestamp,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *InclusionPromise) Reset() { *x = InclusionPromise{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_rekor_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_rekor_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *InclusionPromise) String() string { @@ -279,7 +267,7 @@ func (*InclusionPromise) ProtoMessage() {} func (x *InclusionPromise) ProtoReflect() protoreflect.Message { mi := &file_sigstore_rekor_proto_msgTypes[3] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -310,10 +298,7 @@ func (x *InclusionPromise) GetSignedEntryTimestamp() []byte { // the response from Rekor) is similar to a Signed Certificate Timestamp // as described here https://www.rfc-editor.org/rfc/rfc6962.html#section-3.2. type TransparencyLogEntry struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The global index of the entry, used when querying the log by index. LogIndex int64 `protobuf:"varint,1,opt,name=log_index,json=logIndex,proto3" json:"log_index,omitempty"` // The unique identifier of the log. @@ -357,15 +342,15 @@ type TransparencyLogEntry struct { // If not set, clients are responsible for constructing an equivalent // payload from other sources to verify the signature. CanonicalizedBody []byte `protobuf:"bytes,7,opt,name=canonicalized_body,json=canonicalizedBody,proto3" json:"canonicalized_body,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *TransparencyLogEntry) Reset() { *x = TransparencyLogEntry{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_rekor_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_rekor_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *TransparencyLogEntry) String() string { @@ -376,7 +361,7 @@ func (*TransparencyLogEntry) ProtoMessage() {} func (x *TransparencyLogEntry) ProtoReflect() protoreflect.Message { mi := &file_sigstore_rekor_proto_msgTypes[4] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -528,7 +513,7 @@ func file_sigstore_rekor_proto_rawDescGZIP() []byte { } var file_sigstore_rekor_proto_msgTypes = make([]protoimpl.MessageInfo, 5) -var file_sigstore_rekor_proto_goTypes = []interface{}{ +var file_sigstore_rekor_proto_goTypes = []any{ (*KindVersion)(nil), // 0: dev.sigstore.rekor.v1.KindVersion (*Checkpoint)(nil), // 1: dev.sigstore.rekor.v1.Checkpoint (*InclusionProof)(nil), // 2: dev.sigstore.rekor.v1.InclusionProof @@ -554,68 +539,6 @@ func file_sigstore_rekor_proto_init() { if File_sigstore_rekor_proto != nil { return } - if !protoimpl.UnsafeEnabled { - file_sigstore_rekor_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*KindVersion); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_rekor_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Checkpoint); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_rekor_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*InclusionProof); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_rekor_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*InclusionPromise); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_rekor_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*TransparencyLogEntry); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ diff --git a/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/trustroot/v1/sigstore_trustroot.pb.go b/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/trustroot/v1/sigstore_trustroot.pb.go index e86dfed497..8888d385b6 100644 --- a/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/trustroot/v1/sigstore_trustroot.pb.go +++ b/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/trustroot/v1/sigstore_trustroot.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.6 +// protoc-gen-go v1.36.3 +// protoc v5.29.3 // source: sigstore_trustroot.proto package v1 @@ -43,10 +43,7 @@ const ( // The included parameters are the minimal set required to identify a log, // and verify an inclusion proof/promise. type TransparencyLogInstance struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The base URL at which can be used to URLs for the client. BaseUrl string `protobuf:"bytes,1,opt,name=base_url,json=baseUrl,proto3" json:"base_url,omitempty"` // The hash algorithm used for the Merkle Tree. @@ -76,15 +73,15 @@ type TransparencyLogInstance struct { // SHOULD be set for logs generating Ed25519 signatures. // SHOULD be 4 bytes long, as a truncated hash. CheckpointKeyId *v1.LogId `protobuf:"bytes,5,opt,name=checkpoint_key_id,json=checkpointKeyId,proto3" json:"checkpoint_key_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *TransparencyLogInstance) Reset() { *x = TransparencyLogInstance{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_trustroot_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_trustroot_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *TransparencyLogInstance) String() string { @@ -95,7 +92,7 @@ func (*TransparencyLogInstance) ProtoMessage() {} func (x *TransparencyLogInstance) ProtoReflect() protoreflect.Message { mi := &file_sigstore_trustroot_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -148,10 +145,7 @@ func (x *TransparencyLogInstance) GetCheckpointKeyId() *v1.LogId { // CertificateAuthority enlists the information required to identify which // CA to use and perform signature verification. type CertificateAuthority struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The root certificate MUST be self-signed, and so the subject and // issuer are the same. Subject *v1.DistinguishedName `protobuf:"bytes,1,opt,name=subject,proto3" json:"subject,omitempty"` @@ -173,16 +167,16 @@ type CertificateAuthority struct { // // The TimeRange should be considered valid *inclusive* of the // endpoints. - ValidFor *v1.TimeRange `protobuf:"bytes,4,opt,name=valid_for,json=validFor,proto3" json:"valid_for,omitempty"` + ValidFor *v1.TimeRange `protobuf:"bytes,4,opt,name=valid_for,json=validFor,proto3" json:"valid_for,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *CertificateAuthority) Reset() { *x = CertificateAuthority{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_trustroot_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_trustroot_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *CertificateAuthority) String() string { @@ -193,7 +187,7 @@ func (*CertificateAuthority) ProtoMessage() {} func (x *CertificateAuthority) ProtoReflect() protoreflect.Message { mi := &file_sigstore_trustroot_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -267,10 +261,7 @@ func (x *CertificateAuthority) GetValidFor() *v1.TimeRange { // for a suitable instance before creating a per artifact trust root (that // is, a sub-set of the complete trust root) that is used for verification. type TrustedRoot struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // MUST be application/vnd.dev.sigstore.trustedroot.v0.1+json // when encoded as JSON. // Clients MUST be able to process and parse content with the media @@ -292,15 +283,15 @@ type TrustedRoot struct { Ctlogs []*TransparencyLogInstance `protobuf:"bytes,4,rep,name=ctlogs,proto3" json:"ctlogs,omitempty"` // A set of trusted timestamping authorities. TimestampAuthorities []*CertificateAuthority `protobuf:"bytes,5,rep,name=timestamp_authorities,json=timestampAuthorities,proto3" json:"timestamp_authorities,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *TrustedRoot) Reset() { *x = TrustedRoot{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_trustroot_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_trustroot_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *TrustedRoot) String() string { @@ -311,7 +302,7 @@ func (*TrustedRoot) ProtoMessage() {} func (x *TrustedRoot) ProtoReflect() protoreflect.Message { mi := &file_sigstore_trustroot_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -365,10 +356,7 @@ func (x *TrustedRoot) GetTimestampAuthorities() []*CertificateAuthority { // signing. In particular, it primarily contains service URLs that a Sigstore // signer may need to connect to for the online aspects of signing. type SigningConfig struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // MUST be application/vnd.dev.sigstore.signingconfig.v0.1+json MediaType string `protobuf:"bytes,5,opt,name=media_type,json=mediaType,proto3" json:"media_type,omitempty"` // A URL to a Fulcio-compatible CA, capable of receiving @@ -396,16 +384,16 @@ type SigningConfig struct { // Each URL **MUST** be the **full** URL for the TSA, meaning that it // should be suitable for submitting Time Stamp Requests (TSRs) to // via HTTP, per RFC 3161. - TsaUrls []string `protobuf:"bytes,4,rep,name=tsa_urls,json=tsaUrls,proto3" json:"tsa_urls,omitempty"` + TsaUrls []string `protobuf:"bytes,4,rep,name=tsa_urls,json=tsaUrls,proto3" json:"tsa_urls,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *SigningConfig) Reset() { *x = SigningConfig{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_trustroot_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_trustroot_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *SigningConfig) String() string { @@ -416,7 +404,7 @@ func (*SigningConfig) ProtoMessage() {} func (x *SigningConfig) ProtoReflect() protoreflect.Message { mi := &file_sigstore_trustroot_proto_msgTypes[3] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -470,25 +458,22 @@ func (x *SigningConfig) GetTsaUrls() []string { // to perform both signing and verification operations against a particular // instance of Sigstore. type ClientTrustConfig struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // MUST be application/vnd.dev.sigstore.clienttrustconfig.v0.1+json MediaType string `protobuf:"bytes,1,opt,name=media_type,json=mediaType,proto3" json:"media_type,omitempty"` // The root of trust, which MUST be present. TrustedRoot *TrustedRoot `protobuf:"bytes,2,opt,name=trusted_root,json=trustedRoot,proto3" json:"trusted_root,omitempty"` // Configuration for signing clients, which MUST be present. SigningConfig *SigningConfig `protobuf:"bytes,3,opt,name=signing_config,json=signingConfig,proto3" json:"signing_config,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ClientTrustConfig) Reset() { *x = ClientTrustConfig{} - if protoimpl.UnsafeEnabled { - mi := &file_sigstore_trustroot_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_sigstore_trustroot_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ClientTrustConfig) String() string { @@ -499,7 +484,7 @@ func (*ClientTrustConfig) ProtoMessage() {} func (x *ClientTrustConfig) ProtoReflect() protoreflect.Message { mi := &file_sigstore_trustroot_proto_msgTypes[4] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -654,7 +639,7 @@ func file_sigstore_trustroot_proto_rawDescGZIP() []byte { } var file_sigstore_trustroot_proto_msgTypes = make([]protoimpl.MessageInfo, 5) -var file_sigstore_trustroot_proto_goTypes = []interface{}{ +var file_sigstore_trustroot_proto_goTypes = []any{ (*TransparencyLogInstance)(nil), // 0: dev.sigstore.trustroot.v1.TransparencyLogInstance (*CertificateAuthority)(nil), // 1: dev.sigstore.trustroot.v1.CertificateAuthority (*TrustedRoot)(nil), // 2: dev.sigstore.trustroot.v1.TrustedRoot @@ -693,68 +678,6 @@ func file_sigstore_trustroot_proto_init() { if File_sigstore_trustroot_proto != nil { return } - if !protoimpl.UnsafeEnabled { - file_sigstore_trustroot_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*TransparencyLogInstance); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_trustroot_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*CertificateAuthority); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_trustroot_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*TrustedRoot); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_trustroot_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SigningConfig); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_sigstore_trustroot_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ClientTrustConfig); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ diff --git a/vendor/github.com/sigstore/sigstore-go/pkg/bundle/bundle.go b/vendor/github.com/sigstore/sigstore-go/pkg/bundle/bundle.go index 4ce5df86c4..f0c862788f 100644 --- a/vendor/github.com/sigstore/sigstore-go/pkg/bundle/bundle.go +++ b/vendor/github.com/sigstore/sigstore-go/pkg/bundle/bundle.go @@ -35,7 +35,9 @@ import ( var ErrValidation = errors.New("validation error") var ErrUnsupportedMediaType = fmt.Errorf("%w: unsupported media type", ErrValidation) +var ErrEmptyBundle = fmt.Errorf("%w: empty protobuf bundle", ErrValidation) var ErrMissingVerificationMaterial = fmt.Errorf("%w: missing verification material", ErrValidation) +var ErrMissingBundleContent = fmt.Errorf("%w: missing bundle content", ErrValidation) var ErrUnimplemented = errors.New("unimplemented") var ErrInvalidAttestation = fmt.Errorf("%w: invalid attestation", ErrValidation) var ErrMissingEnvelope = fmt.Errorf("%w: missing valid envelope", ErrInvalidAttestation) @@ -172,11 +174,11 @@ func getBundleVersion(mediaType string) (string, error) { func validateBundle(b *protobundle.Bundle) error { if b == nil { - return fmt.Errorf("empty protobuf bundle") + return ErrEmptyBundle } if b.Content == nil { - return fmt.Errorf("missing bundle content") + return ErrMissingBundleContent } switch b.Content.(type) { @@ -185,12 +187,8 @@ func validateBundle(b *protobundle.Bundle) error { return fmt.Errorf("invalid bundle content: bundle content must be either a message signature or dsse envelope") } - if b.VerificationMaterial == nil { - return fmt.Errorf("missing verification material") - } - - if b.VerificationMaterial.Content == nil { - return fmt.Errorf("missing verification material content") + if b.VerificationMaterial == nil || b.VerificationMaterial.Content == nil { + return ErrMissingVerificationMaterial } switch b.VerificationMaterial.Content.(type) { @@ -257,7 +255,7 @@ func (b *Bundle) VerificationContent() (verify.VerificationContent, error) { return nil, ErrValidationError(err) } cert := &Certificate{ - Certificate: parsedCert, + certificate: parsedCert, } return cert, nil case *protobundle.VerificationMaterial_Certificate: @@ -269,7 +267,7 @@ func (b *Bundle) VerificationContent() (verify.VerificationContent, error) { return nil, ErrValidationError(err) } cert := &Certificate{ - Certificate: parsedCert, + certificate: parsedCert, } return cert, nil case *protobundle.VerificationMaterial_PublicKey: diff --git a/vendor/github.com/sigstore/sigstore-go/pkg/bundle/verification_content.go b/vendor/github.com/sigstore/sigstore-go/pkg/bundle/verification_content.go index b775295dea..edb65db330 100644 --- a/vendor/github.com/sigstore/sigstore-go/pkg/bundle/verification_content.go +++ b/vendor/github.com/sigstore/sigstore-go/pkg/bundle/verification_content.go @@ -24,7 +24,11 @@ import ( ) type Certificate struct { - *x509.Certificate + certificate *x509.Certificate +} + +func NewCertificate(cert *x509.Certificate) *Certificate { + return &Certificate{certificate: cert} } type PublicKey struct { @@ -41,19 +45,19 @@ func (c *Certificate) CompareKey(key any, _ root.TrustedMaterial) bool { return false } - return c.Certificate.Equal(x509Key) + return c.certificate.Equal(x509Key) } func (c *Certificate) ValidAtTime(t time.Time, _ root.TrustedMaterial) bool { - return !(c.Certificate.NotAfter.Before(t) || c.Certificate.NotBefore.After(t)) + return !(c.certificate.NotAfter.Before(t) || c.certificate.NotBefore.After(t)) } -func (c *Certificate) GetCertificate() *x509.Certificate { - return c.Certificate +func (c *Certificate) Certificate() *x509.Certificate { + return c.certificate } -func (c *Certificate) HasPublicKey() (verify.PublicKeyProvider, bool) { - return PublicKey{}, false +func (c *Certificate) PublicKey() verify.PublicKeyProvider { + return nil } func (pk *PublicKey) CompareKey(key any, tm root.TrustedMaterial) bool { @@ -79,10 +83,10 @@ func (pk *PublicKey) ValidAtTime(t time.Time, tm root.TrustedMaterial) bool { return verifier.ValidAtTime(t) } -func (pk *PublicKey) GetCertificate() *x509.Certificate { +func (pk *PublicKey) Certificate() *x509.Certificate { return nil } -func (pk *PublicKey) HasPublicKey() (verify.PublicKeyProvider, bool) { - return *pk, true +func (pk *PublicKey) PublicKey() verify.PublicKeyProvider { + return pk } diff --git a/vendor/github.com/sigstore/sigstore-go/pkg/root/certificate_authority.go b/vendor/github.com/sigstore/sigstore-go/pkg/root/certificate_authority.go new file mode 100644 index 0000000000..5e1cb67cca --- /dev/null +++ b/vendor/github.com/sigstore/sigstore-go/pkg/root/certificate_authority.go @@ -0,0 +1,66 @@ +// Copyright 2024 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package root + +import ( + "crypto/x509" + "errors" + "time" +) + +type CertificateAuthority interface { + Verify(cert *x509.Certificate, observerTimestamp time.Time) ([][]*x509.Certificate, error) +} + +type FulcioCertificateAuthority struct { + Root *x509.Certificate + Intermediates []*x509.Certificate + ValidityPeriodStart time.Time + ValidityPeriodEnd time.Time + URI string +} + +var _ CertificateAuthority = &FulcioCertificateAuthority{} + +func (ca *FulcioCertificateAuthority) Verify(cert *x509.Certificate, observerTimestamp time.Time) ([][]*x509.Certificate, error) { + if !ca.ValidityPeriodStart.IsZero() && observerTimestamp.Before(ca.ValidityPeriodStart) { + return nil, errors.New("certificate is not valid yet") + } + if !ca.ValidityPeriodEnd.IsZero() && observerTimestamp.After(ca.ValidityPeriodEnd) { + return nil, errors.New("certificate is no longer valid") + } + + rootCertPool := x509.NewCertPool() + rootCertPool.AddCert(ca.Root) + intermediateCertPool := x509.NewCertPool() + for _, cert := range ca.Intermediates { + intermediateCertPool.AddCert(cert) + } + + // From spec: + // > ## Certificate + // > For a signature with a given certificate to be considered valid, it must have a timestamp while every certificate in the chain up to the root is valid (the so-called “hybrid model” of certificate verification per Braun et al. (2013)). + + opts := x509.VerifyOptions{ + CurrentTime: observerTimestamp, + Roots: rootCertPool, + Intermediates: intermediateCertPool, + KeyUsages: []x509.ExtKeyUsage{ + x509.ExtKeyUsageCodeSigning, + }, + } + + return cert.Verify(opts) +} diff --git a/vendor/github.com/sigstore/sigstore-go/pkg/root/signing_config.go b/vendor/github.com/sigstore/sigstore-go/pkg/root/signing_config.go new file mode 100644 index 0000000000..f9a9295377 --- /dev/null +++ b/vendor/github.com/sigstore/sigstore-go/pkg/root/signing_config.go @@ -0,0 +1,165 @@ +// Copyright 2024 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package root + +import ( + "fmt" + "os" + + prototrustroot "github.com/sigstore/protobuf-specs/gen/pb-go/trustroot/v1" + "github.com/sigstore/sigstore-go/pkg/tuf" + "google.golang.org/protobuf/encoding/protojson" +) + +const SigningConfigMediaType01 = "application/vnd.dev.sigstore.signingconfig.v0.1+json" + +type SigningConfig struct { + signingConfig *prototrustroot.SigningConfig +} + +func (sc *SigningConfig) FulcioCertificateAuthorityURL() string { + return sc.signingConfig.GetCaUrl() +} + +func (sc *SigningConfig) OIDCProviderURL() string { + return sc.signingConfig.GetOidcUrl() +} + +func (sc *SigningConfig) RekorLogURLs() []string { + return sc.signingConfig.GetTlogUrls() +} + +func (sc *SigningConfig) TimestampAuthorityURLs() []string { + return sc.signingConfig.GetTsaUrls() +} + +func (sc *SigningConfig) WithFulcioCertificateAuthorityURL(fulcioURL string) *SigningConfig { + sc.signingConfig.CaUrl = fulcioURL + return sc +} + +func (sc *SigningConfig) WithOIDCProviderURL(oidcURL string) *SigningConfig { + sc.signingConfig.OidcUrl = oidcURL + return sc +} + +func (sc *SigningConfig) WithRekorLogURLs(logURLs []string) *SigningConfig { + sc.signingConfig.TlogUrls = logURLs + return sc +} + +func (sc *SigningConfig) AddRekorLogURLs(logURLs ...string) *SigningConfig { + sc.signingConfig.TlogUrls = append(sc.signingConfig.TlogUrls, logURLs...) + return sc +} + +func (sc *SigningConfig) WithTimestampAuthorityURLs(tsaURLs []string) *SigningConfig { + sc.signingConfig.TsaUrls = tsaURLs + return sc +} + +func (sc *SigningConfig) AddTimestampAuthorityURLs(tsaURLs ...string) *SigningConfig { + sc.signingConfig.TsaUrls = append(sc.signingConfig.TsaUrls, tsaURLs...) + return sc +} + +func (sc SigningConfig) String() string { + return fmt.Sprintf("{CA: %v, OIDC: %v, RekorLogs: %v, TSAs: %v, MediaType: %s}", + sc.FulcioCertificateAuthorityURL(), sc.OIDCProviderURL(), sc.RekorLogURLs(), sc.TimestampAuthorityURLs(), SigningConfigMediaType01) +} + +// NewSigningConfig initializes a SigningConfig object from a mediaType string, Fulcio certificate +// authority URL, OIDC provider URL, list of Rekor transpraency log URLs, and a list of +// timestamp authorities. +func NewSigningConfig(mediaType string, + fulcioCertificateAuthority string, + oidcProvider string, + rekorLogs []string, + timestampAuthorities []string) (*SigningConfig, error) { + if mediaType != SigningConfigMediaType01 { + return nil, fmt.Errorf("unsupported SigningConfig media type, must be: %s", SigningConfigMediaType01) + } + sc := &SigningConfig{ + signingConfig: &prototrustroot.SigningConfig{ + MediaType: mediaType, + CaUrl: fulcioCertificateAuthority, + OidcUrl: oidcProvider, + TlogUrls: rekorLogs, + TsaUrls: timestampAuthorities, + }, + } + return sc, nil +} + +// NewSigningConfigFromProtobuf returns a Sigstore signing configuration. +func NewSigningConfigFromProtobuf(sc *prototrustroot.SigningConfig) (*SigningConfig, error) { + if sc.GetMediaType() != SigningConfigMediaType01 { + return nil, fmt.Errorf("unsupported SigningConfig media type: %s", sc.GetMediaType()) + } + return &SigningConfig{signingConfig: sc}, nil +} + +// NewSigningConfigFromPath returns a Sigstore signing configuration from a file. +func NewSigningConfigFromPath(path string) (*SigningConfig, error) { + scJSON, err := os.ReadFile(path) + if err != nil { + return nil, err + } + + return NewSigningConfigFromJSON(scJSON) +} + +// NewSigningConfigFromJSON returns a Sigstore signing configuration from JSON. +func NewSigningConfigFromJSON(rootJSON []byte) (*SigningConfig, error) { + pbSC, err := NewSigningConfigProtobuf(rootJSON) + if err != nil { + return nil, err + } + + return NewSigningConfigFromProtobuf(pbSC) +} + +// NewSigningConfigProtobuf returns a Sigstore signing configuration as a protobuf. +func NewSigningConfigProtobuf(scJSON []byte) (*prototrustroot.SigningConfig, error) { + pbSC := &prototrustroot.SigningConfig{} + err := protojson.Unmarshal(scJSON, pbSC) + if err != nil { + return nil, err + } + return pbSC, nil +} + +// FetchSigningConfig fetches the public-good Sigstore signing configuration from TUF. +func FetchSigningConfig() (*SigningConfig, error) { + return FetchSigningConfigWithOptions(tuf.DefaultOptions()) +} + +// FetchSigningConfig fetches the public-good Sigstore signing configuration with the given options from TUF. +func FetchSigningConfigWithOptions(opts *tuf.Options) (*SigningConfig, error) { + client, err := tuf.New(opts) + if err != nil { + return nil, err + } + return GetSigningConfig(client) +} + +// FetchSigningConfig fetches the public-good Sigstore signing configuration target from TUF. +func GetSigningConfig(c *tuf.Client) (*SigningConfig, error) { + jsonBytes, err := c.GetTarget("signing_config.json") + if err != nil { + return nil, err + } + return NewSigningConfigFromJSON(jsonBytes) +} diff --git a/vendor/github.com/sigstore/sigstore-go/pkg/root/timestamping_authority.go b/vendor/github.com/sigstore/sigstore-go/pkg/root/timestamping_authority.go new file mode 100644 index 0000000000..07545bd452 --- /dev/null +++ b/vendor/github.com/sigstore/sigstore-go/pkg/root/timestamping_authority.go @@ -0,0 +1,68 @@ +// Copyright 2024 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package root + +import ( + "bytes" + "crypto/x509" + "errors" + "time" + + tsaverification "github.com/sigstore/timestamp-authority/pkg/verification" +) + +type Timestamp struct { + Time time.Time + URI string +} + +type TimestampingAuthority interface { + Verify(signedTimestamp []byte, signatureBytes []byte) (*Timestamp, error) +} + +type SigstoreTimestampingAuthority struct { + Root *x509.Certificate + Intermediates []*x509.Certificate + Leaf *x509.Certificate + ValidityPeriodStart time.Time + ValidityPeriodEnd time.Time + URI string +} + +var _ TimestampingAuthority = &SigstoreTimestampingAuthority{} + +func (tsa *SigstoreTimestampingAuthority) Verify(signedTimestamp []byte, signatureBytes []byte) (*Timestamp, error) { + trustedRootVerificationOptions := tsaverification.VerifyOpts{ + Roots: []*x509.Certificate{tsa.Root}, + Intermediates: tsa.Intermediates, + TSACertificate: tsa.Leaf, + } + + // Ensure timestamp responses are from trusted sources + timestamp, err := tsaverification.VerifyTimestampResponse(signedTimestamp, bytes.NewReader(signatureBytes), trustedRootVerificationOptions) + if err != nil { + return nil, err + } + + if !tsa.ValidityPeriodStart.IsZero() && timestamp.Time.Before(tsa.ValidityPeriodStart) { + return nil, errors.New("timestamp is before the validity period start") + } + if !tsa.ValidityPeriodEnd.IsZero() && timestamp.Time.After(tsa.ValidityPeriodEnd) { + return nil, errors.New("timestamp is after the validity period end") + } + + // All above verification successful, so return nil + return &Timestamp{Time: timestamp.Time, URI: tsa.URI}, nil +} diff --git a/vendor/github.com/sigstore/sigstore-go/pkg/root/trusted_material.go b/vendor/github.com/sigstore/sigstore-go/pkg/root/trusted_material.go index 4e47f0ab7b..d1ec4d4618 100644 --- a/vendor/github.com/sigstore/sigstore-go/pkg/root/trusted_material.go +++ b/vendor/github.com/sigstore/sigstore-go/pkg/root/trusted_material.go @@ -22,7 +22,7 @@ import ( ) type TrustedMaterial interface { - TimestampingAuthorities() []CertificateAuthority + TimestampingAuthorities() []TimestampingAuthority FulcioCertificateAuthorities() []CertificateAuthority RekorLogs() map[string]*TransparencyLog CTLogs() map[string]*TransparencyLog @@ -31,8 +31,8 @@ type TrustedMaterial interface { type BaseTrustedMaterial struct{} -func (b *BaseTrustedMaterial) TimestampingAuthorities() []CertificateAuthority { - return []CertificateAuthority{} +func (b *BaseTrustedMaterial) TimestampingAuthorities() []TimestampingAuthority { + return []TimestampingAuthority{} } func (b *BaseTrustedMaterial) FulcioCertificateAuthorities() []CertificateAuthority { @@ -67,12 +67,12 @@ func (tmc TrustedMaterialCollection) PublicKeyVerifier(keyID string) (TimeConstr return nil, fmt.Errorf("public key verifier not found for keyID: %s", keyID) } -func (tmc TrustedMaterialCollection) TimestampingAuthorities() []CertificateAuthority { - var certAuthorities []CertificateAuthority +func (tmc TrustedMaterialCollection) TimestampingAuthorities() []TimestampingAuthority { + var timestampingAuthorities []TimestampingAuthority for _, tm := range tmc { - certAuthorities = append(certAuthorities, tm.TimestampingAuthorities()...) + timestampingAuthorities = append(timestampingAuthorities, tm.TimestampingAuthorities()...) } - return certAuthorities + return timestampingAuthorities } func (tmc TrustedMaterialCollection) FulcioCertificateAuthorities() []CertificateAuthority { diff --git a/vendor/github.com/sigstore/sigstore-go/pkg/root/trusted_root.go b/vendor/github.com/sigstore/sigstore-go/pkg/root/trusted_root.go index 3112aebb53..c48c6084b3 100644 --- a/vendor/github.com/sigstore/sigstore-go/pkg/root/trusted_root.go +++ b/vendor/github.com/sigstore/sigstore-go/pkg/root/trusted_root.go @@ -40,18 +40,9 @@ type TrustedRoot struct { BaseTrustedMaterial trustedRoot *prototrustroot.TrustedRoot rekorLogs map[string]*TransparencyLog - fulcioCertAuthorities []CertificateAuthority + certificateAuthorities []CertificateAuthority ctLogs map[string]*TransparencyLog - timestampingAuthorities []CertificateAuthority -} - -type CertificateAuthority struct { - Root *x509.Certificate - Intermediates []*x509.Certificate - Leaf *x509.Certificate - ValidityPeriodStart time.Time - ValidityPeriodEnd time.Time - URI string + timestampingAuthorities []TimestampingAuthority } type TransparencyLog struct { @@ -66,12 +57,12 @@ type TransparencyLog struct { SignatureHashFunc crypto.Hash } -func (tr *TrustedRoot) TimestampingAuthorities() []CertificateAuthority { +func (tr *TrustedRoot) TimestampingAuthorities() []TimestampingAuthority { return tr.timestampingAuthorities } func (tr *TrustedRoot) FulcioCertificateAuthorities() []CertificateAuthority { - return tr.fulcioCertAuthorities + return tr.certificateAuthorities } func (tr *TrustedRoot) RekorLogs() map[string]*TransparencyLog { @@ -102,12 +93,12 @@ func NewTrustedRootFromProtobuf(protobufTrustedRoot *prototrustroot.TrustedRoot) return nil, err } - trustedRoot.fulcioCertAuthorities, err = ParseCertificateAuthorities(protobufTrustedRoot.GetCertificateAuthorities()) + trustedRoot.certificateAuthorities, err = ParseCertificateAuthorities(protobufTrustedRoot.GetCertificateAuthorities()) if err != nil { return nil, err } - trustedRoot.timestampingAuthorities, err = ParseCertificateAuthorities(protobufTrustedRoot.GetTimestampAuthorities()) + trustedRoot.timestampingAuthorities, err = ParseTimestampingAuthorities(protobufTrustedRoot.GetTimestampAuthorities()) if err != nil { return nil, err } @@ -232,12 +223,12 @@ func ParseCertificateAuthorities(certAuthorities []*prototrustroot.CertificateAu if err != nil { return nil, err } - certificateAuthorities[i] = *certificateAuthority + certificateAuthorities[i] = certificateAuthority } return certificateAuthorities, nil } -func ParseCertificateAuthority(certAuthority *prototrustroot.CertificateAuthority) (certificateAuthority *CertificateAuthority, err error) { +func ParseCertificateAuthority(certAuthority *prototrustroot.CertificateAuthority) (*FulcioCertificateAuthority, error) { if certAuthority == nil { return nil, fmt.Errorf("CertificateAuthority is nil") } @@ -250,7 +241,7 @@ func ParseCertificateAuthority(certAuthority *prototrustroot.CertificateAuthorit return nil, fmt.Errorf("CertificateAuthority cert chain is empty") } - certificateAuthority = &CertificateAuthority{ + certificateAuthority := &FulcioCertificateAuthority{ URI: certAuthority.Uri, } for i, cert := range certChain.GetCertificates() { @@ -258,12 +249,9 @@ func ParseCertificateAuthority(certAuthority *prototrustroot.CertificateAuthorit if err != nil { return nil, err } - switch { - case i == 0 && !parsedCert.IsCA: - certificateAuthority.Leaf = parsedCert - case i < chainLen-1: + if i < chainLen-1 { certificateAuthority.Intermediates = append(certificateAuthority.Intermediates, parsedCert) - case i == chainLen-1: + } else { certificateAuthority.Root = parsedCert } } @@ -279,12 +267,70 @@ func ParseCertificateAuthority(certAuthority *prototrustroot.CertificateAuthorit } } - // TODO: Should we inspect/enforce ca.Subject and ca.Uri? - // TODO: Handle validity period (ca.ValidFor) + certificateAuthority.URI = certAuthority.Uri return certificateAuthority, nil } +func ParseTimestampingAuthorities(certAuthorities []*prototrustroot.CertificateAuthority) (timestampingAuthorities []TimestampingAuthority, err error) { + timestampingAuthorities = make([]TimestampingAuthority, len(certAuthorities)) + for i, certAuthority := range certAuthorities { + timestampingAuthority, err := ParseTimestampingAuthority(certAuthority) + if err != nil { + return nil, err + } + timestampingAuthorities[i] = timestampingAuthority + } + return timestampingAuthorities, nil +} + +func ParseTimestampingAuthority(certAuthority *prototrustroot.CertificateAuthority) (TimestampingAuthority, error) { + if certAuthority == nil { + return nil, fmt.Errorf("CertificateAuthority is nil") + } + certChain := certAuthority.GetCertChain() + if certChain == nil { + return nil, fmt.Errorf("CertificateAuthority missing cert chain") + } + chainLen := len(certChain.GetCertificates()) + if chainLen < 1 { + return nil, fmt.Errorf("CertificateAuthority cert chain is empty") + } + + timestampingAuthority := &SigstoreTimestampingAuthority{ + URI: certAuthority.Uri, + } + for i, cert := range certChain.GetCertificates() { + parsedCert, err := x509.ParseCertificate(cert.RawBytes) + if err != nil { + return nil, err + } + switch { + case i == 0 && !parsedCert.IsCA: + timestampingAuthority.Leaf = parsedCert + case i < chainLen-1: + timestampingAuthority.Intermediates = append(timestampingAuthority.Intermediates, parsedCert) + case i == chainLen-1: + timestampingAuthority.Root = parsedCert + } + } + validFor := certAuthority.GetValidFor() + if validFor != nil { + start := validFor.GetStart() + if start != nil { + timestampingAuthority.ValidityPeriodStart = start.AsTime() + } + end := validFor.GetEnd() + if end != nil { + timestampingAuthority.ValidityPeriodEnd = end.AsTime() + } + } + + timestampingAuthority.URI = certAuthority.Uri + + return timestampingAuthority, nil +} + func NewTrustedRootFromPath(path string) (*TrustedRoot, error) { trustedrootJSON, err := os.ReadFile(path) if err != nil { @@ -320,14 +366,14 @@ func NewTrustedRootProtobuf(rootJSON []byte) (*prototrustroot.TrustedRoot, error func NewTrustedRoot(mediaType string, certificateAuthorities []CertificateAuthority, certificateTransparencyLogs map[string]*TransparencyLog, - timestampAuthorities []CertificateAuthority, + timestampAuthorities []TimestampingAuthority, transparencyLogs map[string]*TransparencyLog) (*TrustedRoot, error) { // document that we assume 1 cert chain per target and with certs already ordered from leaf to root if mediaType != TrustedRootMediaType01 { return nil, fmt.Errorf("unsupported TrustedRoot media type: %s", TrustedRootMediaType01) } tr := &TrustedRoot{ - fulcioCertAuthorities: certificateAuthorities, + certificateAuthorities: certificateAuthorities, ctLogs: certificateTransparencyLogs, timestampingAuthorities: timestampAuthorities, rekorLogs: transparencyLogs, @@ -428,7 +474,7 @@ func NewLiveTrustedRoot(opts *tuf.Options) (*LiveTrustedRoot, error) { return ltr, nil } -func (l *LiveTrustedRoot) TimestampingAuthorities() []CertificateAuthority { +func (l *LiveTrustedRoot) TimestampingAuthorities() []TimestampingAuthority { l.mu.RLock() defer l.mu.RUnlock() return l.TrustedRoot.TimestampingAuthorities() diff --git a/vendor/github.com/sigstore/sigstore-go/pkg/root/trusted_root_create.go b/vendor/github.com/sigstore/sigstore-go/pkg/root/trusted_root_create.go index b9de08b29f..d467c2bd74 100644 --- a/vendor/github.com/sigstore/sigstore-go/pkg/root/trusted_root_create.go +++ b/vendor/github.com/sigstore/sigstore-go/pkg/root/trusted_root_create.go @@ -54,8 +54,8 @@ func (tr *TrustedRoot) constructProtoTrustRoot() error { // ensure stable sorting of the slice sortTlogSlice(tr.trustedRoot.Ctlogs) - for _, ca := range tr.fulcioCertAuthorities { - caProto, err := certificateAuthorityToProtobufCA(&ca) + for _, ca := range tr.certificateAuthorities { + caProto, err := certificateAuthorityToProtobufCA(ca.(*FulcioCertificateAuthority)) if err != nil { return fmt.Errorf("failed converting fulcio cert chain to protobuf: %w", err) } @@ -65,7 +65,7 @@ func (tr *TrustedRoot) constructProtoTrustRoot() error { sortCASlice(tr.trustedRoot.CertificateAuthorities) for _, ca := range tr.timestampingAuthorities { - caProto, err := certificateAuthorityToProtobufCA(&ca) + caProto, err := timestampingAuthorityToProtobufCA(ca.(*SigstoreTimestampingAuthority)) if err != nil { return fmt.Errorf("failed converting TSA cert chain to protobuf: %w", err) } @@ -109,7 +109,42 @@ func sortTlogSlice(slc []*prototrustroot.TransparencyLogInstance) { }) } -func certificateAuthorityToProtobufCA(ca *CertificateAuthority) (*prototrustroot.CertificateAuthority, error) { +func certificateAuthorityToProtobufCA(ca *FulcioCertificateAuthority) (*prototrustroot.CertificateAuthority, error) { + org := "" + if len(ca.Root.Subject.Organization) > 0 { + org = ca.Root.Subject.Organization[0] + } + var allCerts []*protocommon.X509Certificate + for _, intermed := range ca.Intermediates { + allCerts = append(allCerts, &protocommon.X509Certificate{RawBytes: intermed.Raw}) + } + if ca.Root == nil { + return nil, fmt.Errorf("root certificate is nil") + } + allCerts = append(allCerts, &protocommon.X509Certificate{RawBytes: ca.Root.Raw}) + + caProto := prototrustroot.CertificateAuthority{ + Uri: ca.URI, + Subject: &protocommon.DistinguishedName{ + Organization: org, + CommonName: ca.Root.Subject.CommonName, + }, + ValidFor: &protocommon.TimeRange{ + Start: timestamppb.New(ca.ValidityPeriodStart), + }, + CertChain: &protocommon.X509CertificateChain{ + Certificates: allCerts, + }, + } + + if !ca.ValidityPeriodEnd.IsZero() { + caProto.ValidFor.End = timestamppb.New(ca.ValidityPeriodEnd) + } + + return &caProto, nil +} + +func timestampingAuthorityToProtobufCA(ca *SigstoreTimestampingAuthority) (*prototrustroot.CertificateAuthority, error) { org := "" if len(ca.Root.Subject.Organization) > 0 { org = ca.Root.Subject.Organization[0] diff --git a/vendor/github.com/sigstore/sigstore-go/pkg/tuf/repository/root.json b/vendor/github.com/sigstore/sigstore-go/pkg/tuf/repository/root.json index 8c12a0c0a9..451d4143ec 100644 --- a/vendor/github.com/sigstore/sigstore-go/pkg/tuf/repository/root.json +++ b/vendor/github.com/sigstore/sigstore-go/pkg/tuf/repository/root.json @@ -1,164 +1,165 @@ { - "signed": { - "_type": "root", - "spec_version": "1.0", - "version": 9, - "expires": "2024-09-12T06:53:10Z", - "keys": { - "1e1d65ce98b10addad4764febf7dda2d0436b3d3a3893579c0dddaea20e54849": { - "keytype": "ecdsa", - "scheme": "ecdsa-sha2-nistp256", - "keyid_hash_algorithms": [ - "sha256", - "sha512" - ], - "keyval": { - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEzBzVOmHCPojMVLSI364WiiV8NPrD\n6IgRxVliskz/v+y3JER5mcVGcONliDcWMC5J2lfHmjPNPhb4H7xm8LzfSA==\n-----END PUBLIC KEY-----\n" - } - }, - "230e212616274a4195cdc28e9fce782c20e6c720f1a811b40f98228376bdd3ac": { - "keytype": "ecdsa", - "scheme": "ecdsa-sha2-nistp256", - "keyid_hash_algorithms": [ - "sha256", - "sha512" - ], - "keyval": { - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAELrWvNt94v4R085ELeeCMxHp7PldF\n0/T1GxukUh2ODuggLGJE0pc1e8CSBf6CS91Fwo9FUOuRsjBUld+VqSyCdQ==\n-----END PUBLIC KEY-----\n" - } - }, - "3c344aa068fd4cc4e87dc50b612c02431fbc771e95003993683a2b0bf260cf0e": { - "keytype": "ecdsa", - "scheme": "ecdsa-sha2-nistp256", - "keyid_hash_algorithms": [ - "sha256", - "sha512" - ], - "keyval": { - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEy8XKsmhBYDI8Jc0GwzBxeKax0cm5\nSTKEU65HPFunUn41sT8pi0FjM4IkHz/YUmwmLUO0Wt7lxhj6BkLIK4qYAw==\n-----END PUBLIC KEY-----\n" - } - }, - "923bb39e60dd6fa2c31e6ea55473aa93b64dd4e53e16fbe42f6a207d3f97de2d": { - "keytype": "ecdsa", - "scheme": "ecdsa-sha2-nistp256", - "keyid_hash_algorithms": [ - "sha256", - "sha512" - ], - "keyval": { - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEWRiGr5+j+3J5SsH+Ztr5nE2H2wO7\nBV+nO3s93gLca18qTOzHY1oWyAGDykMSsGTUBSt9D+An0KfKsD2mfSM42Q==\n-----END PUBLIC KEY-----\n" - } - }, - "e2f59acb9488519407e18cbfc9329510be03c04aca9929d2f0301343fec85523": { - "keytype": "ecdsa", - "scheme": "ecdsa-sha2-nistp256", - "keyid_hash_algorithms": [ - "sha256", - "sha512" - ], - "keyval": { - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEinikSsAQmYkNeH5eYq/CnIzLaacO\nxlSaawQDOwqKy/tCqxq5xxPSJc21K4WIhs9GyOkKfzueY3GILzcMJZ4cWw==\n-----END PUBLIC KEY-----\n" - } - }, - "ec81669734e017996c5b85f3d02c3de1dd4637a152019fe1af125d2f9368b95e": { - "keytype": "ecdsa", - "scheme": "ecdsa-sha2-nistp256", - "keyid_hash_algorithms": [ - "sha256", - "sha512" - ], - "keyval": { - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEXsz3SZXFb8jMV42j6pJlyjbjR8K\nN3Bwocexq6LMIb5qsWKOQvLN16NUefLc4HswOoumRsVVaajSpQS6fobkRw==\n-----END PUBLIC KEY-----\n" - } - }, - "fdfa83a07b5a83589b87ded41f77f39d232ad91f7cce52868dacd06ba089849f": { - "keytype": "ecdsa", - "scheme": "ecdsa-sha2-nistp256", - "keyid_hash_algorithms": [ - "sha256", - "sha512" - ], - "keyval": { - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE0ghrh92Lw1Yr3idGV5WqCtMDB8Cx\n+D8hdC4w2ZLNIplVRoVGLskYa3gheMyOjiJ8kPi15aQ2//7P+oj7UvJPGw==\n-----END PUBLIC KEY-----\n" - } - } - }, - "roles": { - "root": { - "keyids": [ - "3c344aa068fd4cc4e87dc50b612c02431fbc771e95003993683a2b0bf260cf0e", - "ec81669734e017996c5b85f3d02c3de1dd4637a152019fe1af125d2f9368b95e", - "1e1d65ce98b10addad4764febf7dda2d0436b3d3a3893579c0dddaea20e54849", - "e2f59acb9488519407e18cbfc9329510be03c04aca9929d2f0301343fec85523", - "fdfa83a07b5a83589b87ded41f77f39d232ad91f7cce52868dacd06ba089849f" - ], - "threshold": 3 - }, - "snapshot": { - "keyids": [ - "230e212616274a4195cdc28e9fce782c20e6c720f1a811b40f98228376bdd3ac" - ], - "threshold": 1 - }, - "targets": { - "keyids": [ - "3c344aa068fd4cc4e87dc50b612c02431fbc771e95003993683a2b0bf260cf0e", - "ec81669734e017996c5b85f3d02c3de1dd4637a152019fe1af125d2f9368b95e", - "1e1d65ce98b10addad4764febf7dda2d0436b3d3a3893579c0dddaea20e54849", - "e2f59acb9488519407e18cbfc9329510be03c04aca9929d2f0301343fec85523", - "fdfa83a07b5a83589b87ded41f77f39d232ad91f7cce52868dacd06ba089849f" - ], - "threshold": 3 - }, - "timestamp": { - "keyids": [ - "923bb39e60dd6fa2c31e6ea55473aa93b64dd4e53e16fbe42f6a207d3f97de2d" - ], - "threshold": 1 - } - }, - "consistent_snapshot": true - }, - "signatures": [ - { - "keyid": "ff51e17fcf253119b7033f6f57512631da4a0969442afcf9fc8b141c7f2be99c", - "sig": "30450221008b78f894c3cfed3bd486379c4e0e0dfb3e7dd8cbc4d5598d2818eea1ba3c7550022029d3d06e89d04d37849985dc46c0e10dc5b1fc68dc70af1ec9910303a1f3ee2f" - }, - { - "keyid": "25a0eb450fd3ee2bd79218c963dce3f1cc6118badf251bf149f0bd07d5cabe99", - "sig": "30450221009e6b90b935e09b837a90d4402eaa27d5ea26eb7891948ba0ed7090841248f436022003dc2251c4d4a7999b91e9ad0868765ae09ac7269279f2a7899bafef7a2d9260" - }, - { - "keyid": "f5312f542c21273d9485a49394386c4575804770667f2ddb59b3bf0669fddd2f", - "sig": "30440220099e907dcf90b7b6e109fd1d6e442006fccbb48894aaaff47ab824b03fb35d0d02202aa0a06c21a4233f37900a48bc8777d3b47f59e3a38616ce631a04df57f96736" - }, - { - "keyid": "3c344aa068fd4cc4e87dc50b612c02431fbc771e95003993683a2b0bf260cf0e", - "sig": "30450221008b78f894c3cfed3bd486379c4e0e0dfb3e7dd8cbc4d5598d2818eea1ba3c7550022029d3d06e89d04d37849985dc46c0e10dc5b1fc68dc70af1ec9910303a1f3ee2f" - }, - { - "keyid": "ec81669734e017996c5b85f3d02c3de1dd4637a152019fe1af125d2f9368b95e", - "sig": "30450221009e6b90b935e09b837a90d4402eaa27d5ea26eb7891948ba0ed7090841248f436022003dc2251c4d4a7999b91e9ad0868765ae09ac7269279f2a7899bafef7a2d9260" - }, - { - "keyid": "e2f59acb9488519407e18cbfc9329510be03c04aca9929d2f0301343fec85523", - "sig": "304502200e5613b901e0f3e08eceabddc73f98b50ddf892e998d0b369c6e3d451ac48875022100940cf92d1f43ee2e5cdbb22572bb52925ed3863a688f7ffdd4bd2e2e56f028b3" - }, - { - "keyid": "2e61cd0cbf4a8f45809bda9f7f78c0d33ad11842ff94ae340873e2664dc843de", - "sig": "304502202cff44f2215d7a47b28b8f5f580c2cfbbd1bfcfcbbe78de323045b2c0badc5e9022100c743949eb3f4ea5a4b9ae27ac6eddea1f0ff9bfd004f8a9a9d18c6e4142b6e75" - }, - { - "keyid": "1e1d65ce98b10addad4764febf7dda2d0436b3d3a3893579c0dddaea20e54849", - "sig": "30440220099e907dcf90b7b6e109fd1d6e442006fccbb48894aaaff47ab824b03fb35d0d02202aa0a06c21a4233f37900a48bc8777d3b47f59e3a38616ce631a04df57f96736" - }, - { - "keyid": "fdfa83a07b5a83589b87ded41f77f39d232ad91f7cce52868dacd06ba089849f", - "sig": "304502202cff44f2215d7a47b28b8f5f580c2cfbbd1bfcfcbbe78de323045b2c0badc5e9022100c743949eb3f4ea5a4b9ae27ac6eddea1f0ff9bfd004f8a9a9d18c6e4142b6e75" - }, - { - "keyid": "7f7513b25429a64473e10ce3ad2f3da372bbdd14b65d07bbaf547e7c8bbbe62b", - "sig": "304502200e5613b901e0f3e08eceabddc73f98b50ddf892e998d0b369c6e3d451ac48875022100940cf92d1f43ee2e5cdbb22572bb52925ed3863a688f7ffdd4bd2e2e56f028b3" - } - ] + "signatures": [ + { + "keyid": "6f260089d5923daf20166ca657c543af618346ab971884a99962b01988bbe0c3", + "sig": "30460221008ab1f6f17d4f9e6d7dcf1c88912b6b53cc10388644ae1f09bc37a082cd06003e022100e145ef4c7b782d4e8107b53437e669d0476892ce999903ae33d14448366996e7" + }, + { + "keyid": "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2", + "sig": "3045022100c768b2f86da99569019c160a081da54ae36c34c0a3120d3cb69b53b7d113758e02204f671518f617b20d46537fae6c3b63bae8913f4f1962156105cc4f019ac35c6a" + }, + { + "keyid": "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06", + "sig": "3045022100b4434e6995d368d23e74759acd0cb9013c83a5d3511f0f997ec54c456ae4350a022015b0e265d182d2b61dc74e155d98b3c3fbe564ba05286aa14c8df02c9b756516" + }, + { + "keyid": "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222", + "sig": "304502210082c58411d989eb9f861410857d42381590ec9424dbdaa51e78ed13515431904e0220118185da6a6c2947131c17797e2bb7620ce26e5f301d1ceac5f2a7e58f9dcf2e" + }, + { + "keyid": "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70", + "sig": "3046022100c78513854cae9c32eaa6b88e18912f48006c2757a258f917312caba75948eb9e022100d9e1b4ce0adfe9fd2e2148d7fa27a2f40ba1122bd69da7612d8d1776b013c91d" + }, + { + "keyid": "fdfa83a07b5a83589b87ded41f77f39d232ad91f7cce52868dacd06ba089849f", + "sig": "3045022056483a2d5d9ea9cec6e11eadfb33c484b614298faca15acf1c431b11ed7f734c022100d0c1d726af92a87e4e66459ca5adf38a05b44e1f94318423f954bae8bca5bb2e" + }, + { + "keyid": "e2f59acb9488519407e18cbfc9329510be03c04aca9929d2f0301343fec85523", + "sig": "3046022100d004de88024c32dc5653a9f4843cfc5215427048ad9600d2cf9c969e6edff3d2022100d9ebb798f5fc66af10899dece014a8628ccf3c5402cd4a4270207472f8f6e712" + }, + { + "keyid": "3c344aa068fd4cc4e87dc50b612c02431fbc771e95003993683a2b0bf260cf0e", + "sig": "3046022100b7b09996c45ca2d4b05603e56baefa29718a0b71147cf8c6e66349baa61477df022100c4da80c717b4fa7bba0fd5c72da8a0499358b01358b2309f41d1456ea1e7e1d9" + }, + { + "keyid": "ec81669734e017996c5b85f3d02c3de1dd4637a152019fe1af125d2f9368b95e", + "sig": "3046022100be9782c30744e411a82fa85b5138d601ce148bc19258aec64e7ec24478f38812022100caef63dcaf1a4b9a500d3bd0e3f164ec18f1b63d7a9460d9acab1066db0f016d" + }, + { + "keyid": "1e1d65ce98b10addad4764febf7dda2d0436b3d3a3893579c0dddaea20e54849", + "sig": "30450220746ec3f8534ce55531d0d01ff64964ef440d1e7d2c4c142409b8e9769f1ada6f022100e3b929fcd93ea18feaa0825887a7210489879a66780c07a83f4bd46e2f09ab3b" + } + ], + "signed": { + "_type": "root", + "consistent_snapshot": true, + "expires": "2025-02-19T08:04:32Z", + "keys": { + "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEzBzVOmHCPojMVLSI364WiiV8NPrD\n6IgRxVliskz/v+y3JER5mcVGcONliDcWMC5J2lfHmjPNPhb4H7xm8LzfSA==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@santiagotorres" + }, + "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEinikSsAQmYkNeH5eYq/CnIzLaacO\nxlSaawQDOwqKy/tCqxq5xxPSJc21K4WIhs9GyOkKfzueY3GILzcMJZ4cWw==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@bobcallaway" + }, + "6f260089d5923daf20166ca657c543af618346ab971884a99962b01988bbe0c3": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEy8XKsmhBYDI8Jc0GwzBxeKax0cm5\nSTKEU65HPFunUn41sT8pi0FjM4IkHz/YUmwmLUO0Wt7lxhj6BkLIK4qYAw==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@dlorenc" + }, + "7247f0dbad85b147e1863bade761243cc785dcb7aa410e7105dd3d2b61a36d2c": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEWRiGr5+j+3J5SsH+Ztr5nE2H2wO7\nBV+nO3s93gLca18qTOzHY1oWyAGDykMSsGTUBSt9D+An0KfKsD2mfSM42Q==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-online-uri": "gcpkms://projects/sigstore-root-signing/locations/global/keyRings/root/cryptoKeys/timestamp" + }, + "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE0ghrh92Lw1Yr3idGV5WqCtMDB8Cx\n+D8hdC4w2ZLNIplVRoVGLskYa3gheMyOjiJ8kPi15aQ2//7P+oj7UvJPGw==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@joshuagl" + }, + "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEXsz3SZXFb8jMV42j6pJlyjbjR8K\nN3Bwocexq6LMIb5qsWKOQvLN16NUefLc4HswOoumRsVVaajSpQS6fobkRw==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@mnm678" + } + }, + "roles": { + "root": { + "keyids": [ + "6f260089d5923daf20166ca657c543af618346ab971884a99962b01988bbe0c3", + "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2", + "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06", + "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222", + "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70" + ], + "threshold": 3 + }, + "snapshot": { + "keyids": [ + "7247f0dbad85b147e1863bade761243cc785dcb7aa410e7105dd3d2b61a36d2c" + ], + "threshold": 1, + "x-tuf-on-ci-expiry-period": 3650, + "x-tuf-on-ci-signing-period": 365 + }, + "targets": { + "keyids": [ + "6f260089d5923daf20166ca657c543af618346ab971884a99962b01988bbe0c3", + "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2", + "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06", + "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222", + "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70" + ], + "threshold": 3 + }, + "timestamp": { + "keyids": [ + "7247f0dbad85b147e1863bade761243cc785dcb7aa410e7105dd3d2b61a36d2c" + ], + "threshold": 1, + "x-tuf-on-ci-expiry-period": 7, + "x-tuf-on-ci-signing-period": 4 + } + }, + "spec_version": "1.0", + "version": 10, + "x-tuf-on-ci-expiry-period": 182, + "x-tuf-on-ci-signing-period": 31 + } } diff --git a/vendor/github.com/sigstore/sigstore-go/pkg/tuf/repository/staging_root.json b/vendor/github.com/sigstore/sigstore-go/pkg/tuf/repository/staging_root.json index a9174b1f18..0dcde90a08 100644 --- a/vendor/github.com/sigstore/sigstore-go/pkg/tuf/repository/staging_root.json +++ b/vendor/github.com/sigstore/sigstore-go/pkg/tuf/repository/staging_root.json @@ -1,81 +1,81 @@ { "signatures": [ { - "keyid": "762cb22caca65de5e9b7b6baecb84ca989d337280ce6914b6440aea95769ad93", - "sig": "3045022100ac48110076c9264a95e9cfdb7dc72fdf2aeefa6f0c06919f6780933ef00d8f33022040bcef86bfbe246a603b4d6def14ba9b3bd245b134257d570dd79ef52e8de134" + "keyid": "aa61e09f6af7662ac686cf0c6364079f63d3e7a86836684eeced93eace3acd81", + "sig": "304502204d5d01c2ae4b846cc6d29d7c5676f5d99ea464a69bd464fef16a5d0cdd4a616d022100bf73b2b11b68bf7a7047480bf0d5961a3a40c524f64a82e2c90f59d4083e498e" }, { - "keyid": "d7d2d47a3f644fc3a685bac7b39c81ed9f9cee48ff861b44fbd86b91e34e7829", - "sig": "3046022100872bef41303c3ca2a7174f9b62c3999c05a2f4f79f0eb6a11d0196bc7e2b5068022100ecd664cf3cd5d280dd1ce479b3a9175ea4347e67e18f44db3f9872267cc20c5e" + "keyid": "61f9609d2655b346fcebccd66b509d5828168d5e447110e261f0bcc8553624bc", + "sig": "3044022005a8e904d484b7f4c3bac53ed6babeee303f6308f81f9ea29a7a1f6ad51068c20220641303f1e5ab14b151525c63ca95b35df64ffc905c8883f96cbee703ed45a2df" }, { - "keyid": "b78c9e4ff9048a1d9876a20f97fa1b3cb03223a0c520c7de730cfa9f5c7b77e5", - "sig": "3045022100c2e73ee944df991aa88fc9bdb6caaa94e0ca3b7d8c963bf3460eafc23f6ac1ce02202dfcf29fd52c768f9482511ed8382d42634a255e3ac435ca36928db81667e81d" + "keyid": "9471fbda95411d10109e467ad526082d15f14a38de54ea2ada9687ab39d8e237", + "sig": "" }, { - "keyid": "afd6a6ebad62a0dd091db368c1806eeb172c893c80bece1098fed116e985ba35", - "sig": "30440220594071728ae3cc8751caf2f506f4a594b0b38d14eb0f244fc96bd54eba345f0d022069c155f8c98ada28ccf28a1420bb6e4fbed13689ac028c13d23142fd6799cd69" + "keyid": "0374a9e18a20a2103736cb4277e2fdd7f8453642c7d9eaf4ad8aee9cf2d47bb5", + "sig": "" } ], "signed": { "_type": "root", "consistent_snapshot": true, - "expires": "2024-06-26T12:37:39Z", + "expires": "2025-03-07T07:44:40Z", "keys": { - "5416a7a35ef827abc651e200ac11f3d23e9db74ef890b1fedb69fb2a152ebac5": { + "0374a9e18a20a2103736cb4277e2fdd7f8453642c7d9eaf4ad8aee9cf2d47bb5": { "keytype": "ecdsa", "keyval": { - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAExxmEtmhF5U+i+v/6he4BcSLzCgMx\n/0qSrvDg6bUWwUrkSKS2vDpcJrhGy5fmmhRrGawjPp1ALpC3y1kqFTpXDg==\n-----END PUBLIC KEY-----\n" + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEoxkvDOmtGEknB3M+ZkPts8joDM0X\nIH5JZwPlgC2CXs/eqOuNF8AcEWwGYRiDhV/IMlQw5bg8PLICQcgsbrDiKg==\n-----END PUBLIC KEY-----\n" }, "scheme": "ecdsa-sha2-nistp256", - "x-tuf-on-ci-online-uri": "gcpkms:projects/projectsigstore-staging/locations/global/keyRings/tuf-keyring/cryptoKeys/tuf-key/cryptoKeyVersions/2" + "x-tuf-on-ci-keyowner": "@mnm678" }, - "762cb22caca65de5e9b7b6baecb84ca989d337280ce6914b6440aea95769ad93": { + "61f9609d2655b346fcebccd66b509d5828168d5e447110e261f0bcc8553624bc": { "keytype": "ecdsa", "keyval": { - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEohqIdE+yTl4OxpX8ZxNUPrg3SL9H\nBDnhZuceKkxy2oMhUOxhWweZeG3bfM1T4ZLnJimC6CAYVU5+F5jZCoftRw==\n-----END PUBLIC KEY-----\n" + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE++Wv+DcLRk+mfkmlpCwl1GUi9EMh\npBUTz8K0fH7bE4mQuViGSyWA/eyMc0HvzZi6Xr0diHw0/lUPBvok214YQw==\n-----END PUBLIC KEY-----\n" }, "scheme": "ecdsa-sha2-nistp256", - "x-tuf-on-ci-keyowner": "@jku" + "x-tuf-on-ci-keyowner": "@kommendorkapten" }, - "afd6a6ebad62a0dd091db368c1806eeb172c893c80bece1098fed116e985ba35": { + "9471fbda95411d10109e467ad526082d15f14a38de54ea2ada9687ab39d8e237": { "keytype": "ecdsa", "keyval": { - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEoxkvDOmtGEknB3M+ZkPts8joDM0X\nIH5JZwPlgC2CXs/eqOuNF8AcEWwGYRiDhV/IMlQw5bg8PLICQcgsbrDiKg==\n-----END PUBLIC KEY-----\n" + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEFHDb85JH+JYR1LQmxiz4UMokVMnP\nxKoWpaEnFCKXH8W4Fc/DfIxMnkpjCuvWUBdJXkO0aDIxwsij8TOFh2R7dw==\n-----END PUBLIC KEY-----\n" }, "scheme": "ecdsa-sha2-nistp256", - "x-tuf-on-ci-keyowner": "@mnm678" + "x-tuf-on-ci-keyowner": "@joshuagl" }, - "b78c9e4ff9048a1d9876a20f97fa1b3cb03223a0c520c7de730cfa9f5c7b77e5": { + "aa61e09f6af7662ac686cf0c6364079f63d3e7a86836684eeced93eace3acd81": { "keytype": "ecdsa", "keyval": { - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEFHDb85JH+JYR1LQmxiz4UMokVMnP\nxKoWpaEnFCKXH8W4Fc/DfIxMnkpjCuvWUBdJXkO0aDIxwsij8TOFh2R7dw==\n-----END PUBLIC KEY-----\n" + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEohqIdE+yTl4OxpX8ZxNUPrg3SL9H\nBDnhZuceKkxy2oMhUOxhWweZeG3bfM1T4ZLnJimC6CAYVU5+F5jZCoftRw==\n-----END PUBLIC KEY-----\n" }, "scheme": "ecdsa-sha2-nistp256", - "x-tuf-on-ci-keyowner": "@joshuagl" + "x-tuf-on-ci-keyowner": "@jku" }, - "d7d2d47a3f644fc3a685bac7b39c81ed9f9cee48ff861b44fbd86b91e34e7829": { + "c3479007e861445ce5dc109d9661ed77b35bbc0e3f161852c46114266fc2daa4": { "keytype": "ecdsa", "keyval": { - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE++Wv+DcLRk+mfkmlpCwl1GUi9EMh\npBUTz8K0fH7bE4mQuViGSyWA/eyMc0HvzZi6Xr0diHw0/lUPBvok214YQw==\n-----END PUBLIC KEY-----\n" + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAExxmEtmhF5U+i+v/6he4BcSLzCgMx\n/0qSrvDg6bUWwUrkSKS2vDpcJrhGy5fmmhRrGawjPp1ALpC3y1kqFTpXDg==\n-----END PUBLIC KEY-----\n" }, "scheme": "ecdsa-sha2-nistp256", - "x-tuf-on-ci-keyowner": "@kommendorkapten" + "x-tuf-on-ci-online-uri": "gcpkms:projects/projectsigstore-staging/locations/global/keyRings/tuf-keyring/cryptoKeys/tuf-key/cryptoKeyVersions/2" } }, "roles": { "root": { "keyids": [ - "762cb22caca65de5e9b7b6baecb84ca989d337280ce6914b6440aea95769ad93", - "d7d2d47a3f644fc3a685bac7b39c81ed9f9cee48ff861b44fbd86b91e34e7829", - "b78c9e4ff9048a1d9876a20f97fa1b3cb03223a0c520c7de730cfa9f5c7b77e5", - "afd6a6ebad62a0dd091db368c1806eeb172c893c80bece1098fed116e985ba35" + "aa61e09f6af7662ac686cf0c6364079f63d3e7a86836684eeced93eace3acd81", + "61f9609d2655b346fcebccd66b509d5828168d5e447110e261f0bcc8553624bc", + "9471fbda95411d10109e467ad526082d15f14a38de54ea2ada9687ab39d8e237", + "0374a9e18a20a2103736cb4277e2fdd7f8453642c7d9eaf4ad8aee9cf2d47bb5" ], "threshold": 2 }, "snapshot": { "keyids": [ - "5416a7a35ef827abc651e200ac11f3d23e9db74ef890b1fedb69fb2a152ebac5" + "c3479007e861445ce5dc109d9661ed77b35bbc0e3f161852c46114266fc2daa4" ], "threshold": 1, "x-tuf-on-ci-expiry-period": 3650, @@ -83,25 +83,25 @@ }, "targets": { "keyids": [ - "762cb22caca65de5e9b7b6baecb84ca989d337280ce6914b6440aea95769ad93", - "d7d2d47a3f644fc3a685bac7b39c81ed9f9cee48ff861b44fbd86b91e34e7829", - "b78c9e4ff9048a1d9876a20f97fa1b3cb03223a0c520c7de730cfa9f5c7b77e5", - "afd6a6ebad62a0dd091db368c1806eeb172c893c80bece1098fed116e985ba35" + "aa61e09f6af7662ac686cf0c6364079f63d3e7a86836684eeced93eace3acd81", + "61f9609d2655b346fcebccd66b509d5828168d5e447110e261f0bcc8553624bc", + "9471fbda95411d10109e467ad526082d15f14a38de54ea2ada9687ab39d8e237", + "0374a9e18a20a2103736cb4277e2fdd7f8453642c7d9eaf4ad8aee9cf2d47bb5" ], "threshold": 1 }, "timestamp": { "keyids": [ - "5416a7a35ef827abc651e200ac11f3d23e9db74ef890b1fedb69fb2a152ebac5" + "c3479007e861445ce5dc109d9661ed77b35bbc0e3f161852c46114266fc2daa4" ], "threshold": 1, "x-tuf-on-ci-expiry-period": 7, - "x-tuf-on-ci-signing-period": 4 + "x-tuf-on-ci-signing-period": 6 } }, "spec_version": "1.0", - "version": 7, - "x-tuf-on-ci-expiry-period": 91, + "version": 10, + "x-tuf-on-ci-expiry-period": 182, "x-tuf-on-ci-signing-period": 35 } -} \ No newline at end of file +} diff --git a/vendor/github.com/sigstore/sigstore-go/pkg/verify/certificate.go b/vendor/github.com/sigstore/sigstore-go/pkg/verify/certificate.go index 4ce2dff287..e33d915a8d 100644 --- a/vendor/github.com/sigstore/sigstore-go/pkg/verify/certificate.go +++ b/vendor/github.com/sigstore/sigstore-go/pkg/verify/certificate.go @@ -22,40 +22,13 @@ import ( "github.com/sigstore/sigstore-go/pkg/root" ) -func VerifyLeafCertificate(observerTimestamp time.Time, leafCert *x509.Certificate, trustedMaterial root.TrustedMaterial) error { // nolint: revive +func VerifyLeafCertificate(observerTimestamp time.Time, leafCert *x509.Certificate, trustedMaterial root.TrustedMaterial) ([][]*x509.Certificate, error) { // nolint: revive for _, ca := range trustedMaterial.FulcioCertificateAuthorities() { - if !ca.ValidityPeriodStart.IsZero() && observerTimestamp.Before(ca.ValidityPeriodStart) { - continue - } - if !ca.ValidityPeriodEnd.IsZero() && observerTimestamp.After(ca.ValidityPeriodEnd) { - continue - } - - rootCertPool := x509.NewCertPool() - rootCertPool.AddCert(ca.Root) - intermediateCertPool := x509.NewCertPool() - for _, cert := range ca.Intermediates { - intermediateCertPool.AddCert(cert) - } - - // From spec: - // > ## Certificate - // > For a signature with a given certificate to be considered valid, it must have a timestamp while every certificate in the chain up to the root is valid (the so-called “hybrid model” of certificate verification per Braun et al. (2013)). - - opts := x509.VerifyOptions{ - CurrentTime: observerTimestamp, - Roots: rootCertPool, - Intermediates: intermediateCertPool, - KeyUsages: []x509.ExtKeyUsage{ - x509.ExtKeyUsageCodeSigning, - }, - } - - _, err := leafCert.Verify(opts) + chains, err := ca.Verify(leafCert, observerTimestamp) if err == nil { - return nil + return chains, nil } } - return errors.New("leaf certificate verification failed") + return nil, errors.New("leaf certificate verification failed") } diff --git a/vendor/github.com/sigstore/sigstore-go/pkg/verify/interface.go b/vendor/github.com/sigstore/sigstore-go/pkg/verify/interface.go index 6440554c5c..2ff080345d 100644 --- a/vendor/github.com/sigstore/sigstore-go/pkg/verify/interface.go +++ b/vendor/github.com/sigstore/sigstore-go/pkg/verify/interface.go @@ -21,7 +21,6 @@ import ( in_toto "github.com/in-toto/attestation/go/v1" "github.com/secure-systems-lab/go-securesystemslib/dsse" - protocommon "github.com/sigstore/protobuf-specs/gen/pb-go/common/v1" "github.com/sigstore/sigstore-go/pkg/root" "github.com/sigstore/sigstore-go/pkg/tlog" ) @@ -64,8 +63,8 @@ type SignedEntity interface { type VerificationContent interface { CompareKey(any, root.TrustedMaterial) bool ValidAtTime(time.Time, root.TrustedMaterial) bool - GetCertificate() *x509.Certificate - HasPublicKey() (PublicKeyProvider, bool) + Certificate() *x509.Certificate + PublicKey() PublicKeyProvider } type SignatureContent interface { @@ -95,19 +94,21 @@ type EnvelopeContent interface { // that only implements a subset of the interfaces. type BaseSignedEntity struct{} -func (b *BaseSignedEntity) VerificationProvider() (VerificationContent, error) { - return nil, errNotImplemented +var _ SignedEntity = &BaseSignedEntity{} + +func (b *BaseSignedEntity) HasInclusionPromise() bool { + return false } -func (b *BaseSignedEntity) Envelope() (*dsse.Envelope, error) { - return nil, errNotImplemented +func (b *BaseSignedEntity) HasInclusionProof() bool { + return false } -func (b *BaseSignedEntity) MessageSignature() (*protocommon.MessageSignature, error) { +func (b *BaseSignedEntity) VerificationContent() (VerificationContent, error) { return nil, errNotImplemented } -func (b *BaseSignedEntity) Signature() ([]byte, error) { +func (b *BaseSignedEntity) SignatureContent() (SignatureContent, error) { return nil, errNotImplemented } diff --git a/vendor/github.com/sigstore/sigstore-go/pkg/verify/sct.go b/vendor/github.com/sigstore/sigstore-go/pkg/verify/sct.go index 7b6edf67bc..bf447c28c3 100644 --- a/vendor/github.com/sigstore/sigstore-go/pkg/verify/sct.go +++ b/vendor/github.com/sigstore/sigstore-go/pkg/verify/sct.go @@ -17,8 +17,10 @@ package verify import ( "crypto/x509" "encoding/hex" + "errors" "fmt" + ct "github.com/google/certificate-transparency-go" "github.com/google/certificate-transparency-go/ctutil" ctx509 "github.com/google/certificate-transparency-go/x509" "github.com/google/certificate-transparency-go/x509util" @@ -29,16 +31,21 @@ import ( // leaf certificate, will extract SCTs from the leaf certificate and verify the // timestamps using the TrustedMaterial's FulcioCertificateAuthorities() and // CTLogs() -func VerifySignedCertificateTimestamp(leafCert *x509.Certificate, threshold int, trustedMaterial root.TrustedMaterial) error { // nolint: revive +func VerifySignedCertificateTimestamp(chains [][]*x509.Certificate, threshold int, trustedMaterial root.TrustedMaterial) error { // nolint: revive + if len(chains) == 0 || len(chains[0]) == 0 || chains[0][0] == nil { + return errors.New("no chains provided") + } + // The first certificate in the chain is always the leaf certificate + leaf := chains[0][0] + ctlogs := trustedMaterial.CTLogs() - fulcioCerts := trustedMaterial.FulcioCertificateAuthorities() - scts, err := x509util.ParseSCTsFromCertificate(leafCert.Raw) + scts, err := x509util.ParseSCTsFromCertificate(leaf.Raw) if err != nil { return err } - leafCTCert, err := ctx509.ParseCertificates(leafCert.Raw) + leafCTCert, err := ctx509.ParseCertificates(leaf.Raw) if err != nil { return err } @@ -52,17 +59,25 @@ func VerifySignedCertificateTimestamp(leafCert *x509.Certificate, threshold int, continue } - for _, fulcioCa := range fulcioCerts { + // Ensure sct is within ctlog validity window + sctTime := ct.TimestampToTime(sct.Timestamp) + if !key.ValidityPeriodStart.IsZero() && sctTime.Before(key.ValidityPeriodStart) { + // skip entries that were before ctlog key start time + continue + } + if !key.ValidityPeriodEnd.IsZero() && sctTime.After(key.ValidityPeriodEnd) { + // skip entries that were after ctlog key end time + continue + } + + for _, chain := range chains { fulcioChain := make([]*ctx509.Certificate, len(leafCTCert)) copy(fulcioChain, leafCTCert) - var parentCert []byte - - if len(fulcioCa.Intermediates) == 0 { - parentCert = fulcioCa.Root.Raw - } else { - parentCert = fulcioCa.Intermediates[0].Raw + if len(chain) < 2 { + continue } + parentCert := chain[1].Raw fulcioIssuer, err := ctx509.ParseCertificates(parentCert) if err != nil { diff --git a/vendor/github.com/sigstore/sigstore-go/pkg/verify/signature.go b/vendor/github.com/sigstore/sigstore-go/pkg/verify/signature.go index 1d0ddfabbd..1d96c121b3 100644 --- a/vendor/github.com/sigstore/sigstore-go/pkg/verify/signature.go +++ b/vendor/github.com/sigstore/sigstore-go/pkg/verify/signature.go @@ -24,6 +24,7 @@ import ( "hash" "io" + in_toto "github.com/in-toto/attestation/go/v1" "github.com/secure-systems-lab/go-securesystemslib/dsse" "github.com/sigstore/sigstore-go/pkg/root" "github.com/sigstore/sigstore/pkg/signature" @@ -94,10 +95,10 @@ func VerifySignatureWithArtifactDigest(sigContent SignatureContent, verification } func getSignatureVerifier(verificationContent VerificationContent, tm root.TrustedMaterial) (signature.Verifier, error) { - if leafCert := verificationContent.GetCertificate(); leafCert != nil { + if leafCert := verificationContent.Certificate(); leafCert != nil { // TODO: Inspect certificate's SignatureAlgorithm to determine hash function return signature.LoadVerifier(leafCert.PublicKey, crypto.SHA256) - } else if pk, ok := verificationContent.HasPublicKey(); ok { + } else if pk := verificationContent.PublicKey(); pk != nil { return tm.PublicKeyVerifier(pk.Hint()) } @@ -142,6 +143,10 @@ func verifyEnvelopeWithArtifact(verifier signature.Verifier, envelope EnvelopeCo if err != nil { return fmt.Errorf("could not verify artifact: unable to extract statement from envelope: %w", err) } + if err = limitSubjects(statement); err != nil { + return err + } + var artifactDigestAlgorithm string var artifactDigest []byte @@ -182,17 +187,8 @@ func verifyEnvelopeWithArtifact(verifier signature.Verifier, envelope EnvelopeCo } artifactDigest = hasher.Sum(nil) - // limit the number of subjects to prevent DoS - if len(statement.Subject) > maxAllowedSubjects { - return fmt.Errorf("too many subjects: %d > %d", len(statement.Subject), maxAllowedSubjects) - } - // Look for artifact digest in statement for _, subject := range statement.Subject { - // limit the number of digests to prevent DoS - if len(subject.Digest) > maxAllowedSubjectDigests { - return fmt.Errorf("too many digests: %d > %d", len(subject.Digest), maxAllowedSubjectDigests) - } for alg, digest := range subject.Digest { hexdigest, err := hex.DecodeString(digest) if err != nil { @@ -215,17 +211,11 @@ func verifyEnvelopeWithArtifactDigest(verifier signature.Verifier, envelope Enve if err != nil { return fmt.Errorf("could not verify artifact: unable to extract statement from envelope: %w", err) } - - // limit the number of subjects to prevent DoS - if len(statement.Subject) > maxAllowedSubjects { - return fmt.Errorf("too many subjects: %d > %d", len(statement.Subject), maxAllowedSubjects) + if err = limitSubjects(statement); err != nil { + return err } for _, subject := range statement.Subject { - // limit the number of digests to prevent DoS - if len(subject.Digest) > maxAllowedSubjectDigests { - return fmt.Errorf("too many digests: %d > %d", len(subject.Digest), maxAllowedSubjectDigests) - } for alg, digest := range subject.Digest { if alg == artifactDigestAlgorithm { hexdigest, err := hex.DecodeString(digest) @@ -265,3 +255,17 @@ func verifyMessageSignatureWithArtifactDigest(verifier signature.Verifier, msg M return nil } + +// limitSubjects limits the number of subjects and digests in a statement to prevent DoS. +func limitSubjects(statement *in_toto.Statement) error { + if len(statement.Subject) > maxAllowedSubjects { + return fmt.Errorf("too many subjects: %d > %d", len(statement.Subject), maxAllowedSubjects) + } + for _, subject := range statement.Subject { + // limit the number of digests too + if len(subject.Digest) > maxAllowedSubjectDigests { + return fmt.Errorf("too many digests: %d > %d", len(subject.Digest), maxAllowedSubjectDigests) + } + } + return nil +} diff --git a/vendor/github.com/sigstore/sigstore-go/pkg/verify/signed_entity.go b/vendor/github.com/sigstore/sigstore-go/pkg/verify/signed_entity.go index 2ab826e911..918bf545c5 100644 --- a/vendor/github.com/sigstore/sigstore-go/pkg/verify/signed_entity.go +++ b/vendor/github.com/sigstore/sigstore-go/pkg/verify/signed_entity.go @@ -15,7 +15,9 @@ package verify import ( + "crypto/x509" "encoding/asn1" + "encoding/json" "errors" "fmt" "io" @@ -25,6 +27,7 @@ import ( "github.com/sigstore/sigstore-go/pkg/fulcio/certificate" "github.com/sigstore/sigstore-go/pkg/root" "github.com/sigstore/sigstore/pkg/cryptoutils" + "google.golang.org/protobuf/encoding/protojson" ) const ( @@ -37,12 +40,9 @@ type SignedEntityVerifier struct { } type VerifierConfig struct { // nolint: revive - // performOnlineVerification queries logs during verification. - // Default is offline - performOnlineVerification bool - // weExpectSignedTimestamps requires RFC3161 timestamps to verify + // requireSignedTimestamps requires RFC3161 timestamps to verify // short-lived certificates - weExpectSignedTimestamps bool + requireSignedTimestamps bool // signedTimestampThreshold is the minimum number of verified // RFC3161 timestamps in a bundle signedTimestampThreshold int @@ -58,20 +58,19 @@ type VerifierConfig struct { // nolint: revive // observerTimestampThreshold is the minimum number of verified // RFC3161 timestamps and/or log integrated timestamps in a bundle observerTimestampThreshold int - // weExpectTlogEntries requires log inclusion proofs in a bundle - weExpectTlogEntries bool + // requireTlogEntries requires log inclusion proofs in a bundle + requireTlogEntries bool // tlogEntriesThreshold is the minimum number of verified inclusion // proofs in a bundle tlogEntriesThreshold int - // weExpectSCTs requires SCTs in Fulcio certificates - weExpectSCTs bool + // requireSCTs requires SCTs in Fulcio certificates + requireSCTs bool // ctlogEntriesTreshold is the minimum number of verified SCTs in // a Fulcio certificate ctlogEntriesThreshold int - // weDoNotExpectAnyObserverTimestamps uses the certificate's lifetime - // rather than a provided signed or log timestamp. Most workflows will - // not use this option - weDoNotExpectAnyObserverTimestamps bool + // useCurrentTime uses the current time rather than a provided signed + // or log timestamp. Most workflows will not use this option + useCurrentTime bool } type VerifierOption func(*VerifierConfig) error @@ -108,16 +107,6 @@ func NewSignedEntityVerifier(trustedMaterial root.TrustedMaterial, options ...Ve return v, nil } -// WithOnlineVerification configures the SignedEntityVerifier to perform -// online verification when verifying Transparency Log entries and -// Signed Certificate Timestamps. -func WithOnlineVerification() VerifierOption { - return func(c *VerifierConfig) error { - c.performOnlineVerification = true - return nil - } -} - // WithSignedTimestamps configures the SignedEntityVerifier to expect RFC 3161 // timestamps from a Timestamp Authority, verify them using the TrustedMaterial's // TimestampingAuthorities(), and, if it exists, use the resulting timestamp(s) @@ -127,7 +116,7 @@ func WithSignedTimestamps(threshold int) VerifierOption { if threshold < 1 { return errors.New("signed timestamp threshold must be at least 1") } - c.weExpectSignedTimestamps = true + c.requireSignedTimestamps = true c.signedTimestampThreshold = threshold return nil } @@ -157,7 +146,7 @@ func WithTransparencyLog(threshold int) VerifierOption { if threshold < 1 { return errors.New("transparency log entry threshold must be at least 1") } - c.weExpectTlogEntries = true + c.requireTlogEntries = true c.tlogEntriesThreshold = threshold return nil } @@ -182,32 +171,28 @@ func WithSignedCertificateTimestamps(threshold int) VerifierOption { if threshold < 1 { return errors.New("ctlog entry threshold must be at least 1") } - c.weExpectSCTs = true + c.requireSCTs = true c.ctlogEntriesThreshold = threshold return nil } } -// WithoutAnyObserverTimestampsUnsafe configures the SignedEntityVerifier to not expect +// WithCurrentTime configures the SignedEntityVerifier to not expect // any timestamps from either a Timestamp Authority or a Transparency Log. -// -// A SignedEntity without a trusted "observer" timestamp to verify the attached -// Fulcio certificate can't provide the same kind of integrity guarantee. -// -// Do not enable this if you don't know what you are doing; as the name implies, -// using it defeats part of the security guarantees offered by Sigstore. This -// option is only useful for testing. -func WithoutAnyObserverTimestampsUnsafe() VerifierOption { +// This option should not be enabled when verifying short-lived certificates, +// as an observer timestamp is needed. This option is useful primarily for +// private deployments with long-lived code signing certificates. +func WithCurrentTime() VerifierOption { return func(c *VerifierConfig) error { - c.weDoNotExpectAnyObserverTimestamps = true + c.useCurrentTime = true return nil } } func (c *VerifierConfig) Validate() error { - if !c.requireObserverTimestamps && !c.weExpectSignedTimestamps && !c.requireIntegratedTimestamps && !c.weDoNotExpectAnyObserverTimestamps { + if !c.requireObserverTimestamps && !c.requireSignedTimestamps && !c.requireIntegratedTimestamps && !c.useCurrentTime { return errors.New("when initializing a new SignedEntityVerifier, you must specify at least one of " + - "WithObserverTimestamps(), WithSignedTimestamps(), WithIntegratedTimestamps(), or WithoutAnyObserverTimestampsUnsafe()") + "WithObserverTimestamps(), WithSignedTimestamps(), or WithIntegratedTimestamps()") } return nil @@ -238,6 +223,40 @@ func NewVerificationResult() *VerificationResult { } } +// MarshalJSON deals with protojson needed for the Statement. +// Can be removed when https://github.com/in-toto/attestation/pull/403 is merged. +func (b *VerificationResult) MarshalJSON() ([]byte, error) { + statement, err := protojson.Marshal(b.Statement) + if err != nil { + return nil, err + } + // creating a type alias to avoid infinite recursion, as MarshalJSON is + // not copied into the alias. + type Alias VerificationResult + return json.Marshal(struct { + Alias + Statement json.RawMessage `json:"statement,omitempty"` + }{ + Alias: Alias(*b), + Statement: statement, + }) +} + +func (b *VerificationResult) UnmarshalJSON(data []byte) error { + b.Statement = &in_toto.Statement{} + type Alias VerificationResult + aux := &struct { + Alias + Statement json.RawMessage `json:"statement,omitempty"` + }{ + Alias: Alias(*b), + } + if err := json.Unmarshal(data, aux); err != nil { + return err + } + return protojson.Unmarshal(aux.Statement, b.Statement) +} + type PolicyOption func(*PolicyConfig) error type ArtifactPolicyOption func(*PolicyConfig) error @@ -520,7 +539,7 @@ func (v *SignedEntityVerifier) Verify(entity SignedEntity, pb PolicyBuilder) (*V // If the bundle was signed with a long-lived key, and does not have a Fulcio certificate, // then skip the certificate verification steps - if leafCert := verificationContent.GetCertificate(); leafCert != nil { + if leafCert := verificationContent.Certificate(); leafCert != nil { if policy.WeExpectSigningKey() { return nil, errors.New("expected key signature, not certificate") } @@ -552,9 +571,10 @@ func (v *SignedEntityVerifier) Verify(entity SignedEntity, pb PolicyBuilder) (*V leafCert.UnhandledCriticalExtensions = unhandledExts } + var chains [][]*x509.Certificate for _, verifiedTs := range verifiedTimestamps { // verify the leaf certificate against the root - err = VerifyLeafCertificate(verifiedTs.Timestamp, leafCert, v.trustedMaterial) + chains, err = VerifyLeafCertificate(verifiedTs.Timestamp, leafCert, v.trustedMaterial) if err != nil { return nil, fmt.Errorf("failed to verify leaf certificate: %w", err) } @@ -563,8 +583,8 @@ func (v *SignedEntityVerifier) Verify(entity SignedEntity, pb PolicyBuilder) (*V // From spec: // > Unless performing online verification (see §Alternative Workflows), the Verifier MUST extract the SignedCertificateTimestamp embedded in the leaf certificate, and verify it as in RFC 9162 §8.1.3, using the verification key from the Certificate Transparency Log. - if v.config.weExpectSCTs { - err = VerifySignedCertificateTimestamp(leafCert, v.config.ctlogEntriesThreshold, v.trustedMaterial) + if v.config.requireSCTs { + err = VerifySignedCertificateTimestamp(chains, v.config.ctlogEntriesThreshold, v.trustedMaterial) if err != nil { return nil, fmt.Errorf("failed to verify signed certificate timestamp: %w", err) } @@ -658,16 +678,16 @@ func (v *SignedEntityVerifier) Verify(entity SignedEntity, pb PolicyBuilder) (*V func (v *SignedEntityVerifier) VerifyTransparencyLogInclusion(entity SignedEntity) ([]TimestampVerificationResult, error) { verifiedTimestamps := []TimestampVerificationResult{} - if v.config.weExpectTlogEntries { + if v.config.requireTlogEntries { // log timestamps should be verified if with WithIntegratedTimestamps or WithObserverTimestamps is used verifiedTlogTimestamps, err := VerifyArtifactTransparencyLog(entity, v.trustedMaterial, v.config.tlogEntriesThreshold, - v.config.requireIntegratedTimestamps || v.config.requireObserverTimestamps, v.config.performOnlineVerification) + v.config.requireIntegratedTimestamps || v.config.requireObserverTimestamps) if err != nil { return nil, err } for _, vts := range verifiedTlogTimestamps { - verifiedTimestamps = append(verifiedTimestamps, TimestampVerificationResult{Type: "Tlog", URI: "TODO", Timestamp: vts}) + verifiedTimestamps = append(verifiedTimestamps, TimestampVerificationResult{Type: "Tlog", URI: vts.URI, Timestamp: vts.Time}) } } @@ -686,13 +706,13 @@ func (v *SignedEntityVerifier) VerifyObserverTimestamps(entity SignedEntity, log // From spec: // > … if verification or timestamp parsing fails, the Verifier MUST abort - if v.config.weExpectSignedTimestamps { + if v.config.requireSignedTimestamps { verifiedSignedTimestamps, err := VerifyTimestampAuthorityWithThreshold(entity, v.trustedMaterial, v.config.signedTimestampThreshold) if err != nil { return nil, err } for _, vts := range verifiedSignedTimestamps { - verifiedTimestamps = append(verifiedTimestamps, TimestampVerificationResult{Type: "TimestampAuthority", URI: "TODO", Timestamp: vts}) + verifiedTimestamps = append(verifiedTimestamps, TimestampVerificationResult{Type: "TimestampAuthority", URI: vts.URI, Timestamp: vts.Time}) } } @@ -719,23 +739,13 @@ func (v *SignedEntityVerifier) VerifyObserverTimestamps(entity SignedEntity, log // append all timestamps verifiedTimestamps = append(verifiedTimestamps, logTimestamps...) for _, vts := range verifiedSignedTimestamps { - verifiedTimestamps = append(verifiedTimestamps, TimestampVerificationResult{Type: "TimestampAuthority", URI: "TODO", Timestamp: vts}) + verifiedTimestamps = append(verifiedTimestamps, TimestampVerificationResult{Type: "TimestampAuthority", URI: vts.URI, Timestamp: vts.Time}) } } - if v.config.weDoNotExpectAnyObserverTimestamps { - // if we have a cert, let's pop the leafcert's NotBefore - verificationContent, err := entity.VerificationContent() - if err != nil { - return nil, err - } - - if leafCert := verificationContent.GetCertificate(); leafCert != nil { - verifiedTimestamps = append(verifiedTimestamps, TimestampVerificationResult{Type: "LeafCert.NotBefore", URI: "", Timestamp: leafCert.NotBefore}) - } else { - // no cert? use current time - verifiedTimestamps = append(verifiedTimestamps, TimestampVerificationResult{Type: "CurrentTime", URI: "", Timestamp: time.Now()}) - } + if v.config.useCurrentTime { + // use current time to verify certificate if no signed timestamps are provided + verifiedTimestamps = append(verifiedTimestamps, TimestampVerificationResult{Type: "CurrentTime", URI: "", Timestamp: time.Now()}) } if len(verifiedTimestamps) == 0 { diff --git a/vendor/github.com/sigstore/sigstore-go/pkg/verify/tlog.go b/vendor/github.com/sigstore/sigstore-go/pkg/verify/tlog.go index e91baafde1..a52b0a17b2 100644 --- a/vendor/github.com/sigstore/sigstore-go/pkg/verify/tlog.go +++ b/vendor/github.com/sigstore/sigstore-go/pkg/verify/tlog.go @@ -16,22 +16,15 @@ package verify import ( "bytes" - "context" "crypto" "encoding/hex" "errors" "fmt" - "time" - rekorClient "github.com/sigstore/rekor/pkg/client" - rekorGeneratedClient "github.com/sigstore/rekor/pkg/generated/client" - rekorEntries "github.com/sigstore/rekor/pkg/generated/client/entries" - rekorVerify "github.com/sigstore/rekor/pkg/verify" "github.com/sigstore/sigstore/pkg/signature" "github.com/sigstore/sigstore-go/pkg/root" "github.com/sigstore/sigstore-go/pkg/tlog" - "github.com/sigstore/sigstore-go/pkg/util" ) const maxAllowedTlogEntries = 32 @@ -41,9 +34,7 @@ const maxAllowedTlogEntries = 32 // // The threshold parameter is the number of unique transparency log entries // that must be verified. -// -// If online is true, the log entry is verified against the Rekor server. -func VerifyArtifactTransparencyLog(entity SignedEntity, trustedMaterial root.TrustedMaterial, logThreshold int, trustIntegratedTime, online bool) ([]time.Time, error) { //nolint:revive +func VerifyArtifactTransparencyLog(entity SignedEntity, trustedMaterial root.TrustedMaterial, logThreshold int, trustIntegratedTime bool) ([]root.Timestamp, error) { //nolint:revive entries, err := entity.TlogEntries() if err != nil { return nil, err @@ -75,7 +66,7 @@ func VerifyArtifactTransparencyLog(entity SignedEntity, trustedMaterial root.Tru return nil, err } - verifiedTimestamps := []time.Time{} + verifiedTimestamps := []root.Timestamp{} logEntriesVerified := 0 for _, entry := range entries { @@ -84,85 +75,41 @@ func VerifyArtifactTransparencyLog(entity SignedEntity, trustedMaterial root.Tru return nil, err } - if !online { - if !entry.HasInclusionPromise() && !entry.HasInclusionProof() { - return nil, fmt.Errorf("entry must contain an inclusion proof and/or promise") - } - if entry.HasInclusionPromise() { - err = tlog.VerifySET(entry, trustedMaterial.RekorLogs()) - if err != nil { - // skip entries the trust root cannot verify - continue - } - if trustIntegratedTime { - verifiedTimestamps = append(verifiedTimestamps, entry.IntegratedTime()) - } - } - if entity.HasInclusionProof() { - keyID := entry.LogKeyID() - hex64Key := hex.EncodeToString([]byte(keyID)) - tlogVerifier, ok := trustedMaterial.RekorLogs()[hex64Key] - if !ok { - // skip entries the trust root cannot verify - continue - } - - verifier, err := getVerifier(tlogVerifier.PublicKey, tlogVerifier.SignatureHashFunc) - if err != nil { - return nil, err - } - - err = tlog.VerifyInclusion(entry, *verifier) - if err != nil { - return nil, err - } - // DO NOT use timestamp with only an inclusion proof, because it is not signed metadata - } - } else { - keyID := entry.LogKeyID() - hex64Key := hex.EncodeToString([]byte(keyID)) - tlogVerifier, ok := trustedMaterial.RekorLogs()[hex64Key] - if !ok { + rekorLogs := trustedMaterial.RekorLogs() + keyID := entry.LogKeyID() + hex64Key := hex.EncodeToString([]byte(keyID)) + tlogVerifier, ok := trustedMaterial.RekorLogs()[hex64Key] + if !ok { + // skip entries the trust root cannot verify + continue + } + + if !entry.HasInclusionPromise() && !entry.HasInclusionProof() { + return nil, fmt.Errorf("entry must contain an inclusion proof and/or promise") + } + if entry.HasInclusionPromise() { + err = tlog.VerifySET(entry, rekorLogs) + if err != nil { // skip entries the trust root cannot verify continue } - - client, err := getRekorClient(tlogVerifier.BaseURL) - if err != nil { - return nil, err + if trustIntegratedTime { + verifiedTimestamps = append(verifiedTimestamps, root.Timestamp{Time: entry.IntegratedTime(), URI: tlogVerifier.BaseURL}) } + } + if entry.HasInclusionProof() { verifier, err := getVerifier(tlogVerifier.PublicKey, tlogVerifier.SignatureHashFunc) if err != nil { return nil, err } - logIndex := entry.LogIndex() - - searchParams := rekorEntries.NewGetLogEntryByIndexParams() - searchParams.LogIndex = logIndex - - resp, err := client.Entries.GetLogEntryByIndex(searchParams) + err = tlog.VerifyInclusion(entry, *verifier) if err != nil { return nil, err } - - if len(resp.Payload) == 0 { - return nil, fmt.Errorf("unable to locate log entry %d", logIndex) - } - - logEntry := resp.Payload - - for _, v := range logEntry { - v := v - err = rekorVerify.VerifyLogEntry(context.TODO(), &v, *verifier) - if err != nil { - return nil, err - } - } - if trustIntegratedTime { - verifiedTimestamps = append(verifiedTimestamps, entry.IntegratedTime()) - } + // DO NOT use timestamp with only an inclusion proof, because it is not signed metadata } + // Ensure entry signature matches signature from bundle if !bytes.Equal(entry.Signature(), entitySignature) { return nil, errors.New("transparency log signature does not match") @@ -199,12 +146,3 @@ func getVerifier(publicKey crypto.PublicKey, hashFunc crypto.Hash) (*signature.V return &verifier, nil } - -func getRekorClient(baseURL string) (*rekorGeneratedClient.Rekor, error) { - client, err := rekorClient.GetRekorClient(baseURL, rekorClient.WithUserAgent(util.ConstructUserAgent())) - if err != nil { - return nil, err - } - - return client, nil -} diff --git a/vendor/github.com/sigstore/sigstore-go/pkg/verify/tsa.go b/vendor/github.com/sigstore/sigstore-go/pkg/verify/tsa.go index 966fad20af..92f8289453 100644 --- a/vendor/github.com/sigstore/sigstore-go/pkg/verify/tsa.go +++ b/vendor/github.com/sigstore/sigstore-go/pkg/verify/tsa.go @@ -16,12 +16,8 @@ package verify import ( "bytes" - "crypto/x509" "errors" "fmt" - "time" - - tsaverification "github.com/sigstore/timestamp-authority/pkg/verification" "github.com/sigstore/sigstore-go/pkg/root" ) @@ -30,7 +26,7 @@ const maxAllowedTimestamps = 32 // VerifyTimestampAuthority verifies that the given entity has been timestamped // by a trusted timestamp authority and that the timestamp is valid. -func VerifyTimestampAuthority(entity SignedEntity, trustedMaterial root.TrustedMaterial) ([]time.Time, error) { //nolint:revive +func VerifyTimestampAuthority(entity SignedEntity, trustedMaterial root.TrustedMaterial) ([]*root.Timestamp, error) { //nolint:revive signedTimestamps, err := entity.Timestamps() if err != nil { return nil, err @@ -57,14 +53,9 @@ func VerifyTimestampAuthority(entity SignedEntity, trustedMaterial root.TrustedM signatureBytes := sigContent.Signature() - verificationContent, err := entity.VerificationContent() - if err != nil { - return nil, err - } - - verifiedTimestamps := []time.Time{} + verifiedTimestamps := []*root.Timestamp{} for _, timestamp := range signedTimestamps { - verifiedSignedTimestamp, err := verifySignedTimestamp(timestamp, signatureBytes, trustedMaterial, verificationContent) + verifiedSignedTimestamp, err := verifySignedTimestamp(timestamp, signatureBytes, trustedMaterial) // Timestamps from unknown source are okay, but don't count as verified if err != nil { @@ -82,7 +73,7 @@ func VerifyTimestampAuthority(entity SignedEntity, trustedMaterial root.TrustedM // // The threshold parameter is the number of unique timestamps that must be // verified. -func VerifyTimestampAuthorityWithThreshold(entity SignedEntity, trustedMaterial root.TrustedMaterial, threshold int) ([]time.Time, error) { //nolint:revive +func VerifyTimestampAuthorityWithThreshold(entity SignedEntity, trustedMaterial root.TrustedMaterial, threshold int) ([]*root.Timestamp, error) { //nolint:revive verifiedTimestamps, err := VerifyTimestampAuthority(entity, trustedMaterial) if err != nil { return nil, err @@ -93,39 +84,16 @@ func VerifyTimestampAuthorityWithThreshold(entity SignedEntity, trustedMaterial return verifiedTimestamps, nil } -func verifySignedTimestamp(signedTimestamp []byte, dsseSignatureBytes []byte, trustedMaterial root.TrustedMaterial, verificationContent VerificationContent) (time.Time, error) { - certAuthorities := trustedMaterial.TimestampingAuthorities() +func verifySignedTimestamp(signedTimestamp []byte, signatureBytes []byte, trustedMaterial root.TrustedMaterial) (*root.Timestamp, error) { + timestampAuthorities := trustedMaterial.TimestampingAuthorities() // Iterate through TSA certificate authorities to find one that verifies - for _, ca := range certAuthorities { - trustedRootVerificationOptions := tsaverification.VerifyOpts{ - Roots: []*x509.Certificate{ca.Root}, - Intermediates: ca.Intermediates, - TSACertificate: ca.Leaf, - } - - // Ensure timestamp responses are from trusted sources - timestamp, err := tsaverification.VerifyTimestampResponse(signedTimestamp, bytes.NewReader(dsseSignatureBytes), trustedRootVerificationOptions) - if err != nil { - continue + for _, tsa := range timestampAuthorities { + ts, err := tsa.Verify(signedTimestamp, signatureBytes) + if err == nil { + return ts, nil } - - if !ca.ValidityPeriodStart.IsZero() && timestamp.Time.Before(ca.ValidityPeriodStart) { - continue - } - if !ca.ValidityPeriodEnd.IsZero() && timestamp.Time.After(ca.ValidityPeriodEnd) { - continue - } - - // Check tlog entry time against bundle certificates - // TODO: technically no longer needed since we check the cert validity period in the main Verify loop - if !verificationContent.ValidAtTime(timestamp.Time, trustedMaterial) { - continue - } - - // All above verification successful, so return nil - return timestamp.Time, nil } - return time.Time{}, errors.New("unable to verify signed timestamps") + return nil, errors.New("unable to verify signed timestamps") } diff --git a/vendor/github.com/sigstore/sigstore/pkg/signature/algorithm_registry.go b/vendor/github.com/sigstore/sigstore/pkg/signature/algorithm_registry.go new file mode 100644 index 0000000000..0612d8f7a2 --- /dev/null +++ b/vendor/github.com/sigstore/sigstore/pkg/signature/algorithm_registry.go @@ -0,0 +1,206 @@ +// +// Copyright 2024 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package signature + +import ( + "crypto" + "crypto/ecdsa" + "crypto/ed25519" + "crypto/elliptic" + "crypto/rsa" + "fmt" + + v1 "github.com/sigstore/protobuf-specs/gen/pb-go/common/v1" +) + +// PublicKeyType represents the public key algorithm for a given signature algorithm. +type PublicKeyType uint + +const ( + // RSA public key + RSA PublicKeyType = iota + // ECDSA public key + ECDSA + // ED25519 public key + ED25519 +) + +// RSAKeySize represents the size of an RSA public key in bits. +type RSAKeySize int + +type algorithmDetails struct { + // knownAlgorithm is the signature algorithm that the following details refer to. + knownAlgorithm v1.PublicKeyDetails + + // keyType is the public key algorithm being used. + keyType PublicKeyType + + // hashType is the hash algorithm being used. + hashType crypto.Hash + + // extraKeyParams contains any extra parameters required to check a given public key against this entry. + // + // The underlying type of these parameters is dependent on the keyType. + // For example, ECDSA algorithms will store an elliptic curve here whereas, RSA keys will store the key size. + // Algorithms that don't require any extra parameters leave this set to nil. + extraKeyParams interface{} + + // flagValue is a string representation of the signature algorithm that follows the naming conventions of CLI + // arguments that are used for Sigstore services. + flagValue string +} + +func (a algorithmDetails) GetRSAKeySize() (RSAKeySize, error) { + if a.keyType != RSA { + return 0, fmt.Errorf("unable to retrieve RSA key size for key type: %T", a.keyType) + } + rsaKeySize, ok := a.extraKeyParams.(RSAKeySize) + if !ok { + // This should be unreachable. + return 0, fmt.Errorf("unable to retrieve key size for RSA, malformed algorithm details?: %T", a.keyType) + } + return rsaKeySize, nil +} + +func (a algorithmDetails) GetECDSACurve() (*elliptic.Curve, error) { + if a.keyType != ECDSA { + return nil, fmt.Errorf("unable to retrieve ECDSA curve for key type: %T", a.keyType) + } + ecdsaCurve, ok := a.extraKeyParams.(elliptic.Curve) + if !ok { + // This should be unreachable. + return nil, fmt.Errorf("unable to retrieve curve for ECDSA, malformed algorithm details?: %T", a.keyType) + } + return &ecdsaCurve, nil +} + +func (a algorithmDetails) checkKey(pubKey crypto.PublicKey) (bool, error) { + switch a.keyType { + case RSA: + rsaKey, ok := pubKey.(*rsa.PublicKey) + if !ok { + return false, nil + } + keySize, err := a.GetRSAKeySize() + if err != nil { + return false, err + } + return rsaKey.Size()*8 == int(keySize), nil + case ECDSA: + ecdsaKey, ok := pubKey.(*ecdsa.PublicKey) + if !ok { + return false, nil + } + curve, err := a.GetECDSACurve() + if err != nil { + return false, err + } + return ecdsaKey.Curve == *curve, nil + case ED25519: + _, ok := pubKey.(ed25519.PublicKey) + return ok, nil + } + return false, fmt.Errorf("unrecognized key type: %T", a.keyType) +} + +func (a algorithmDetails) checkHash(hashType crypto.Hash) bool { + return a.hashType == hashType +} + +// Note that deprecated options in PublicKeyDetails are not included in this +// list, including PKCS1v1.5 encoded RSA. Refer to the v1.PublicKeyDetails enum +// for more details. +var supportedAlgorithms = []algorithmDetails{ + {v1.PublicKeyDetails_PKIX_RSA_PKCS1V15_2048_SHA256, RSA, crypto.SHA256, RSAKeySize(2048), "rsa-sign-pkcs1-2048-sha256"}, + {v1.PublicKeyDetails_PKIX_RSA_PKCS1V15_3072_SHA256, RSA, crypto.SHA256, RSAKeySize(3072), "rsa-sign-pkcs1-3072-sha256"}, + {v1.PublicKeyDetails_PKIX_RSA_PKCS1V15_4096_SHA256, RSA, crypto.SHA256, RSAKeySize(4096), "rsa-sign-pkcs1-4096-sha256"}, + {v1.PublicKeyDetails_PKIX_RSA_PSS_2048_SHA256, RSA, crypto.SHA256, RSAKeySize(2048), "rsa-sign-pss-2048-sha256"}, + {v1.PublicKeyDetails_PKIX_RSA_PSS_3072_SHA256, RSA, crypto.SHA256, RSAKeySize(3072), "rsa-sign-pss-3072-sha256"}, + {v1.PublicKeyDetails_PKIX_RSA_PSS_4096_SHA256, RSA, crypto.SHA256, RSAKeySize(4096), "rsa-sign-pss-4092-sha256"}, + {v1.PublicKeyDetails_PKIX_ECDSA_P256_SHA_256, ECDSA, crypto.SHA256, elliptic.P256(), "ecdsa-sha2-256-nistp256"}, + {v1.PublicKeyDetails_PKIX_ECDSA_P384_SHA_384, ECDSA, crypto.SHA384, elliptic.P384(), "ecdsa-sha2-384-nistp384"}, + {v1.PublicKeyDetails_PKIX_ECDSA_P521_SHA_512, ECDSA, crypto.SHA512, elliptic.P521(), "ecdsa-sha2-512-nistp521"}, + {v1.PublicKeyDetails_PKIX_ED25519, ED25519, crypto.Hash(0), nil, "ed25519"}, + {v1.PublicKeyDetails_PKIX_ED25519_PH, ED25519, crypto.SHA512, nil, "ed25519-ph"}, +} + +// AlgorithmRegistryConfig represents a set of permitted algorithms for a given Sigstore service or component. +// +// Individual services may wish to restrict what algorithms are allowed to a subset of what is covered in the algorithm +// registry (represented by v1.PublicKeyDetails). +type AlgorithmRegistryConfig struct { + permittedAlgorithms []algorithmDetails +} + +// getAlgorithmDetails retrieves a set of details for a given v1.PublicKeyDetails flag that allows users to +// introspect the public key algorithm, hash algorithm and more. +func getAlgorithmDetails(knownSignatureAlgorithm v1.PublicKeyDetails) (*algorithmDetails, error) { + for _, detail := range supportedAlgorithms { + if detail.knownAlgorithm == knownSignatureAlgorithm { + return &detail, nil + } + } + return nil, fmt.Errorf("could not find algorithm details for known signature algorithm: %s", knownSignatureAlgorithm) +} + +// NewAlgorithmRegistryConfig creates a new AlgorithmRegistryConfig for a set of permitted signature algorithms. +func NewAlgorithmRegistryConfig(algorithmConfig []v1.PublicKeyDetails) (*AlgorithmRegistryConfig, error) { + permittedAlgorithms := make([]algorithmDetails, 0, len(supportedAlgorithms)) + for _, algorithm := range algorithmConfig { + a, err := getAlgorithmDetails(algorithm) + if err != nil { + return nil, err + } + permittedAlgorithms = append(permittedAlgorithms, *a) + } + return &AlgorithmRegistryConfig{permittedAlgorithms: permittedAlgorithms}, nil +} + +// IsAlgorithmPermitted checks whether a given public key/hash algorithm combination is permitted by a registry config. +func (registryConfig AlgorithmRegistryConfig) IsAlgorithmPermitted(key crypto.PublicKey, hash crypto.Hash) (bool, error) { + for _, algorithm := range registryConfig.permittedAlgorithms { + keyMatch, err := algorithm.checkKey(key) + if err != nil { + return false, err + } + if keyMatch && algorithm.checkHash(hash) { + return true, nil + } + } + return false, nil +} + +// FormatSignatureAlgorithmFlag formats a v1.PublicKeyDetails to a string that conforms to the naming conventions +// of CLI arguments that are used for Sigstore services. +func FormatSignatureAlgorithmFlag(algorithm v1.PublicKeyDetails) (string, error) { + for _, a := range supportedAlgorithms { + if a.knownAlgorithm == algorithm { + return a.flagValue, nil + } + } + return "", fmt.Errorf("could not find matching flag for signature algorithm: %s", algorithm) +} + +// ParseSignatureAlgorithmFlag parses a string produced by FormatSignatureAlgorithmFlag and returns the corresponding +// v1.PublicKeyDetails value. +func ParseSignatureAlgorithmFlag(flag string) (v1.PublicKeyDetails, error) { + for _, a := range supportedAlgorithms { + if a.flagValue == flag { + return a.knownAlgorithm, nil + } + } + return v1.PublicKeyDetails_PUBLIC_KEY_DETAILS_UNSPECIFIED, fmt.Errorf("could not find matching signature algorithm for flag: %s", flag) +} diff --git a/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/README.md b/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/README.md new file mode 100644 index 0000000000..17c2a3e8bd --- /dev/null +++ b/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/README.md @@ -0,0 +1,109 @@ +# CLI Plugin + +This is a package and module for using custom KMS plugins as separate executables. +It is intended to be used by cosign, but you may use this in your own programs that import sigstore. + +## Design + +We follow [kubectl's style](https://kubernetes.io/docs/tasks/extend-kubectl/kubectl-plugins/#writing-kubectl-plugins) of plugins. Any language that can create CLI programs can be used to make a plugin. + +### Usage + +Plugins are separate programs on your system's PATH, named in the scheme `sigstore-kms-[name]`, like `sigstore-kms-my-hsm`. They can be invoked with cosign like `cosign [sub-command] --key "my-hsm://my-key-id" ... +` + +### Protocol + +The main program will invoke the program with these specifications: + +* stdin + * Data to be signed or verified. +* arg 1 + * A number identifying the version of this protocol. + * In the future we may change this protocol, either the encoding or the formatting of argument and return values. + Protocol changes will result in a major-version bump for the library. + When changing the protocol, new versions of sigstore will not maintain backwards compatibility with + previous protocol versions. If a plugin author wishes, they may branch their plugin program’s behaviour + to be compatible with multiple versions of the protocol, or multiple major versions of sigstore and cosign. +* arg 2 + * JSON of initialization options and method arguments. +* stdout + * JSON of method return values. + +See [./common/interface.go](./common/interface.go) and [./common/interface_test.go](./common/interface_test.go) for the full JSON schema. + +The plugin program must first exit before sigstore begins parsing responses. + +#### Error Handling + +The plugin program’s stderr will be redirected to the main program’s stderr. This way, the main program may also see the plugin program’s debug messages. + +Plugin authors may return errors with `PluginResp.ErrorMessage`, but the plugin's exit status will be ignored. + +### Implementation + +Plugin authors must implement the `kms.SignerVerifier` interface methods in their chosen language. Each method will invoke your program once, and the response will be parsed from stdout. + +`PluginClient.CryptoSigner()` will return object that is a wrapper around `PluginClient`, so plugin authors need not do a full implementation of `SignerVerifier()`. + +Exit status is ignored. Your program's stderr will be redirected to the main program, and errors you wish to return must be serialized in `PluginResp.ErrorMessage` in stdout. + +For authors using Go, we vend some helper functions to help you get started. See [handler](./handler/README.md) + +## Development + +Changes to the `SignerVerifier` interface are to be handled in [./signer.go's](./signer.go) `PluginClient` and [./handler/dispatch.go's](./handler/dispatch.go) `Dispatch()`. + +### Adding New Methods or Method Options + +Adding new methods or options are *not* necessarily breaking changes to the schemas, so we may consider these to be minor version increments, both to the protocol version and the sigstore version. + +### Removing Methods + +Removing methods, or altering their signatures will break the schemas and will require major version increments, both to the protocol version and the sigstore version. + +### Example Plugin + +We have an example plugin in [test/cliplugin/localkms](../../../../test/cliplugin/localkms). + +1. Compile cosign and the plugin + + ```shell + go build -C cosign/cmd/cosign -o `pwd`/cosign-cli + go build -C sigstore/test/cliplugin/localkms -o `pwd`/sigstore-kms-localkms + ``` + +2. Sign some data + + With our example, you need to first create the key. + + ```shell + export PATH="$PATH:`pwd`" + cosign-cli generate-key-pair --kms localkms://`pwd`/key.pem + cat cosign.pub + ``` + + Sign some data. + + ```shell + export PATH="$PATH:`pwd`" + echo "my-data" > blob.txt + cosign-cli sign-blob --tlog-upload=false --key localkms://`pwd`/key.pem blob.txt + ``` + +### Testing + +Unit tests against an example plugin program are in [./signer_program_test.go](./signer_program_test.go). +Compile the plugin and invoke unit tests with + +```shell +make test-signer-program +``` + +Or invoke the unit tests with your own pre-compiled plugin program like + + +```shell +export PATH=$PATH:[folder containing plugin program] +go test -C ./pkg/signature/kms/cliplugin -v -tags=signer_program ./... -key-resource-id [my-kms]://[my key ref] +``` diff --git a/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/client.go b/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/client.go new file mode 100644 index 0000000000..213a926cb3 --- /dev/null +++ b/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/client.go @@ -0,0 +1,76 @@ +// +// Copyright 2024 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package cliplugin implements the plugin functionality. +package cliplugin + +import ( + "context" + "crypto" + "errors" + "fmt" + "os/exec" + "strings" + + "github.com/sigstore/sigstore/pkg/signature" + "github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/common" + "github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/encoding" + "github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/internal/signerverifier" +) + +const ( + // PluginBinaryPrefix is the prefix for all plugin binaries. e.g., sigstore-kms-my-hsm. + PluginBinaryPrefix = "sigstore-kms-" +) + +// ErrorInputKeyResourceID indicates a problem parsing the key resource id. +var ErrorInputKeyResourceID = errors.New("parsing input key resource id") + +// LoadSignerVerifier creates a PluginClient with these InitOptions. +// If the plugin executable does not exist, then it returns exec.ErrNotFound. +func LoadSignerVerifier(ctx context.Context, inputKeyResourceID string, hashFunc crypto.Hash, opts ...signature.RPCOption) (signerverifier.SignerVerifier, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + executable, keyResourceID, err := getPluginExecutableAndKeyResourceID(inputKeyResourceID) + if err != nil { + return nil, err + } + if _, err := exec.LookPath(executable); err != nil { + return nil, err + } + initOptions := &common.InitOptions{ + ProtocolVersion: common.ProtocolVersion, + KeyResourceID: keyResourceID, + HashFunc: hashFunc, + RPCOptions: encoding.PackRPCOptions(opts), + } + if deadline, ok := ctx.Deadline(); ok { + initOptions.CtxDeadline = &deadline + } + pluginClient := newPluginClient(executable, initOptions, makeCmd) + return pluginClient, nil +} + +// getPluginExecutableAndKeyResourceID parses the inputKeyResourceID into the plugin executable and the actual keyResourceID. +func getPluginExecutableAndKeyResourceID(inputKeyResourceID string) (string, string, error) { + parts := strings.SplitN(inputKeyResourceID, "://", 2) + if len(parts) != 2 { + return "", "", fmt.Errorf("%w: expected format: [plugin name]://[key ref], got: %s", ErrorInputKeyResourceID, inputKeyResourceID) + } + pluginName, keyResourceID := parts[0], parts[1] + executable := PluginBinaryPrefix + pluginName + return executable, keyResourceID, nil +} diff --git a/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/cmd.go b/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/cmd.go new file mode 100644 index 0000000000..f73c14f9e1 --- /dev/null +++ b/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/cmd.go @@ -0,0 +1,45 @@ +// +// Copyright 2025 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package cliplugin implements the plugin functionality. +package cliplugin + +import ( + "context" + "io" + "os/exec" +) + +// cmd is an interface for os/exec.Cmd. +type cmd interface { + Output() ([]byte, error) +} + +// makeCmdFunc is a type for a function that can create a cmd. +type makeCmdFunc func(ctx context.Context, stdin io.Reader, stderr io.Writer, name string, args ...string) cmd + +// makeCmd is an implementation of makeCmdFunc. +func makeCmd(ctx context.Context, stdin io.Reader, stderr io.Writer, name string, args ...string) cmd { + cmd := exec.CommandContext(ctx, name, args...) + cmd.Stdin = stdin + cmd.Stderr = stderr + return cmd +} + +// cmdExitError is an interface for os/exec.ExitError. +type cmdExitError interface { + Error() string + ExitCode() int +} diff --git a/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/common/interface.go b/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/common/interface.go new file mode 100644 index 0000000000..ea9487db19 --- /dev/null +++ b/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/common/interface.go @@ -0,0 +1,147 @@ +// +// Copyright 2024 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package common defines the JSON schema for plugin arguments and return values. +package common + +import ( + "crypto" + "time" +) + +const ( + // ProtocolVersion is the version of the schema and communication protocol for the plugin system. + // Breaking changes to the PluginClient and this schema necessarily mean major version bumps of + // this ProtocolVersion and the sigstore version. + // Plugin authors may choose to be backwards compatible with older versions. + ProtocolVersion = "v1" + // DefaultAlgorithmMethodName is the MethodName for DefaultAlgorithsm(). + DefaultAlgorithmMethodName = "defaultAlgorithm" + // SupportedAlgorithmsMethodName is the MethodName for SupportedAlgorithms(). + SupportedAlgorithmsMethodName = "supportedAlgorithms" + // CreateKeyMethodName is the MethodName for CreateKey(). + CreateKeyMethodName = "createKey" + // PublicKeyMethodName is the MethodName for PublicKey(). + PublicKeyMethodName = "publicKey" + // SignMessageMethodName is the MethodName for SignMessage(). + SignMessageMethodName = "signMessage" + // VerifySignatureMethodName is the MethodName for VerifySignature(). + VerifySignatureMethodName = "verifySignature" + // CryptoSigner is not to be added to the protocol. + // PluginClient.CryptoSigner() will instead return a wrapper around the plugin. +) + +// PluginArgs contains all the initialization and method arguments to be sent to the plugin as a CLI argument. +type PluginArgs struct { + InitOptions *InitOptions `json:"initOptions"` + *MethodArgs +} + +// InitOptions contains the initial arguments when calling cliplugin.LoadSignerVerifier(). +type InitOptions struct { + // CtxDeadline serializes to RFC 3339. See https://pkg.go.dev/time@go1.23.5#Time.MarshalJSON. e.g, 2025-04-01T02:47:00Z. + CtxDeadline *time.Time `json:"ctxDeadline,omitempty"` + ProtocolVersion string `json:"protocolVersion"` + KeyResourceID string `json:"keyResourceID"` + // HashFunc will serialize to ints according to https://pkg.go.dev/crypto@go1.23.5#Hash. e.g., crypto.SHA256 serializes to 5. + HashFunc crypto.Hash `json:"hashFunc"` + RPCOptions *RPCOptions `json:"rpcOptions"` +} + +// MethodArgs contains the method arguments. MethodName must be specified, +// while any one of the other fields describing method arguments must also be specified. +// Arguments that are io.Readers, like `message` in `SignMessage()` will be sent over stdin. +type MethodArgs struct { + // MethodName specifies which method is intended to be called. + MethodName string `json:"methodName"` + DefaultAlgorithm *DefaultAlgorithmArgs `json:"defaultAlgorithm,omitempty"` + SupportedAlgorithms *SupportedAlgorithmsArgs `json:"supportedAlgorithms,omitempty"` + CreateKey *CreateKeyArgs `json:"createKey,omitempty"` + PublicKey *PublicKeyArgs `json:"publicKey,omitempty"` + SignMessage *SignMessageArgs `json:"signMessage,omitempty"` + VerifySignature *VerifySignatureArgs `json:"verifySignature,omitempty"` +} + +// PluginResp contains the serialized plugin method return values. +type PluginResp struct { + ErrorMessage string `json:"errorMessage,omitempty"` + DefaultAlgorithm *DefaultAlgorithmResp `json:"defaultAlgorithm,omitempty"` + SupportedAlgorithms *SupportedAlgorithmsResp `json:"supportedAlgorithms,omitempty"` + CreateKey *CreateKeyResp `json:"createKey,omitempty"` + PublicKey *PublicKeyResp `json:"publicKey,omitempty"` + SignMessage *SignMessageResp `json:"signMessage,omitempty"` + VerifySignature *VerifySignatureResp `json:"verifySignature,omitempty"` +} + +// DefaultAlgorithmArgs contains the serialized arguments for `DefaultAlgorithm()`. +type DefaultAlgorithmArgs struct{} + +// DefaultAlgorithmResp contains the serialized response for `DefaultAlgorithm()`. +type DefaultAlgorithmResp struct { + DefaultAlgorithm string `json:"defaultAlgorithm"` +} + +// SupportedAlgorithmsArgs contains the serialized arguments for `SupportedAlgorithms()`. +type SupportedAlgorithmsArgs struct{} + +// SupportedAlgorithmsResp contains the serialized response for `SupportedAlgorithms()`. +type SupportedAlgorithmsResp struct { + SupportedAlgorithms []string `json:"supportedAlgorithms"` +} + +// CreateKeyArgs contains the serialized arguments for `CreateKeyArgs()`. +type CreateKeyArgs struct { + // CtxDeadline serializes to RFC 3339. See https://pkg.go.dev/time@go1.23.5#Time.MarshalJSON. e.g, 2025-04-01T02:47:00Z. + CtxDeadline *time.Time `json:"ctxDeadline,omitempty"` + Algorithm string `json:"algorithm"` +} + +// CreateKeyResp contains the serialized response for `CreateKeyResp()`. +type CreateKeyResp struct { + // PublicKeyPEM is a base64 encoding of the Public Key PEM bytes. e.g, []byte("mypem") serializes to "bXlwZW0=". + PublicKeyPEM []byte `json:"publicKeyPEM"` +} + +// PublicKeyArgs contains the serialized response for `PublicKey()`. +type PublicKeyArgs struct { + PublicKeyOptions *PublicKeyOptions `json:"publicKeyOptions"` +} + +// PublicKeyResp contains the serialized response for `PublicKey()`. +type PublicKeyResp struct { + // PublicKeyPEM is a base64 encoding of the Public Key PEM bytes. e.g, []byte("mypem") serializes to "bXlwZW0=". + PublicKeyPEM []byte `json:"publicKeyPEM"` +} + +// SignMessageArgs contains the serialized arguments for `SignMessage()`. +type SignMessageArgs struct { + SignOptions *SignOptions `json:"signOptions"` +} + +// SignMessageResp contains the serialized response for `SignMessage()`. +type SignMessageResp struct { + // Signature is a base64 encoding of the signature bytes. e.g, []byte("any-signature") serializes to "W55LXNpZ25hdHVyZQ==". + Signature []byte `json:"signature"` +} + +// VerifySignatureArgs contains the serialized arguments for `VerifySignature()`. +type VerifySignatureArgs struct { + // Signature is a base64 encoding of the signature bytes. e.g, []byte("any-signature") serializes to "W55LXNpZ25hdHVyZQ==". + Signature []byte `json:"signature"` + VerifyOptions *VerifyOptions `json:"verifyOptions"` +} + +// VerifySignatureResp contains the serialized response for `VerifySignature()`. +type VerifySignatureResp struct{} diff --git a/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/common/options.go b/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/common/options.go new file mode 100644 index 0000000000..a875282489 --- /dev/null +++ b/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/common/options.go @@ -0,0 +1,57 @@ +// +// Copyright 2024 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package common defines the JSON schema for plugin arguments and return values. +package common + +import ( + "crypto" + "time" +) + +// PublicKeyOptions contains the values for signature.PublicKeyOptions. +type PublicKeyOptions struct { + RPCOptions RPCOptions `json:"rpcOptions"` +} + +// SignOptions contains the values for signature.SignOption. +type SignOptions struct { + RPCOptions RPCOptions `json:"rpcOptions"` + MessageOptions MessageOptions `json:"messageOptions"` +} + +// VerifyOptions contains the values for signature.VerifyOption. +type VerifyOptions struct { + RPCOptions RPCOptions `json:"rpcOptions"` + MessageOptions MessageOptions `json:"messageOptions"` +} + +// RPCOptions contains the values for signature.RPCOption. +// We do not use RPCOptions.RPCAuth to avoid sending secrets over CLI to the plugin program. +// The plugin program should instead read secrets with env variables. +type RPCOptions struct { + // CtxDeadline serializes to RFC 3339. See https://pkg.go.dev/time@go1.23.5#Time.MarshalJSON. e.g, 2025-04-01T02:47:00Z. + CtxDeadline *time.Time `json:"ctxDeadline,omitempty"` + KeyVersion *string `json:"keyVersion,omitempty"` + RemoteVerification *bool `json:"remoteVerification,omitempty"` +} + +// MessageOptions contains the values for signature.MessageOption. +type MessageOptions struct { + // Digest is a base64 encoding of the digest bytes. e.g, []byte("anyDigest") serializes to "YW55RGlnZXN0". + Digest *[]byte `json:"digest,omitempty"` + // HashFunc will serialize to ints according to https://pkg.go.dev/crypto@go1.23.5#Hash. e.g., crypto.SHA256 serializes to 5. + HashFunc *crypto.Hash `json:"hashFunc,omitempty"` +} diff --git a/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/encoding/options.go b/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/encoding/options.go new file mode 100644 index 0000000000..09e4671ad1 --- /dev/null +++ b/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/encoding/options.go @@ -0,0 +1,197 @@ +// +// Copyright 2024 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package encoding has helper functions for encoding and decoding some method arguments and return values. +package encoding + +// We have some type assertions that seem like they may panic, but this is just to satisfy +// golanci-lint's forcetypeassert linter. If they were to ever fail, unit tests would also fail. +// We know the asserted types are valid because otherwise we would have compiler failures. + +import ( + "context" + "crypto" + "time" + + "github.com/sigstore/sigstore/pkg/signature" + "github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/common" + "github.com/sigstore/sigstore/pkg/signature/options" +) + +// PackRPCOptions extracts properties of all of opts into struct ready for serializing. +func PackRPCOptions(opts []signature.RPCOption) *common.RPCOptions { + ctx := context.Background() + var keyVersion string + var remoteVerification bool + for _, opt := range opts { + opt.ApplyContext(&ctx) + opt.ApplyKeyVersion(&keyVersion) + opt.ApplyRemoteVerification(&remoteVerification) + } + var ctxDeadline *time.Time + if deadline, ok := ctx.Deadline(); ok { + ctxDeadline = &deadline + } + return &common.RPCOptions{ + CtxDeadline: ctxDeadline, + KeyVersion: &keyVersion, + RemoteVerification: &remoteVerification, + } +} + +// UnpackRPCOptions builds the []signature.RPCOption from common.RPCOptions. +func UnpackRPCOptions(commonOpts *common.RPCOptions) []signature.RPCOption { + opts := []signature.RPCOption{} + if commonOpts.CtxDeadline != nil { + // no need fot this package to cancel the context early, + // and users may still check if the deadline is exceeded with ctx.Err(). + ctx, _ := context.WithDeadline(context.Background(), *commonOpts.CtxDeadline) //nolint:govet + opts = append(opts, options.WithContext(ctx)) + } + if commonOpts.KeyVersion != nil { + opts = append(opts, options.WithKeyVersion(*commonOpts.KeyVersion)) + } + if commonOpts.RemoteVerification != nil { + opts = append(opts, options.WithRemoteVerification(*commonOpts.RemoteVerification)) + } + return opts +} + +// PackMessageOptions extracts properties of all of opts into struct ready for serializing. +func PackMessageOptions(opts []signature.MessageOption) *common.MessageOptions { + var digest []byte + var signerOpts crypto.SignerOpts + for _, opt := range opts { + opt.ApplyDigest(&digest) + opt.ApplyCryptoSignerOpts(&signerOpts) + } + var hashFunc *crypto.Hash + if signerOpts != nil { + hf := signerOpts.HashFunc() + hashFunc = &hf + } + return &common.MessageOptions{ + Digest: &digest, + HashFunc: hashFunc, + } +} + +// PackPublicKeyOptions extracts properties of all of opts into struct ready for serializing. +func PackPublicKeyOptions(opts []signature.PublicKeyOption) *common.PublicKeyOptions { + rpcOpts := []signature.RPCOption{} + for _, opt := range opts { + rpcOpts = append(rpcOpts, opt) + } + return &common.PublicKeyOptions{ + RPCOptions: *PackRPCOptions(rpcOpts), + } +} + +// UnpackPublicKeyOptions builds the []signature.PublicKeyOption from common.PublicKeyOptions. +func UnpackPublicKeyOptions(commonOpts *common.PublicKeyOptions) []signature.PublicKeyOption { + opts := []signature.PublicKeyOption{} + for _, opt := range UnpackRPCOptions(&commonOpts.RPCOptions) { + opt, ok := opt.(signature.PublicKeyOption) + if !ok { + panic("cannot assert as PublicKeyOption") + } + opts = append(opts, opt) + } + return opts +} + +// UnpackMessageOptions builds the []signature.MessageOption from common.MessageOptions. +func UnpackMessageOptions(commonOpts *common.MessageOptions) []signature.MessageOption { + opts := []signature.MessageOption{} + if commonOpts.Digest != nil { + opts = append(opts, options.WithDigest(*commonOpts.Digest)) + } + if commonOpts.HashFunc != nil { + opts = append(opts, options.WithCryptoSignerOpts(*commonOpts.HashFunc)) + } + return opts +} + +// PackSignOptions extracts properties of all of opts into struct ready for serializing, +func PackSignOptions(opts []signature.SignOption) *common.SignOptions { + rpcOpts := []signature.RPCOption{} + for _, opt := range opts { + rpcOpts = append(rpcOpts, opt) + } + messageOpts := []signature.MessageOption{} + for _, opt := range opts { + messageOpts = append(messageOpts, opt) + } + return &common.SignOptions{ + RPCOptions: *PackRPCOptions(rpcOpts), + MessageOptions: *PackMessageOptions(messageOpts), + } +} + +// UnpackSignOptions builds the []]signature.SignOption from common.SignOptions. +func UnpackSignOptions(commonOpts *common.SignOptions) []signature.SignOption { + opts := []signature.SignOption{} + for _, opt := range UnpackRPCOptions(&commonOpts.RPCOptions) { + opt, ok := opt.(signature.SignOption) + if !ok { + panic("cannot assert as SignOption") + } + opts = append(opts, opt) + } + for _, opt := range UnpackMessageOptions(&commonOpts.MessageOptions) { + opt, ok := opt.(signature.SignOption) + if !ok { + panic("cannot assert as SignOption") + } + opts = append(opts, opt) + } + return opts +} + +// PackVerifyOptions extracts properties of all of opts into struct ready for serializing, +func PackVerifyOptions(opts []signature.VerifyOption) *common.VerifyOptions { + rpcOpts := []signature.RPCOption{} + for _, opt := range opts { + rpcOpts = append(rpcOpts, opt) + } + messageOpts := []signature.MessageOption{} + for _, opt := range opts { + messageOpts = append(messageOpts, opt) + } + return &common.VerifyOptions{ + RPCOptions: *PackRPCOptions(rpcOpts), + MessageOptions: *PackMessageOptions(messageOpts), + } +} + +// UnpackVerifyOptions builds the []]signature.VerifyOption from common.VerifyOptions. +func UnpackVerifyOptions(commonOpts *common.VerifyOptions) []signature.VerifyOption { + opts := []signature.VerifyOption{} + for _, opt := range UnpackRPCOptions(&commonOpts.RPCOptions) { + opt, ok := opt.(signature.VerifyOption) + if !ok { + panic("cannot assert as VerifyOption") + } + opts = append(opts, opt) + } + for _, opt := range UnpackMessageOptions(&commonOpts.MessageOptions) { + opt, ok := opt.(signature.VerifyOption) + if !ok { + panic("cannot assert as VerifyOption") + } + opts = append(opts, opt) + } + return opts +} diff --git a/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/internal/signerverifier/interface.go b/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/internal/signerverifier/interface.go new file mode 100644 index 0000000000..db17180d5a --- /dev/null +++ b/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/internal/signerverifier/interface.go @@ -0,0 +1,35 @@ +// +// Copyright 2025 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package signerverifier contains interface for to be implemented by KMSs. +package signerverifier + +import ( + "context" + "crypto" + + "github.com/sigstore/sigstore/pkg/signature" +) + +// SignerVerifier creates and verifies digital signatures over a message using a KMS service +// The contents must be kept in sync with kms.SignerVerifier, to continue satisfying that interface. +// We don't directly embed kms.SignerVerfifier because then we would have an import cycle. +type SignerVerifier interface { + signature.SignerVerifier + CreateKey(ctx context.Context, algorithm string) (crypto.PublicKey, error) + CryptoSigner(ctx context.Context, errFunc func(error)) (crypto.Signer, crypto.SignerOpts, error) + SupportedAlgorithms() []string + DefaultAlgorithm() string +} diff --git a/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/signer.go b/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/signer.go new file mode 100644 index 0000000000..ef4bb4fe5e --- /dev/null +++ b/vendor/github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/signer.go @@ -0,0 +1,246 @@ +// +// Copyright 2024 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package cliplugin implements the plugin functionality. +package cliplugin + +import ( + "bytes" + "context" + "crypto" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "os" + + "github.com/sigstore/sigstore/pkg/cryptoutils" + "github.com/sigstore/sigstore/pkg/signature" + "github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/common" + "github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/encoding" + "github.com/sigstore/sigstore/pkg/signature/options" +) + +var ( + // ErrorExecutingPlugin indicates a problem executing the plugin program. + ErrorExecutingPlugin = errors.New("error executing plugin program") + // ErrorResponseParse indicates a problem parsing the plugin response. + ErrorResponseParse = errors.New("parsing plugin response") + // ErrorPluginReturnError indicates that the plugin returned a praseable error. + ErrorPluginReturnError = errors.New("plugin returned error") +) + +// PluginClient implements signerverifier.SignerVerifier with calls to our plugin program. +type PluginClient struct { + executable string + initOptions common.InitOptions + makeCmdFunc makeCmdFunc +} + +// newPluginClient creates a new PluginClient. +func newPluginClient(executable string, initOptions *common.InitOptions, makeCmd makeCmdFunc) *PluginClient { + pluginClient := &PluginClient{ + executable: executable, + initOptions: *initOptions, + makeCmdFunc: makeCmd, + } + return pluginClient +} + +// invokePlugin invokes the plugin program and parses its response. +func (c PluginClient) invokePlugin(ctx context.Context, stdin io.Reader, methodArgs *common.MethodArgs) (*common.PluginResp, error) { + pluginArgs := &common.PluginArgs{ + InitOptions: &c.initOptions, + MethodArgs: methodArgs, + } + argsEnc, err := json.Marshal(pluginArgs) + if err != nil { + return nil, err + } + cmd := c.makeCmdFunc(ctx, stdin, os.Stderr, c.executable, common.ProtocolVersion, string(argsEnc)) + // We won't look at the program's non-zero exit code, but we will respect any other + // error, and cases when exec.ExitError.ExitCode() is 0 or -1: + // * (0) the program finished successfully or + // * (-1) there was some other problem not due to the program itself. + // The only debugging is to either parse the the returned error in stdout, + // or for the user to examine the sterr logs. + // See https://pkg.go.dev/os#ProcessState.ExitCode. + stdout, err := cmd.Output() + var exitError cmdExitError + if err != nil && (!errors.As(err, &exitError) || exitError.ExitCode() < 1) { + return nil, fmt.Errorf("%w: %w", ErrorExecutingPlugin, err) + } + var resp common.PluginResp + if unmarshallErr := json.Unmarshal(stdout, &resp); unmarshallErr != nil { + return nil, fmt.Errorf("%w: %w", ErrorResponseParse, unmarshallErr) + } + if resp.ErrorMessage != "" { + return nil, fmt.Errorf("%w: %s", ErrorPluginReturnError, resp.ErrorMessage) + } + return &resp, nil +} + +// DefaultAlgorithm calls and returns the plugin's implementation of DefaultAlgorithm(). +func (c PluginClient) DefaultAlgorithm() string { + args := &common.MethodArgs{ + MethodName: common.DefaultAlgorithmMethodName, + DefaultAlgorithm: &common.DefaultAlgorithmArgs{}, + } + resp, err := c.invokePlugin(context.Background(), nil, args) + if err != nil { + log.Fatal(err) + } + return resp.DefaultAlgorithm.DefaultAlgorithm +} + +// SupportedAlgorithms calls and returns the plugin's implementation of SupportedAlgorithms(). +func (c PluginClient) SupportedAlgorithms() []string { + args := &common.MethodArgs{ + MethodName: common.SupportedAlgorithmsMethodName, + SupportedAlgorithms: &common.SupportedAlgorithmsArgs{}, + } + resp, err := c.invokePlugin(context.Background(), nil, args) + if err != nil { + log.Fatal(err) + } + return resp.SupportedAlgorithms.SupportedAlgorithms +} + +// CreateKey calls and returns the plugin's implementation of CreateKey(). +func (c PluginClient) CreateKey(ctx context.Context, algorithm string) (crypto.PublicKey, error) { + args := &common.MethodArgs{ + MethodName: common.CreateKeyMethodName, + CreateKey: &common.CreateKeyArgs{ + Algorithm: algorithm, + }, + } + if deadline, ok := ctx.Deadline(); ok { + args.CreateKey.CtxDeadline = &deadline + } + resp, err := c.invokePlugin(ctx, nil, args) + if err != nil { + return nil, err + } + return cryptoutils.UnmarshalPEMToPublicKey(resp.CreateKey.PublicKeyPEM) +} + +// PublicKey calls and returns the plugin's implementation of PublicKey(). +// If the opts contain a context, then it will be used with the Cmd. +func (c PluginClient) PublicKey(opts ...signature.PublicKeyOption) (crypto.PublicKey, error) { + args := &common.MethodArgs{ + MethodName: common.PublicKeyMethodName, + PublicKey: &common.PublicKeyArgs{ + PublicKeyOptions: encoding.PackPublicKeyOptions(opts), + }, + } + ctx := context.Background() + for _, opt := range opts { + opt.ApplyContext(&ctx) + } + resp, err := c.invokePlugin(ctx, nil, args) + if err != nil { + return nil, err + } + return cryptoutils.UnmarshalPEMToPublicKey(resp.PublicKey.PublicKeyPEM) +} + +// SignMessage calls and returns the plugin's implementation of SignMessage(). +// If the opts contain a context, then it will be used with the Cmd. +func (c PluginClient) SignMessage(message io.Reader, opts ...signature.SignOption) ([]byte, error) { + args := &common.MethodArgs{ + MethodName: common.SignMessageMethodName, + SignMessage: &common.SignMessageArgs{ + SignOptions: encoding.PackSignOptions(opts), + }, + } + ctx := context.Background() + for _, opt := range opts { + opt.ApplyContext(&ctx) + } + resp, err := c.invokePlugin(ctx, message, args) + if err != nil { + return nil, err + } + signature := resp.SignMessage.Signature + return signature, nil +} + +// VerifySignature calls and returns the plugin's implementation of VerifySignature(). +// If the opts contain a context, then it will be used with the Cmd. +func (c PluginClient) VerifySignature(signature, message io.Reader, opts ...signature.VerifyOption) error { + // signatures won't be larger than 1MB, so it's fine to read the entire content into memory. + signatureBytes, err := io.ReadAll(signature) + if err != nil { + return err + } + args := &common.MethodArgs{ + MethodName: common.VerifySignatureMethodName, + VerifySignature: &common.VerifySignatureArgs{ + Signature: signatureBytes, + VerifyOptions: encoding.PackVerifyOptions(opts), + }, + } + ctx := context.Background() + for _, opt := range opts { + opt.ApplyContext(&ctx) + } + _, err = c.invokePlugin(ctx, message, args) + return err +} + +// CryptoSigner is a wrapper around PluginClient. +type CryptoSigner struct { + client *PluginClient + ctx context.Context + errFunc func(error) +} + +// CryptoSigner returns a wrapper around PluginClient. +func (c PluginClient) CryptoSigner(ctx context.Context, errFunc func(error)) (crypto.Signer, crypto.SignerOpts, error) { + if err := ctx.Err(); err != nil { + return nil, nil, err + } + return &CryptoSigner{ + client: &c, + ctx: ctx, + errFunc: errFunc, + }, c.initOptions.HashFunc, nil +} + +// Sign is a wrapper around PluginClient.SignMessage(). The first argument for a rand source is not used. +func (c CryptoSigner) Sign(_ io.Reader, digest []byte, cryptoSignerOpts crypto.SignerOpts) (sig []byte, err error) { + emptyMessage := bytes.NewReader([]byte("")) + opts := []signature.SignOption{ + options.WithCryptoSignerOpts(cryptoSignerOpts.HashFunc()), + options.WithDigest(digest), + // the client's initializing ctx should not be used in calls to its methods. + } + sig, err = c.client.SignMessage(emptyMessage, opts...) + if err != nil && c.errFunc != nil { + c.errFunc(err) + } + return sig, err +} + +// Public is a wrapper around PluginClient.PublicKey(). +func (c CryptoSigner) Public() crypto.PublicKey { + publicKey, err := c.client.PublicKey() + if err != nil && c.errFunc != nil { + c.errFunc(err) + // we don't panic here. + } + return publicKey +} diff --git a/vendor/github.com/sigstore/sigstore/pkg/signature/kms/kms.go b/vendor/github.com/sigstore/sigstore/pkg/signature/kms/kms.go index 7095eb10fe..7baf9504b8 100644 --- a/vendor/github.com/sigstore/sigstore/pkg/signature/kms/kms.go +++ b/vendor/github.com/sigstore/sigstore/pkg/signature/kms/kms.go @@ -19,10 +19,13 @@ package kms import ( "context" "crypto" + "errors" "fmt" + "os/exec" "strings" "github.com/sigstore/sigstore/pkg/signature" + "github.com/sigstore/sigstore/pkg/signature/kms/cliplugin" ) // ProviderNotFoundError indicates that no matching KMS provider was found @@ -48,15 +51,27 @@ func AddProvider(keyResourceID string, init ProviderInit) { var providersMap = map[string]ProviderInit{} // Get returns a KMS SignerVerifier for the given resource string and hash function. -// If no matching provider is found, Get returns a ProviderNotFoundError. It -// also returns an error if initializing the SignerVerifier fails. +// If no matching built-in provider is found, it will try to use the plugin system as a provider. +// It returns a ProviderNotFoundError in these situations: +// - keyResourceID doesn't match any of our hard-coded providers' schemas, +// - the plugin name and key ref cannot be parsed from the input keyResourceID, +// - the plugin program, can't be found. +// It also returns an error if initializing the SignerVerifier fails. func Get(ctx context.Context, keyResourceID string, hashFunc crypto.Hash, opts ...signature.RPCOption) (SignerVerifier, error) { for ref, pi := range providersMap { if strings.HasPrefix(keyResourceID, ref) { - return pi(ctx, keyResourceID, hashFunc, opts...) + sv, err := pi(ctx, keyResourceID, hashFunc, opts...) + if err != nil { + return nil, err + } + return sv, nil } } - return nil, &ProviderNotFoundError{ref: keyResourceID} + sv, err := cliplugin.LoadSignerVerifier(ctx, keyResourceID, hashFunc, opts...) + if errors.Is(err, exec.ErrNotFound) || errors.Is(err, cliplugin.ErrorInputKeyResourceID) { + return nil, fmt.Errorf("%w: %w", &ProviderNotFoundError{ref: keyResourceID}, err) + } + return sv, err } // SupportedProviders returns list of initialized providers diff --git a/vendor/github.com/sigstore/timestamp-authority/pkg/verification/verify.go b/vendor/github.com/sigstore/timestamp-authority/pkg/verification/verify.go index d47f57f1b5..82bebdd2f8 100644 --- a/vendor/github.com/sigstore/timestamp-authority/pkg/verification/verify.go +++ b/vendor/github.com/sigstore/timestamp-authority/pkg/verification/verify.go @@ -250,7 +250,7 @@ func verifyTSRWithChain(ts *timestamp.Timestamp, opts VerifyOpts) error { return fmt.Errorf("error parsing hashed message: %w", err) } - if opts.Roots == nil || len(opts.Roots) == 0 { + if len(opts.Roots) == 0 { return fmt.Errorf("no root certificates provided for verifying the certificate chain") } diff --git a/vendor/github.com/spf13/cobra/README.md b/vendor/github.com/spf13/cobra/README.md index 6444f4b7f6..71757151c3 100644 --- a/vendor/github.com/spf13/cobra/README.md +++ b/vendor/github.com/spf13/cobra/README.md @@ -1,4 +1,5 @@ -![cobra logo](assets/CobraMain.png) + +![cobra logo](https://github.com/user-attachments/assets/cbc3adf8-0dff-46e9-a88d-5e2d971c169e) Cobra is a library for creating powerful modern CLI applications. @@ -105,7 +106,7 @@ go install github.com/spf13/cobra-cli@latest For complete details on using the Cobra-CLI generator, please read [The Cobra Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md) -For complete details on using the Cobra library, please read the [The Cobra User Guide](site/content/user_guide.md). +For complete details on using the Cobra library, please read [The Cobra User Guide](site/content/user_guide.md). # License diff --git a/vendor/github.com/spf13/cobra/active_help.go b/vendor/github.com/spf13/cobra/active_help.go index 25c30e3ccc..b3e2dadfed 100644 --- a/vendor/github.com/spf13/cobra/active_help.go +++ b/vendor/github.com/spf13/cobra/active_help.go @@ -35,7 +35,7 @@ const ( // This function can be called multiple times before and/or after completions are added to // the array. Each time this function is called with the same array, the new // ActiveHelp line will be shown below the previous ones when completion is triggered. -func AppendActiveHelp(compArray []string, activeHelpStr string) []string { +func AppendActiveHelp(compArray []Completion, activeHelpStr string) []Completion { return append(compArray, fmt.Sprintf("%s%s", activeHelpMarker, activeHelpStr)) } diff --git a/vendor/github.com/spf13/cobra/bash_completionsV2.go b/vendor/github.com/spf13/cobra/bash_completionsV2.go index 1cce5c329c..d2397aa366 100644 --- a/vendor/github.com/spf13/cobra/bash_completionsV2.go +++ b/vendor/github.com/spf13/cobra/bash_completionsV2.go @@ -146,7 +146,7 @@ __%[1]s_process_completion_results() { if (((directive & shellCompDirectiveFilterFileExt) != 0)); then # File extension filtering - local fullFilter filter filteringCmd + local fullFilter="" filter filteringCmd # Do not use quotes around the $completions variable or else newline # characters will be kept. @@ -177,20 +177,71 @@ __%[1]s_process_completion_results() { __%[1]s_handle_special_char "$cur" = # Print the activeHelp statements before we finish + __%[1]s_handle_activeHelp +} + +__%[1]s_handle_activeHelp() { + # Print the activeHelp statements if ((${#activeHelp[*]} != 0)); then - printf "\n"; - printf "%%s\n" "${activeHelp[@]}" - printf "\n" - - # The prompt format is only available from bash 4.4. - # We test if it is available before using it. - if (x=${PS1@P}) 2> /dev/null; then - printf "%%s" "${PS1@P}${COMP_LINE[@]}" - else - # Can't print the prompt. Just print the - # text the user had typed, it is workable enough. - printf "%%s" "${COMP_LINE[@]}" + if [ -z $COMP_TYPE ]; then + # Bash v3 does not set the COMP_TYPE variable. + printf "\n"; + printf "%%s\n" "${activeHelp[@]}" + printf "\n" + __%[1]s_reprint_commandLine + return fi + + # Only print ActiveHelp on the second TAB press + if [ $COMP_TYPE -eq 63 ]; then + printf "\n" + printf "%%s\n" "${activeHelp[@]}" + + if ((${#COMPREPLY[*]} == 0)); then + # When there are no completion choices from the program, file completion + # may kick in if the program has not disabled it; in such a case, we want + # to know if any files will match what the user typed, so that we know if + # there will be completions presented, so that we know how to handle ActiveHelp. + # To find out, we actually trigger the file completion ourselves; + # the call to _filedir will fill COMPREPLY if files match. + if (((directive & shellCompDirectiveNoFileComp) == 0)); then + __%[1]s_debug "Listing files" + _filedir + fi + fi + + if ((${#COMPREPLY[*]} != 0)); then + # If there are completion choices to be shown, print a delimiter. + # Re-printing the command-line will automatically be done + # by the shell when it prints the completion choices. + printf -- "--" + else + # When there are no completion choices at all, we need + # to re-print the command-line since the shell will + # not be doing it itself. + __%[1]s_reprint_commandLine + fi + elif [ $COMP_TYPE -eq 37 ] || [ $COMP_TYPE -eq 42 ]; then + # For completion type: menu-complete/menu-complete-backward and insert-completions + # the completions are immediately inserted into the command-line, so we first + # print the activeHelp message and reprint the command-line since the shell won't. + printf "\n" + printf "%%s\n" "${activeHelp[@]}" + + __%[1]s_reprint_commandLine + fi + fi +} + +__%[1]s_reprint_commandLine() { + # The prompt format is only available from bash 4.4. + # We test if it is available before using it. + if (x=${PS1@P}) 2> /dev/null; then + printf "%%s" "${PS1@P}${COMP_LINE[@]}" + else + # Can't print the prompt. Just print the + # text the user had typed, it is workable enough. + printf "%%s" "${COMP_LINE[@]}" fi } @@ -201,6 +252,8 @@ __%[1]s_extract_activeHelp() { local endIndex=${#activeHelpMarker} while IFS='' read -r comp; do + [[ -z $comp ]] && continue + if [[ ${comp:0:endIndex} == $activeHelpMarker ]]; then comp=${comp:endIndex} __%[1]s_debug "ActiveHelp found: $comp" @@ -223,16 +276,21 @@ __%[1]s_handle_completion_types() { # If the user requested inserting one completion at a time, or all # completions at once on the command-line we must remove the descriptions. # https://github.com/spf13/cobra/issues/1508 - local tab=$'\t' comp - while IFS='' read -r comp; do - [[ -z $comp ]] && continue - # Strip any description - comp=${comp%%%%$tab*} - # Only consider the completions that match - if [[ $comp == "$cur"* ]]; then - COMPREPLY+=("$comp") - fi - done < <(printf "%%s\n" "${completions[@]}") + + # If there are no completions, we don't need to do anything + (( ${#completions[@]} == 0 )) && return 0 + + local tab=$'\t' + + # Strip any description and escape the completion to handled special characters + IFS=$'\n' read -ra completions -d '' < <(printf "%%q\n" "${completions[@]%%%%$tab*}") + + # Only consider the completions that match + IFS=$'\n' read -ra COMPREPLY -d '' < <(IFS=$'\n'; compgen -W "${completions[*]}" -- "${cur}") + + # compgen looses the escaping so we need to escape all completions again since they will + # all be inserted on the command-line. + IFS=$'\n' read -ra COMPREPLY -d '' < <(printf "%%q\n" "${COMPREPLY[@]}") ;; *) @@ -243,11 +301,25 @@ __%[1]s_handle_completion_types() { } __%[1]s_handle_standard_completion_case() { - local tab=$'\t' comp + local tab=$'\t' + + # If there are no completions, we don't need to do anything + (( ${#completions[@]} == 0 )) && return 0 # Short circuit to optimize if we don't have descriptions if [[ "${completions[*]}" != *$tab* ]]; then - IFS=$'\n' read -ra COMPREPLY -d '' < <(compgen -W "${completions[*]}" -- "$cur") + # First, escape the completions to handle special characters + IFS=$'\n' read -ra completions -d '' < <(printf "%%q\n" "${completions[@]}") + # Only consider the completions that match what the user typed + IFS=$'\n' read -ra COMPREPLY -d '' < <(IFS=$'\n'; compgen -W "${completions[*]}" -- "${cur}") + + # compgen looses the escaping so, if there is only a single completion, we need to + # escape it again because it will be inserted on the command-line. If there are multiple + # completions, we don't want to escape them because they will be printed in a list + # and we don't want to show escape characters in that list. + if (( ${#COMPREPLY[@]} == 1 )); then + COMPREPLY[0]=$(printf "%%q" "${COMPREPLY[0]}") + fi return 0 fi @@ -256,23 +328,39 @@ __%[1]s_handle_standard_completion_case() { # Look for the longest completion so that we can format things nicely while IFS='' read -r compline; do [[ -z $compline ]] && continue - # Strip any description before checking the length - comp=${compline%%%%$tab*} + + # Before checking if the completion matches what the user typed, + # we need to strip any description and escape the completion to handle special + # characters because those escape characters are part of what the user typed. + # Don't call "printf" in a sub-shell because it will be much slower + # since we are in a loop. + printf -v comp "%%q" "${compline%%%%$tab*}" &>/dev/null || comp=$(printf "%%q" "${compline%%%%$tab*}") + # Only consider the completions that match [[ $comp == "$cur"* ]] || continue + + # The completions matches. Add it to the list of full completions including + # its description. We don't escape the completion because it may get printed + # in a list if there are more than one and we don't want show escape characters + # in that list. COMPREPLY+=("$compline") + + # Strip any description before checking the length, and again, don't escape + # the completion because this length is only used when printing the completions + # in a list and we don't want show escape characters in that list. + comp=${compline%%%%$tab*} if ((${#comp}>longest)); then longest=${#comp} fi done < <(printf "%%s\n" "${completions[@]}") - # If there is a single completion left, remove the description text + # If there is a single completion left, remove the description text and escape any special characters if ((${#COMPREPLY[*]} == 1)); then __%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}" - comp="${COMPREPLY[0]%%%%$tab*}" - __%[1]s_debug "Removed description from single completion, which is now: ${comp}" - COMPREPLY[0]=$comp - else # Format the descriptions + COMPREPLY[0]=$(printf "%%q" "${COMPREPLY[0]%%%%$tab*}") + __%[1]s_debug "Removed description from single completion, which is now: ${COMPREPLY[0]}" + else + # Format the descriptions __%[1]s_format_comp_descriptions $longest fi } diff --git a/vendor/github.com/spf13/cobra/cobra.go b/vendor/github.com/spf13/cobra/cobra.go index e0b0947b04..d9cd2414e2 100644 --- a/vendor/github.com/spf13/cobra/cobra.go +++ b/vendor/github.com/spf13/cobra/cobra.go @@ -176,12 +176,16 @@ func rpad(s string, padding int) string { return fmt.Sprintf(formattedString, s) } -// tmpl executes the given template text on data, writing the result to w. -func tmpl(w io.Writer, text string, data interface{}) error { - t := template.New("top") - t.Funcs(templateFuncs) - template.Must(t.Parse(text)) - return t.Execute(w, data) +func tmpl(text string) *tmplFunc { + return &tmplFunc{ + tmpl: text, + fn: func(w io.Writer, data interface{}) error { + t := template.New("top") + t.Funcs(templateFuncs) + template.Must(t.Parse(text)) + return t.Execute(w, data) + }, + } } // ld compares two strings and returns the levenshtein distance between them. diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go index 54748fc67e..dbb2c298ba 100644 --- a/vendor/github.com/spf13/cobra/command.go +++ b/vendor/github.com/spf13/cobra/command.go @@ -33,6 +33,9 @@ import ( const ( FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra" CommandDisplayNameAnnotation = "cobra_annotation_command_display_name" + + helpFlagName = "help" + helpCommandName = "help" ) // FParseErrWhitelist configures Flag parse errors to be ignored @@ -80,11 +83,11 @@ type Command struct { Example string // ValidArgs is list of all valid non-flag arguments that are accepted in shell completions - ValidArgs []string + ValidArgs []Completion // ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion. // It is a dynamic version of using ValidArgs. // Only one of ValidArgs and ValidArgsFunction can be used for a command. - ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) + ValidArgsFunction CompletionFunc // Expected arguments Args PositionalArgs @@ -168,12 +171,12 @@ type Command struct { // usageFunc is usage func defined by user. usageFunc func(*Command) error // usageTemplate is usage template defined by user. - usageTemplate string + usageTemplate *tmplFunc // flagErrorFunc is func defined by user and it's called when the parsing of // flags returns an error. flagErrorFunc func(*Command, error) error // helpTemplate is help template defined by user. - helpTemplate string + helpTemplate *tmplFunc // helpFunc is help func defined by user. helpFunc func(*Command, []string) // helpCommand is command with usage 'help'. If it's not defined by user, @@ -186,7 +189,7 @@ type Command struct { completionCommandGroupID string // versionTemplate is the version template defined by user. - versionTemplate string + versionTemplate *tmplFunc // errPrefix is the error message prefix defined by user. errPrefix string @@ -281,6 +284,7 @@ func (c *Command) SetArgs(a []string) { // SetOutput sets the destination for usage and error messages. // If output is nil, os.Stderr is used. +// // Deprecated: Use SetOut and/or SetErr instead func (c *Command) SetOutput(output io.Writer) { c.outWriter = output @@ -312,7 +316,11 @@ func (c *Command) SetUsageFunc(f func(*Command) error) { // SetUsageTemplate sets usage template. Can be defined by Application. func (c *Command) SetUsageTemplate(s string) { - c.usageTemplate = s + if s == "" { + c.usageTemplate = nil + return + } + c.usageTemplate = tmpl(s) } // SetFlagErrorFunc sets a function to generate an error when flag parsing @@ -348,12 +356,20 @@ func (c *Command) SetCompletionCommandGroupID(groupID string) { // SetHelpTemplate sets help template to be used. Application can use it to set custom template. func (c *Command) SetHelpTemplate(s string) { - c.helpTemplate = s + if s == "" { + c.helpTemplate = nil + return + } + c.helpTemplate = tmpl(s) } // SetVersionTemplate sets version template to be used. Application can use it to set custom template. func (c *Command) SetVersionTemplate(s string) { - c.versionTemplate = s + if s == "" { + c.versionTemplate = nil + return + } + c.versionTemplate = tmpl(s) } // SetErrPrefix sets error message prefix to be used. Application can use it to set custom prefix. @@ -434,7 +450,8 @@ func (c *Command) UsageFunc() (f func(*Command) error) { } return func(c *Command) error { c.mergePersistentFlags() - err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c) + fn := c.getUsageTemplateFunc() + err := fn(c.OutOrStderr(), c) if err != nil { c.PrintErrln(err) } @@ -442,6 +459,19 @@ func (c *Command) UsageFunc() (f func(*Command) error) { } } +// getUsageTemplateFunc returns the usage template function for the command +// going up the command tree if necessary. +func (c *Command) getUsageTemplateFunc() func(w io.Writer, data interface{}) error { + if c.usageTemplate != nil { + return c.usageTemplate.fn + } + + if c.HasParent() { + return c.parent.getUsageTemplateFunc() + } + return defaultUsageFunc +} + // Usage puts out the usage for the command. // Used when a user provides invalid input. // Can be defined by user by overriding UsageFunc. @@ -460,15 +490,30 @@ func (c *Command) HelpFunc() func(*Command, []string) { } return func(c *Command, a []string) { c.mergePersistentFlags() + fn := c.getHelpTemplateFunc() // The help should be sent to stdout // See https://github.com/spf13/cobra/issues/1002 - err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c) + err := fn(c.OutOrStdout(), c) if err != nil { c.PrintErrln(err) } } } +// getHelpTemplateFunc returns the help template function for the command +// going up the command tree if necessary. +func (c *Command) getHelpTemplateFunc() func(w io.Writer, data interface{}) error { + if c.helpTemplate != nil { + return c.helpTemplate.fn + } + + if c.HasParent() { + return c.parent.getHelpTemplateFunc() + } + + return defaultHelpFunc +} + // Help puts out the help for the command. // Used when a user calls help [command]. // Can be defined by user by overriding HelpFunc. @@ -543,71 +588,55 @@ func (c *Command) NamePadding() int { } // UsageTemplate returns usage template for the command. +// This function is kept for backwards-compatibility reasons. func (c *Command) UsageTemplate() string { - if c.usageTemplate != "" { - return c.usageTemplate + if c.usageTemplate != nil { + return c.usageTemplate.tmpl } if c.HasParent() { return c.parent.UsageTemplate() } - return `Usage:{{if .Runnable}} - {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}} - {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}} - -Aliases: - {{.NameAndAliases}}{{end}}{{if .HasExample}} - -Examples: -{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}} - -Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}} - {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}} - -{{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name "help")))}} - {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}} - -Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}} - {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}} - -Flags: -{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}} - -Global Flags: -{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}} - -Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}} - {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}} - -Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}} -` + return defaultUsageTemplate } // HelpTemplate return help template for the command. +// This function is kept for backwards-compatibility reasons. func (c *Command) HelpTemplate() string { - if c.helpTemplate != "" { - return c.helpTemplate + if c.helpTemplate != nil { + return c.helpTemplate.tmpl } if c.HasParent() { return c.parent.HelpTemplate() } - return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}} - -{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}` + return defaultHelpTemplate } // VersionTemplate return version template for the command. +// This function is kept for backwards-compatibility reasons. func (c *Command) VersionTemplate() string { - if c.versionTemplate != "" { - return c.versionTemplate + if c.versionTemplate != nil { + return c.versionTemplate.tmpl } if c.HasParent() { return c.parent.VersionTemplate() } - return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}} -` + return defaultVersionTemplate +} + +// getVersionTemplateFunc returns the version template function for the command +// going up the command tree if necessary. +func (c *Command) getVersionTemplateFunc() func(w io.Writer, data interface{}) error { + if c.versionTemplate != nil { + return c.versionTemplate.fn + } + + if c.HasParent() { + return c.parent.getVersionTemplateFunc() + } + return defaultVersionFunc } // ErrPrefix return error message prefix for the command @@ -894,7 +923,7 @@ func (c *Command) execute(a []string) (err error) { // If help is called, regardless of other flags, return we want help. // Also say we need help if the command isn't runnable. - helpVal, err := c.Flags().GetBool("help") + helpVal, err := c.Flags().GetBool(helpFlagName) if err != nil { // should be impossible to get here as we always declare a help // flag in InitDefaultHelpFlag() @@ -914,7 +943,8 @@ func (c *Command) execute(a []string) (err error) { return err } if versionVal { - err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c) + fn := c.getVersionTemplateFunc() + err := fn(c.OutOrStdout(), c) if err != nil { c.Println(err) } @@ -1068,12 +1098,6 @@ func (c *Command) ExecuteC() (cmd *Command, err error) { // initialize help at the last point to allow for user overriding c.InitDefaultHelpCmd() - // initialize completion at the last point to allow for user overriding - c.InitDefaultCompletionCmd() - - // Now that all commands have been created, let's make sure all groups - // are properly created also - c.checkCommandGroups() args := c.args @@ -1082,9 +1106,16 @@ func (c *Command) ExecuteC() (cmd *Command, err error) { args = os.Args[1:] } - // initialize the hidden command to be used for shell completion + // initialize the __complete command to be used for shell completion c.initCompleteCmd(args) + // initialize the default completion command + c.InitDefaultCompletionCmd(args...) + + // Now that all commands have been created, let's make sure all groups + // are properly created also + c.checkCommandGroups() + var flags []string if c.TraverseChildren { cmd, flags, err = c.Traverse(args) @@ -1187,16 +1218,16 @@ func (c *Command) checkCommandGroups() { // If c already has help flag, it will do nothing. func (c *Command) InitDefaultHelpFlag() { c.mergePersistentFlags() - if c.Flags().Lookup("help") == nil { + if c.Flags().Lookup(helpFlagName) == nil { usage := "help for " - name := c.displayName() + name := c.DisplayName() if name == "" { usage += "this command" } else { usage += name } - c.Flags().BoolP("help", "h", false, usage) - _ = c.Flags().SetAnnotation("help", FlagSetByCobraAnnotation, []string{"true"}) + c.Flags().BoolP(helpFlagName, "h", false, usage) + _ = c.Flags().SetAnnotation(helpFlagName, FlagSetByCobraAnnotation, []string{"true"}) } } @@ -1215,7 +1246,7 @@ func (c *Command) InitDefaultVersionFlag() { if c.Name() == "" { usage += "this command" } else { - usage += c.Name() + usage += c.DisplayName() } if c.Flags().ShorthandLookup("v") == nil { c.Flags().BoolP("version", "v", false, usage) @@ -1239,9 +1270,9 @@ func (c *Command) InitDefaultHelpCmd() { Use: "help [command]", Short: "Help about any command", Long: `Help provides help for any command in the application. -Simply type ` + c.displayName() + ` help [path to command] for full details.`, - ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]string, ShellCompDirective) { - var completions []string +Simply type ` + c.DisplayName() + ` help [path to command] for full details.`, + ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) { + var completions []Completion cmd, _, e := c.Root().Find(args) if e != nil { return nil, ShellCompDirectiveNoFileComp @@ -1253,7 +1284,7 @@ Simply type ` + c.displayName() + ` help [path to command] for full details.`, for _, subCmd := range cmd.Commands() { if subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand { if strings.HasPrefix(subCmd.Name(), toComplete) { - completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short)) + completions = append(completions, CompletionWithDesc(subCmd.Name(), subCmd.Short)) } } } @@ -1430,10 +1461,12 @@ func (c *Command) CommandPath() string { if c.HasParent() { return c.Parent().CommandPath() + " " + c.Name() } - return c.displayName() + return c.DisplayName() } -func (c *Command) displayName() string { +// DisplayName returns the name to display in help text. Returns command Name() +// If CommandDisplayNameAnnoation is not set +func (c *Command) DisplayName() string { if displayName, ok := c.Annotations[CommandDisplayNameAnnotation]; ok { return displayName } @@ -1443,7 +1476,7 @@ func (c *Command) displayName() string { // UseLine puts out the full usage for a given command (including parents). func (c *Command) UseLine() string { var useline string - use := strings.Replace(c.Use, c.Name(), c.displayName(), 1) + use := strings.Replace(c.Use, c.Name(), c.DisplayName(), 1) if c.HasParent() { useline = c.parent.CommandPath() + " " + use } else { @@ -1649,7 +1682,7 @@ func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) f // to this command (local and persistent declared here and by all parents). func (c *Command) Flags() *flag.FlagSet { if c.flags == nil { - c.flags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) + c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) if c.flagErrorBuf == nil { c.flagErrorBuf = new(bytes.Buffer) } @@ -1664,7 +1697,7 @@ func (c *Command) Flags() *flag.FlagSet { func (c *Command) LocalNonPersistentFlags() *flag.FlagSet { persistentFlags := c.PersistentFlags() - out := flag.NewFlagSet(c.displayName(), flag.ContinueOnError) + out := flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) c.LocalFlags().VisitAll(func(f *flag.Flag) { if persistentFlags.Lookup(f.Name) == nil { out.AddFlag(f) @@ -1679,7 +1712,7 @@ func (c *Command) LocalFlags() *flag.FlagSet { c.mergePersistentFlags() if c.lflags == nil { - c.lflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) + c.lflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) if c.flagErrorBuf == nil { c.flagErrorBuf = new(bytes.Buffer) } @@ -1707,7 +1740,7 @@ func (c *Command) InheritedFlags() *flag.FlagSet { c.mergePersistentFlags() if c.iflags == nil { - c.iflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) + c.iflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) if c.flagErrorBuf == nil { c.flagErrorBuf = new(bytes.Buffer) } @@ -1736,7 +1769,7 @@ func (c *Command) NonInheritedFlags() *flag.FlagSet { // PersistentFlags returns the persistent FlagSet specifically set in the current command. func (c *Command) PersistentFlags() *flag.FlagSet { if c.pflags == nil { - c.pflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) + c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) if c.flagErrorBuf == nil { c.flagErrorBuf = new(bytes.Buffer) } @@ -1749,9 +1782,9 @@ func (c *Command) PersistentFlags() *flag.FlagSet { func (c *Command) ResetFlags() { c.flagErrorBuf = new(bytes.Buffer) c.flagErrorBuf.Reset() - c.flags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) + c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) c.flags.SetOutput(c.flagErrorBuf) - c.pflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) + c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) c.pflags.SetOutput(c.flagErrorBuf) c.lflags = nil @@ -1868,7 +1901,7 @@ func (c *Command) mergePersistentFlags() { // If c.parentsPflags == nil, it makes new. func (c *Command) updateParentsPflags() { if c.parentsPflags == nil { - c.parentsPflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) + c.parentsPflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) c.parentsPflags.SetOutput(c.flagErrorBuf) c.parentsPflags.SortFlags = false } @@ -1894,3 +1927,141 @@ func commandNameMatches(s string, t string) bool { return s == t } + +// tmplFunc holds a template and a function that will execute said template. +type tmplFunc struct { + tmpl string + fn func(io.Writer, interface{}) error +} + +var defaultUsageTemplate = `Usage:{{if .Runnable}} + {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}} + {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}} + +Aliases: + {{.NameAndAliases}}{{end}}{{if .HasExample}} + +Examples: +{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}} + +Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}} + {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}} + +{{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name "help")))}} + {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}} + +Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}} + {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}} + +Flags: +{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}} + +Global Flags: +{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}} + +Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}} + {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}} + +Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}} +` + +// defaultUsageFunc is equivalent to executing defaultUsageTemplate. The two should be changed in sync. +func defaultUsageFunc(w io.Writer, in interface{}) error { + c := in.(*Command) + fmt.Fprint(w, "Usage:") + if c.Runnable() { + fmt.Fprintf(w, "\n %s", c.UseLine()) + } + if c.HasAvailableSubCommands() { + fmt.Fprintf(w, "\n %s [command]", c.CommandPath()) + } + if len(c.Aliases) > 0 { + fmt.Fprintf(w, "\n\nAliases:\n") + fmt.Fprintf(w, " %s", c.NameAndAliases()) + } + if c.HasExample() { + fmt.Fprintf(w, "\n\nExamples:\n") + fmt.Fprintf(w, "%s", c.Example) + } + if c.HasAvailableSubCommands() { + cmds := c.Commands() + if len(c.Groups()) == 0 { + fmt.Fprintf(w, "\n\nAvailable Commands:") + for _, subcmd := range cmds { + if subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName { + fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short) + } + } + } else { + for _, group := range c.Groups() { + fmt.Fprintf(w, "\n\n%s", group.Title) + for _, subcmd := range cmds { + if subcmd.GroupID == group.ID && (subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName) { + fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short) + } + } + } + if !c.AllChildCommandsHaveGroup() { + fmt.Fprintf(w, "\n\nAdditional Commands:") + for _, subcmd := range cmds { + if subcmd.GroupID == "" && (subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName) { + fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short) + } + } + } + } + } + if c.HasAvailableLocalFlags() { + fmt.Fprintf(w, "\n\nFlags:\n") + fmt.Fprint(w, trimRightSpace(c.LocalFlags().FlagUsages())) + } + if c.HasAvailableInheritedFlags() { + fmt.Fprintf(w, "\n\nGlobal Flags:\n") + fmt.Fprint(w, trimRightSpace(c.InheritedFlags().FlagUsages())) + } + if c.HasHelpSubCommands() { + fmt.Fprintf(w, "\n\nAdditional help topcis:") + for _, subcmd := range c.Commands() { + if subcmd.IsAdditionalHelpTopicCommand() { + fmt.Fprintf(w, "\n %s %s", rpad(subcmd.CommandPath(), subcmd.CommandPathPadding()), subcmd.Short) + } + } + } + if c.HasAvailableSubCommands() { + fmt.Fprintf(w, "\n\nUse \"%s [command] --help\" for more information about a command.", c.CommandPath()) + } + fmt.Fprintln(w) + return nil +} + +var defaultHelpTemplate = `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}} + +{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}` + +// defaultHelpFunc is equivalent to executing defaultHelpTemplate. The two should be changed in sync. +func defaultHelpFunc(w io.Writer, in interface{}) error { + c := in.(*Command) + usage := c.Long + if usage == "" { + usage = c.Short + } + usage = trimRightSpace(usage) + if usage != "" { + fmt.Fprintln(w, usage) + fmt.Fprintln(w) + } + if c.Runnable() || c.HasSubCommands() { + fmt.Fprint(w, c.UsageString()) + } + return nil +} + +var defaultVersionTemplate = `{{with .DisplayName}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}} +` + +// defaultVersionFunc is equivalent to executing defaultVersionTemplate. The two should be changed in sync. +func defaultVersionFunc(w io.Writer, in interface{}) error { + c := in.(*Command) + _, err := fmt.Fprintf(w, "%s version %s\n", c.DisplayName(), c.Version) + return err +} diff --git a/vendor/github.com/spf13/cobra/completions.go b/vendor/github.com/spf13/cobra/completions.go index c0c08b0572..a1752f7631 100644 --- a/vendor/github.com/spf13/cobra/completions.go +++ b/vendor/github.com/spf13/cobra/completions.go @@ -35,7 +35,7 @@ const ( ) // Global map of flag completion functions. Make sure to use flagCompletionMutex before you try to read and write from it. -var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){} +var flagCompletionFunctions = map[*pflag.Flag]CompletionFunc{} // lock for reading and writing from flagCompletionFunctions var flagCompletionMutex = &sync.RWMutex{} @@ -117,22 +117,50 @@ type CompletionOptions struct { HiddenDefaultCmd bool } +// Completion is a string that can be used for completions +// +// two formats are supported: +// - the completion choice +// - the completion choice with a textual description (separated by a TAB). +// +// [CompletionWithDesc] can be used to create a completion string with a textual description. +// +// Note: Go type alias is used to provide a more descriptive name in the documentation, but any string can be used. +type Completion = string + +// CompletionFunc is a function that provides completion results. +type CompletionFunc = func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) + +// CompletionWithDesc returns a [Completion] with a description by using the TAB delimited format. +func CompletionWithDesc(choice string, description string) Completion { + return choice + "\t" + description +} + // NoFileCompletions can be used to disable file completion for commands that should // not trigger file completions. -func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { +// +// This method satisfies [CompletionFunc]. +// It can be used with [Command.RegisterFlagCompletionFunc] and for [Command.ValidArgsFunction]. +func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) { return nil, ShellCompDirectiveNoFileComp } // FixedCompletions can be used to create a completion function which always // returns the same results. -func FixedCompletions(choices []string, directive ShellCompDirective) func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { - return func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { +// +// This method returns a function that satisfies [CompletionFunc] +// It can be used with [Command.RegisterFlagCompletionFunc] and for [Command.ValidArgsFunction]. +func FixedCompletions(choices []Completion, directive ShellCompDirective) CompletionFunc { + return func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) { return choices, directive } } // RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag. -func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error { +// +// You can use pre-defined completion functions such as [FixedCompletions] or [NoFileCompletions], +// or you can define your own. +func (c *Command) RegisterFlagCompletionFunc(flagName string, f CompletionFunc) error { flag := c.Flag(flagName) if flag == nil { return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName) @@ -148,7 +176,7 @@ func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Comman } // GetFlagCompletionFunc returns the completion function for the given flag of the command, if available. -func (c *Command) GetFlagCompletionFunc(flagName string) (func(*Command, []string, string) ([]string, ShellCompDirective), bool) { +func (c *Command) GetFlagCompletionFunc(flagName string) (CompletionFunc, bool) { flag := c.Flag(flagName) if flag == nil { return nil, false @@ -270,7 +298,15 @@ func (c *Command) initCompleteCmd(args []string) { } } -func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) { +// SliceValue is a reduced version of [pflag.SliceValue]. It is used to detect +// flags that accept multiple values and therefore can provide completion +// multiple times. +type SliceValue interface { + // GetSlice returns the flag value list as an array of strings. + GetSlice() []string +} + +func (c *Command) getCompletions(args []string) (*Command, []Completion, ShellCompDirective, error) { // The last argument, which is not completely typed by the user, // should not be part of the list of arguments toComplete := args[len(args)-1] @@ -298,7 +334,7 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi } if err != nil { // Unable to find the real command. E.g., someInvalidCmd - return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("unable to find a command for arguments: %v", trimmedArgs) + return c, []Completion{}, ShellCompDirectiveDefault, fmt.Errorf("unable to find a command for arguments: %v", trimmedArgs) } finalCmd.ctx = c.ctx @@ -328,7 +364,7 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi // Parse the flags early so we can check if required flags are set if err = finalCmd.ParseFlags(finalArgs); err != nil { - return finalCmd, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error()) + return finalCmd, []Completion{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error()) } realArgCount := finalCmd.Flags().NArg() @@ -340,14 +376,14 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi if flagErr != nil { // If error type is flagCompError and we don't want flagCompletion we should ignore the error if _, ok := flagErr.(*flagCompError); !(ok && !flagCompletion) { - return finalCmd, []string{}, ShellCompDirectiveDefault, flagErr + return finalCmd, []Completion{}, ShellCompDirectiveDefault, flagErr } } // Look for the --help or --version flags. If they are present, // there should be no further completions. if helpOrVersionFlagPresent(finalCmd) { - return finalCmd, []string{}, ShellCompDirectiveNoFileComp, nil + return finalCmd, []Completion{}, ShellCompDirectiveNoFileComp, nil } // We only remove the flags from the arguments if DisableFlagParsing is not set. @@ -376,11 +412,11 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi return finalCmd, subDir, ShellCompDirectiveFilterDirs, nil } // Directory completion - return finalCmd, []string{}, ShellCompDirectiveFilterDirs, nil + return finalCmd, []Completion{}, ShellCompDirectiveFilterDirs, nil } } - var completions []string + var completions []Completion var directive ShellCompDirective // Enforce flag groups before doing flag completions @@ -399,10 +435,14 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi // If we have not found any required flags, only then can we show regular flags if len(completions) == 0 { doCompleteFlags := func(flag *pflag.Flag) { - if !flag.Changed || + _, acceptsMultiple := flag.Value.(SliceValue) + acceptsMultiple = acceptsMultiple || strings.Contains(flag.Value.Type(), "Slice") || - strings.Contains(flag.Value.Type(), "Array") { - // If the flag is not already present, or if it can be specified multiple times (Array or Slice) + strings.Contains(flag.Value.Type(), "Array") || + strings.HasPrefix(flag.Value.Type(), "stringTo") + + if !flag.Changed || acceptsMultiple { + // If the flag is not already present, or if it can be specified multiple times (Array, Slice, or stringTo) // we suggest it as a completion completions = append(completions, getFlagNameCompletions(flag, toComplete)...) } @@ -462,7 +502,7 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi for _, subCmd := range finalCmd.Commands() { if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand { if strings.HasPrefix(subCmd.Name(), toComplete) { - completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short)) + completions = append(completions, CompletionWithDesc(subCmd.Name(), subCmd.Short)) } directive = ShellCompDirectiveNoFileComp } @@ -507,7 +547,7 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi } // Find the completion function for the flag or command - var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) + var completionFn CompletionFunc if flag != nil && flagCompletion { flagCompletionMutex.RLock() completionFn = flagCompletionFunctions[flag] @@ -518,7 +558,7 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi if completionFn != nil { // Go custom completion defined for this flag or command. // Call the registered completion function to get the completions. - var comps []string + var comps []Completion comps, directive = completionFn(finalCmd, finalArgs, toComplete) completions = append(completions, comps...) } @@ -531,23 +571,23 @@ func helpOrVersionFlagPresent(cmd *Command) bool { len(versionFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && versionFlag.Changed { return true } - if helpFlag := cmd.Flags().Lookup("help"); helpFlag != nil && + if helpFlag := cmd.Flags().Lookup(helpFlagName); helpFlag != nil && len(helpFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && helpFlag.Changed { return true } return false } -func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string { +func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []Completion { if nonCompletableFlag(flag) { - return []string{} + return []Completion{} } - var completions []string + var completions []Completion flagName := "--" + flag.Name if strings.HasPrefix(flagName, toComplete) { // Flag without the = - completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage)) + completions = append(completions, CompletionWithDesc(flagName, flag.Usage)) // Why suggest both long forms: --flag and --flag= ? // This forces the user to *always* have to type either an = or a space after the flag name. @@ -559,20 +599,20 @@ func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string { // if len(flag.NoOptDefVal) == 0 { // // Flag requires a value, so it can be suffixed with = // flagName += "=" - // completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage)) + // completions = append(completions, CompletionWithDesc(flagName, flag.Usage)) // } } flagName = "-" + flag.Shorthand if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) { - completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage)) + completions = append(completions, CompletionWithDesc(flagName, flag.Usage)) } return completions } -func completeRequireFlags(finalCmd *Command, toComplete string) []string { - var completions []string +func completeRequireFlags(finalCmd *Command, toComplete string) []Completion { + var completions []Completion doCompleteRequiredFlags := func(flag *pflag.Flag) { if _, present := flag.Annotations[BashCompOneRequiredFlag]; present { @@ -687,8 +727,8 @@ func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*p // 1- the feature has been explicitly disabled by the program, // 2- c has no subcommands (to avoid creating one), // 3- c already has a 'completion' command provided by the program. -func (c *Command) InitDefaultCompletionCmd() { - if c.CompletionOptions.DisableDefaultCmd || !c.HasSubCommands() { +func (c *Command) InitDefaultCompletionCmd(args ...string) { + if c.CompletionOptions.DisableDefaultCmd { return } @@ -701,6 +741,16 @@ func (c *Command) InitDefaultCompletionCmd() { haveNoDescFlag := !c.CompletionOptions.DisableNoDescFlag && !c.CompletionOptions.DisableDescriptions + // Special case to know if there are sub-commands or not. + hasSubCommands := false + for _, cmd := range c.commands { + if cmd.Name() != ShellCompRequestCmd && cmd.Name() != helpCommandName { + // We found a real sub-command (not 'help' or '__complete') + hasSubCommands = true + break + } + } + completionCmd := &Command{ Use: compCmdName, Short: "Generate the autocompletion script for the specified shell", @@ -714,6 +764,22 @@ See each sub-command's help for details on how to use the generated script. } c.AddCommand(completionCmd) + if !hasSubCommands { + // If the 'completion' command will be the only sub-command, + // we only create it if it is actually being called. + // This avoids breaking programs that would suddenly find themselves with + // a subcommand, which would prevent them from accepting arguments. + // We also create the 'completion' command if the user is triggering + // shell completion for it (prog __complete completion '') + subCmd, cmdArgs, err := c.Find(args) + if err != nil || subCmd.Name() != compCmdName && + !(subCmd.Name() == ShellCompRequestCmd && len(cmdArgs) > 1 && cmdArgs[0] == compCmdName) { + // The completion command is not being called or being completed so we remove it. + c.RemoveCommand(completionCmd) + return + } + } + out := c.OutOrStdout() noDesc := c.CompletionOptions.DisableDescriptions shortDesc := "Generate the autocompletion script for %s" diff --git a/vendor/github.com/spf13/cobra/powershell_completions.go b/vendor/github.com/spf13/cobra/powershell_completions.go index a830b7bcad..746dcb92e3 100644 --- a/vendor/github.com/spf13/cobra/powershell_completions.go +++ b/vendor/github.com/spf13/cobra/powershell_completions.go @@ -162,7 +162,10 @@ filter __%[1]s_escapeStringWithSpecialChars { if (-Not $Description) { $Description = " " } - @{Name="$Name";Description="$Description"} + New-Object -TypeName PSCustomObject -Property @{ + Name = "$Name" + Description = "$Description" + } } @@ -240,7 +243,12 @@ filter __%[1]s_escapeStringWithSpecialChars { __%[1]s_debug "Only one completion left" # insert space after value - [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") + $CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space + if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){ + [System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") + } else { + $CompletionText + } } else { # Add the proper number of spaces to align the descriptions @@ -255,7 +263,12 @@ filter __%[1]s_escapeStringWithSpecialChars { $Description = " ($($comp.Description))" } - [System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description", "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)") + $CompletionText = "$($comp.Name)$Description" + if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){ + [System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)") + } else { + $CompletionText + } } } @@ -264,7 +277,13 @@ filter __%[1]s_escapeStringWithSpecialChars { # insert space after value # MenuComplete will automatically show the ToolTip of # the highlighted value at the bottom of the suggestions. - [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") + + $CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space + if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){ + [System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") + } else { + $CompletionText + } } # TabCompleteNext and in case we get something unknown @@ -272,7 +291,13 @@ filter __%[1]s_escapeStringWithSpecialChars { # Like MenuComplete but we don't want to add a space here because # the user need to press space anyway to get the completion. # Description will not be shown because that's not possible with TabCompleteNext - [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)") + + $CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars) + if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){ + [System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") + } else { + $CompletionText + } } } diff --git a/vendor/github.com/spiffe/go-spiffe/v2/bundle/jwtbundle/bundle.go b/vendor/github.com/spiffe/go-spiffe/v2/bundle/jwtbundle/bundle.go index ff2fcd71e4..ebd3cacd47 100644 --- a/vendor/github.com/spiffe/go-spiffe/v2/bundle/jwtbundle/bundle.go +++ b/vendor/github.com/spiffe/go-spiffe/v2/bundle/jwtbundle/bundle.go @@ -3,6 +3,7 @@ package jwtbundle import ( "crypto" "encoding/json" + "errors" "io" "os" "sync" @@ -69,7 +70,7 @@ func Parse(trustDomain spiffeid.TrustDomain, bundleBytes []byte) (*Bundle, error bundle := New(trustDomain) for i, key := range jwks.Keys { if err := bundle.AddJWTAuthority(key.KeyID, key.Key); err != nil { - return nil, jwtbundleErr.New("error adding authority %d of JWKS: %v", i, errs.Unwrap(err)) + return nil, jwtbundleErr.New("error adding authority %d of JWKS: %v", i, errors.Unwrap(err)) } } diff --git a/vendor/github.com/spiffe/go-spiffe/v2/bundle/jwtbundle/doc.go b/vendor/github.com/spiffe/go-spiffe/v2/bundle/jwtbundle/doc.go index ef165d8827..394878e1b2 100644 --- a/vendor/github.com/spiffe/go-spiffe/v2/bundle/jwtbundle/doc.go +++ b/vendor/github.com/spiffe/go-spiffe/v2/bundle/jwtbundle/doc.go @@ -5,17 +5,17 @@ // // You can create a new bundle for a specific trust domain: // -// td := spiffeid.RequireTrustDomain("example.org") +// td := spiffeid.RequireTrustDomainFromString("example.org") // bundle := jwtbundle.New(td) // // Or you can load it from disk: // -// td := spiffeid.RequireTrustDomain("example.org") +// td := spiffeid.RequireTrustDomainFromString("example.org") // bundle := jwtbundle.Load(td, "bundle.jwks") // // The bundle can be initialized with JWT authorities: // -// td := spiffeid.RequireTrustDomain("example.org") +// td := spiffeid.RequireTrustDomainFromString("example.org") // var jwtAuthorities map[string]crypto.PublicKey = ... // bundle := jwtbundle.FromJWTAuthorities(td, jwtAuthorities) // diff --git a/vendor/github.com/spiffe/go-spiffe/v2/bundle/spiffebundle/bundle.go b/vendor/github.com/spiffe/go-spiffe/v2/bundle/spiffebundle/bundle.go index be176423c1..13b103e24c 100644 --- a/vendor/github.com/spiffe/go-spiffe/v2/bundle/spiffebundle/bundle.go +++ b/vendor/github.com/spiffe/go-spiffe/v2/bundle/spiffebundle/bundle.go @@ -4,6 +4,7 @@ import ( "crypto" "crypto/x509" "encoding/json" + "errors" "io" "os" "sync" @@ -106,7 +107,7 @@ func Parse(trustDomain spiffeid.TrustDomain, bundleBytes []byte) (*Bundle, error bundle.AddX509Authority(key.Certificates[0]) case jwtSVIDUse: if err := bundle.AddJWTAuthority(key.KeyID, key.Key); err != nil { - return nil, spiffebundleErr.New("error adding authority %d of JWKS: %v", i, errs.Unwrap(err)) + return nil, spiffebundleErr.New("error adding authority %d of JWKS: %v", i, errors.Unwrap(err)) } } } diff --git a/vendor/github.com/spiffe/go-spiffe/v2/bundle/spiffebundle/doc.go b/vendor/github.com/spiffe/go-spiffe/v2/bundle/spiffebundle/doc.go index 82218f780d..db9dcde31f 100644 --- a/vendor/github.com/spiffe/go-spiffe/v2/bundle/spiffebundle/doc.go +++ b/vendor/github.com/spiffe/go-spiffe/v2/bundle/spiffebundle/doc.go @@ -5,17 +5,17 @@ // // You can create a new bundle for a specific trust domain: // -// td := spiffeid.RequireTrustDomain("example.org") +// td := spiffeid.RequireTrustDomainFromString("example.org") // bundle := spiffebundle.New(td) // // Or you can load it from disk: // -// td := spiffeid.RequireTrustDomain("example.org") +// td := spiffeid.RequireTrustDomainFromString("example.org") // bundle := spiffebundle.Load(td, "bundle.json") // // The bundle can be initialized with X.509 or JWT authorities: // -// td := spiffeid.RequireTrustDomain("example.org") +// td := spiffeid.RequireTrustDomainFromString("example.org") // // var x509Authorities []*x509.Certificate = ... // bundle := spiffebundle.FromX509Authorities(td, x509Authorities) diff --git a/vendor/github.com/spiffe/go-spiffe/v2/bundle/x509bundle/doc.go b/vendor/github.com/spiffe/go-spiffe/v2/bundle/x509bundle/doc.go index d8a5d8b893..889554f822 100644 --- a/vendor/github.com/spiffe/go-spiffe/v2/bundle/x509bundle/doc.go +++ b/vendor/github.com/spiffe/go-spiffe/v2/bundle/x509bundle/doc.go @@ -5,17 +5,17 @@ // // You can create a new bundle for a specific trust domain: // -// td := spiffeid.RequireTrustDomain("example.org") +// td := spiffeid.RequireTrustDomainFromString("example.org") // bundle := x509bundle.New(td) // // Or you can load it from disk: // -// td := spiffeid.RequireTrustDomain("example.org") +// td := spiffeid.RequireTrustDomainFromString("example.org") // bundle := x509bundle.Load(td, "bundle.pem") // // The bundle can be initialized with X.509 authorities: // -// td := spiffeid.RequireTrustDomain("example.org") +// td := spiffeid.RequireTrustDomainFromString("example.org") // var x509Authorities []*x509.Certificate = ... // bundle := x509bundle.FromX509Authorities(td, x509Authorities) // diff --git a/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/addr.go b/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/addr.go index 6ce0238fe4..a0039b114c 100644 --- a/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/addr.go +++ b/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/addr.go @@ -22,13 +22,13 @@ func GetDefaultAddress() (string, bool) { // a Workload API endpoint exposed as either a Unix // Domain Socket or TCP socket. func ValidateAddress(addr string) error { - _, err := parseTargetFromStringAddr(addr) + _, err := TargetFromAddress(addr) return err } -// parseTargetFromStringAddr parses the endpoint address and returns a gRPC target +// TargetFromAddress parses the endpoint address and returns a gRPC target // string for dialing. -func parseTargetFromStringAddr(addr string) (string, error) { +func TargetFromAddress(addr string) (string, error) { u, err := url.Parse(addr) if err != nil { return "", errors.New("workload endpoint socket is not a valid URI: " + err.Error()) diff --git a/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/backoff.go b/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/backoff.go index b6ef1ed53f..5ff9126128 100644 --- a/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/backoff.go +++ b/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/backoff.go @@ -5,30 +5,51 @@ import ( "time" ) -// backoff defines an linear backoff policy. -type backoff struct { - InitialDelay time.Duration - MaxDelay time.Duration +// BackoffStrategy provides backoff facilities. +type BackoffStrategy interface { + // NewBackoff returns a new backoff for the strategy. The returned + // Backoff is in the same state that it would be in after a call to + // Reset(). + NewBackoff() Backoff +} + +// Backoff provides backoff for a workload API operation. +type Backoff interface { + // Next returns the next backoff period. + Next() time.Duration + + // Reset() resets the backoff. + Reset() +} + +type defaultBackoffStrategy struct{} + +func (defaultBackoffStrategy) NewBackoff() Backoff { + return newLinearBackoff() +} + +// linearBackoff defines an linear backoff policy. +type linearBackoff struct { + initialDelay time.Duration + maxDelay time.Duration n int } -func newBackoff() *backoff { - return &backoff{ - InitialDelay: time.Second, - MaxDelay: 30 * time.Second, +func newLinearBackoff() *linearBackoff { + return &linearBackoff{ + initialDelay: time.Second, + maxDelay: 30 * time.Second, n: 0, } } -// Duration returns the next wait period for the backoff. Not goroutine-safe. -func (b *backoff) Duration() time.Duration { +func (b *linearBackoff) Next() time.Duration { backoff := float64(b.n) + 1 - d := math.Min(b.InitialDelay.Seconds()*backoff, b.MaxDelay.Seconds()) + d := math.Min(b.initialDelay.Seconds()*backoff, b.maxDelay.Seconds()) b.n++ return time.Duration(d) * time.Second } -// Reset resets the backoff's state. -func (b *backoff) Reset() { +func (b *linearBackoff) Reset() { b.n = 0 } diff --git a/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/client.go b/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/client.go index 4d5de5d59f..7739798b5d 100644 --- a/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/client.go +++ b/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/client.go @@ -119,7 +119,7 @@ func (c *Client) FetchX509Bundles(ctx context.Context) (*x509bundle.Set, error) // WatchX509Bundles watches for changes to the X.509 bundles. The watcher receives // the updated X.509 bundles. func (c *Client) WatchX509Bundles(ctx context.Context, watcher X509BundleWatcher) error { - backoff := newBackoff() + backoff := c.config.backoffStrategy.NewBackoff() for { err := c.watchX509Bundles(ctx, watcher, backoff) watcher.OnX509BundlesWatchError(err) @@ -152,7 +152,7 @@ func (c *Client) FetchX509Context(ctx context.Context) (*X509Context, error) { // WatchX509Context watches for updates to the X.509 context. The watcher // receives the updated X.509 context. func (c *Client) WatchX509Context(ctx context.Context, watcher X509ContextWatcher) error { - backoff := newBackoff() + backoff := c.config.backoffStrategy.NewBackoff() for { err := c.watchX509Context(ctx, watcher, backoff) watcher.OnX509ContextWatchError(err) @@ -224,7 +224,7 @@ func (c *Client) FetchJWTBundles(ctx context.Context) (*jwtbundle.Set, error) { // WatchJWTBundles watches for changes to the JWT bundles. The watcher receives // the updated JWT bundles. func (c *Client) WatchJWTBundles(ctx context.Context, watcher JWTBundleWatcher) error { - backoff := newBackoff() + backoff := c.config.backoffStrategy.NewBackoff() for { err := c.watchJWTBundles(ctx, watcher, backoff) watcher.OnJWTBundlesWatchError(err) @@ -258,7 +258,7 @@ func (c *Client) newConn(ctx context.Context) (*grpc.ClientConn, error) { return grpc.DialContext(ctx, c.config.address, c.config.dialOptions...) //nolint:staticcheck // preserve backcompat with WithDialOptions option } -func (c *Client) handleWatchError(ctx context.Context, err error, backoff *backoff) error { +func (c *Client) handleWatchError(ctx context.Context, err error, backoff Backoff) error { code := status.Code(err) if code == codes.Canceled { return err @@ -270,7 +270,7 @@ func (c *Client) handleWatchError(ctx context.Context, err error, backoff *backo } c.config.log.Errorf("Failed to watch the Workload API: %v", err) - retryAfter := backoff.Duration() + retryAfter := backoff.Next() c.config.log.Debugf("Retrying watch in %s", retryAfter) select { case <-time.After(retryAfter): @@ -281,7 +281,7 @@ func (c *Client) handleWatchError(ctx context.Context, err error, backoff *backo } } -func (c *Client) watchX509Context(ctx context.Context, watcher X509ContextWatcher, backoff *backoff) error { +func (c *Client) watchX509Context(ctx context.Context, watcher X509ContextWatcher, backoff Backoff) error { ctx, cancel := context.WithCancel(withHeader(ctx)) defer cancel() @@ -308,7 +308,7 @@ func (c *Client) watchX509Context(ctx context.Context, watcher X509ContextWatche } } -func (c *Client) watchJWTBundles(ctx context.Context, watcher JWTBundleWatcher, backoff *backoff) error { +func (c *Client) watchJWTBundles(ctx context.Context, watcher JWTBundleWatcher, backoff Backoff) error { ctx, cancel := context.WithCancel(withHeader(ctx)) defer cancel() @@ -335,7 +335,7 @@ func (c *Client) watchJWTBundles(ctx context.Context, watcher JWTBundleWatcher, } } -func (c *Client) watchX509Bundles(ctx context.Context, watcher X509BundleWatcher, backoff *backoff) error { +func (c *Client) watchX509Bundles(ctx context.Context, watcher X509BundleWatcher, backoff Backoff) error { ctx, cancel := context.WithCancel(withHeader(ctx)) defer cancel() @@ -402,7 +402,8 @@ func withHeader(ctx context.Context) context.Context { func defaultClientConfig() clientConfig { return clientConfig{ - log: logger.Null, + log: logger.Null, + backoffStrategy: defaultBackoffStrategy{}, } } diff --git a/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/client_posix.go b/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/client_posix.go index 8e91a28fa4..58738b42e4 100644 --- a/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/client_posix.go +++ b/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/client_posix.go @@ -24,6 +24,6 @@ func (c *Client) setAddress() error { } var err error - c.config.address, err = parseTargetFromStringAddr(c.config.address) + c.config.address, err = TargetFromAddress(c.config.address) return err } diff --git a/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/client_windows.go b/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/client_windows.go index fb628fccc1..0a14266682 100644 --- a/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/client_windows.go +++ b/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/client_windows.go @@ -45,7 +45,7 @@ func (c *Client) setAddress() error { c.config.dialOptions = append(c.config.dialOptions, grpc.WithContextDialer(winio.DialPipeContext)) } - c.config.address, err = parseTargetFromStringAddr(c.config.address) + c.config.address, err = TargetFromAddress(c.config.address) return err } diff --git a/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/jwtsource.go b/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/jwtsource.go index 47ea83ade5..1122353903 100644 --- a/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/jwtsource.go +++ b/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/jwtsource.go @@ -16,6 +16,7 @@ var jwtsourceErr = errs.Class("jwtsource") // Workload API. type JWTSource struct { watcher *watcher + picker func([]*jwtsvid.SVID) *jwtsvid.SVID mtx sync.RWMutex bundles *jwtbundle.Set @@ -33,7 +34,9 @@ func NewJWTSource(ctx context.Context, options ...JWTSourceOption) (_ *JWTSource option.configureJWTSource(config) } - s := &JWTSource{} + s := &JWTSource{ + picker: config.picker, + } s.watcher, err = newWatcher(ctx, config.watcher, nil, s.setJWTBundles) if err != nil { @@ -61,7 +64,22 @@ func (s *JWTSource) FetchJWTSVID(ctx context.Context, params jwtsvid.Params) (*j if err := s.checkClosed(); err != nil { return nil, err } - return s.watcher.client.FetchJWTSVID(ctx, params) + + var ( + svid *jwtsvid.SVID + err error + ) + if s.picker == nil { + svid, err = s.watcher.client.FetchJWTSVID(ctx, params) + } else { + svids, err := s.watcher.client.FetchJWTSVIDs(ctx, params) + if err != nil { + return svid, err + } + svid = s.picker(svids) + } + + return svid, err } // FetchJWTSVIDs fetches all JWT-SVIDs from the source with the given parameters. diff --git a/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/option.go b/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/option.go index 00cab7d16c..f596f30c46 100644 --- a/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/option.go +++ b/vendor/github.com/spiffe/go-spiffe/v2/workloadapi/option.go @@ -2,6 +2,7 @@ package workloadapi import ( "github.com/spiffe/go-spiffe/v2/logger" + "github.com/spiffe/go-spiffe/v2/svid/jwtsvid" "github.com/spiffe/go-spiffe/v2/svid/x509svid" "google.golang.org/grpc" ) @@ -35,6 +36,14 @@ func WithLogger(logger logger.Logger) ClientOption { }) } +// WithBackoff provides a custom backoff strategy that replaces the +// default backoff strategy (linear backoff). +func WithBackoffStrategy(backoffStrategy BackoffStrategy) ClientOption { + return clientOption(func(c *clientConfig) { + c.backoffStrategy = backoffStrategy + }) +} + // SourceOption are options that are shared among all option types. type SourceOption interface { configureX509Source(*x509SourceConfig) @@ -60,12 +69,12 @@ type X509SourceOption interface { configureX509Source(*x509SourceConfig) } -// WithDefaultX509SVIDPicker provides a function that is used to determine the -// default X509-SVID when more than one is provided by the Workload API. By -// default, the first X509-SVID in the list returned by the Workload API is +// WithDefaultJWTSVIDPicker provides a function that is used to determine the +// default JWT-SVID when more than one is provided by the Workload API. By +// default, the first JWT-SVID in the list returned by the Workload API is // used. -func WithDefaultX509SVIDPicker(picker func([]*x509svid.SVID) *x509svid.SVID) X509SourceOption { - return withDefaultX509SVIDPicker{picker: picker} +func WithDefaultJWTSVIDPicker(picker func([]*jwtsvid.SVID) *jwtsvid.SVID) JWTSourceOption { + return withDefaultJWTSVIDPicker{picker: picker} } // JWTSourceOption is an option for the JWTSource. A SourceOption is also a @@ -74,6 +83,14 @@ type JWTSourceOption interface { configureJWTSource(*jwtSourceConfig) } +// WithDefaultX509SVIDPicker provides a function that is used to determine the +// default X509-SVID when more than one is provided by the Workload API. By +// default, the first X509-SVID in the list returned by the Workload API is +// used. +func WithDefaultX509SVIDPicker(picker func([]*x509svid.SVID) *x509svid.SVID) X509SourceOption { + return withDefaultX509SVIDPicker{picker: picker} +} + // BundleSourceOption is an option for the BundleSource. A SourceOption is also // a BundleSourceOption. type BundleSourceOption interface { @@ -81,10 +98,11 @@ type BundleSourceOption interface { } type clientConfig struct { - address string - namedPipeName string - dialOptions []grpc.DialOption - log logger.Logger + address string + namedPipeName string + dialOptions []grpc.DialOption + log logger.Logger + backoffStrategy BackoffStrategy } type clientOption func(*clientConfig) @@ -100,6 +118,7 @@ type x509SourceConfig struct { type jwtSourceConfig struct { watcher watcherConfig + picker func([]*jwtsvid.SVID) *jwtsvid.SVID } type bundleSourceConfig struct { @@ -145,3 +164,11 @@ type withDefaultX509SVIDPicker struct { func (o withDefaultX509SVIDPicker) configureX509Source(config *x509SourceConfig) { config.picker = o.picker } + +type withDefaultJWTSVIDPicker struct { + picker func([]*jwtsvid.SVID) *jwtsvid.SVID +} + +func (o withDefaultJWTSVIDPicker) configureJWTSource(config *jwtSourceConfig) { + config.picker = o.picker +} diff --git a/vendor/github.com/theupdateframework/go-tuf/v2/metadata/updater/updater.go b/vendor/github.com/theupdateframework/go-tuf/v2/metadata/updater/updater.go index 7194365012..1b9d21b860 100644 --- a/vendor/github.com/theupdateframework/go-tuf/v2/metadata/updater/updater.go +++ b/vendor/github.com/theupdateframework/go-tuf/v2/metadata/updater/updater.go @@ -443,8 +443,11 @@ func (update *Updater) loadTargets(roleName, parentName string) (*metadata.Metad if update.trusted.Snapshot == nil { return nil, fmt.Errorf("trusted snapshot not set") } - // extract the targets meta from the trusted snapshot metadata - metaInfo := update.trusted.Snapshot.Signed.Meta[fmt.Sprintf("%s.json", roleName)] + // extract the targets' meta from the trusted snapshot metadata + metaInfo, ok := update.trusted.Snapshot.Signed.Meta[fmt.Sprintf("%s.json", roleName)] + if !ok { + return nil, fmt.Errorf("role %s not found in snapshot", roleName) + } // extract the length of the target metadata to be downloaded length := metaInfo.Length if length == 0 { diff --git a/vendor/github.com/xanzy/go-gitlab/LICENSE b/vendor/github.com/xanzy/go-gitlab/LICENSE deleted file mode 100644 index 8dada3edaf..0000000000 --- a/vendor/github.com/xanzy/go-gitlab/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/xanzy/go-gitlab/README.md b/vendor/github.com/xanzy/go-gitlab/README.md deleted file mode 100644 index fa5a049a3b..0000000000 --- a/vendor/github.com/xanzy/go-gitlab/README.md +++ /dev/null @@ -1,208 +0,0 @@ -# go-gitlab - -A GitLab API client enabling Go programs to interact with GitLab in a simple and uniform way - -[![Build Status](https://github.com/xanzy/go-gitlab/workflows/Lint%20and%20Test/badge.svg)](https://github.com/xanzy/go-gitlab/actions?workflow=Lint%20and%20Test) -[![Sourcegraph](https://sourcegraph.com/github.com/xanzy/go-gitlab/-/badge.svg)](https://sourcegraph.com/github.com/xanzy/go-gitlab?badge) -[![GoDoc](https://godoc.org/github.com/xanzy/go-gitlab?status.svg)](https://godoc.org/github.com/xanzy/go-gitlab) -[![Go Report Card](https://goreportcard.com/badge/github.com/xanzy/go-gitlab)](https://goreportcard.com/report/github.com/xanzy/go-gitlab) -[![Coverage](https://github.com/xanzy/go-gitlab/wiki/coverage.svg)](https://raw.githack.com/wiki/xanzy/go-gitlab/coverage.html) - -## NOTE - -Release v0.6.0 (released on 25-08-2017) no longer supports the older V3 GitLab API. If -you need V3 support, please use the `f-api-v3` branch. This release contains some backwards -incompatible changes that were needed to fully support the V4 GitLab API. - -## Coverage - -This API client package covers most of the existing GitLab API calls and is updated regularly -to add new and/or missing endpoints. Currently, the following services are supported: - -- [x] Applications -- [x] Award Emojis -- [x] Branches -- [x] Broadcast Messages -- [x] Commits -- [x] Container Registry -- [x] Custom Attributes -- [x] Deploy Keys -- [x] Deployments -- [x] Discussions (threaded comments) -- [x] Environments -- [x] Epic Issues -- [x] Epics -- [x] Error Tracking -- [x] Events -- [x] Feature Flags -- [x] Geo Nodes -- [x] Generic Packages -- [x] GitLab CI Config Templates -- [x] Gitignores Templates -- [x] Group Access Requests -- [x] Group Issue Boards -- [x] Group Members -- [x] Group Milestones -- [x] Group Wikis -- [x] Group-Level Variables -- [x] Groups -- [x] Instance Clusters -- [x] Invites -- [x] Issue Boards -- [x] Issues -- [x] Jobs -- [x] Keys -- [x] Labels -- [x] License -- [x] Markdown -- [x] Merge Request Approvals -- [x] Merge Requests -- [x] Namespaces -- [x] Notes (comments) -- [x] Notification Settings -- [x] Open Source License Templates -- [x] Packages -- [x] Pages -- [x] Pages Domains -- [x] Personal Access Tokens -- [x] Pipeline Schedules -- [x] Pipeline Triggers -- [x] Pipelines -- [x] Plan limits -- [x] Project Access Requests -- [x] Project Badges -- [x] Project Clusters -- [x] Project Import/export -- [x] Project Members -- [x] Project Milestones -- [x] Project Repository Storage Moves -- [x] Project Snippets -- [x] Project Vulnerabilities -- [x] Project-Level Variables -- [x] Projects (including setting Webhooks) -- [x] Protected Branches -- [x] Protected Environments -- [x] Protected Tags -- [x] Repositories -- [x] Repository Files -- [x] Repository Submodules -- [x] Runners -- [x] Search -- [x] Services -- [x] Settings -- [x] Sidekiq Metrics -- [x] System Hooks -- [x] Tags -- [x] Todos -- [x] Topics -- [x] Users -- [x] Validate CI Configuration -- [x] Version -- [x] Wikis - -## Usage - -```go -import "github.com/xanzy/go-gitlab" -``` - -Construct a new GitLab client, then use the various services on the client to -access different parts of the GitLab API. For example, to list all -users: - -```go -git, err := gitlab.NewClient("yourtokengoeshere") -if err != nil { - log.Fatalf("Failed to create client: %v", err) -} -users, _, err := git.Users.ListUsers(&gitlab.ListUsersOptions{}) -``` - -There are a few `With...` option functions that can be used to customize -the API client. For example, to set a custom base URL: - -```go -git, err := gitlab.NewClient("yourtokengoeshere", gitlab.WithBaseURL("https://git.mydomain.com/api/v4")) -if err != nil { - log.Fatalf("Failed to create client: %v", err) -} -users, _, err := git.Users.ListUsers(&gitlab.ListUsersOptions{}) -``` - -Some API methods have optional parameters that can be passed. For example, -to list all projects for user "svanharmelen": - -```go -git := gitlab.NewClient("yourtokengoeshere") -opt := &gitlab.ListProjectsOptions{Search: gitlab.Ptr("svanharmelen")} -projects, _, err := git.Projects.ListProjects(opt) -``` - -### Examples - -The [examples](https://github.com/xanzy/go-gitlab/tree/master/examples) directory -contains a couple for clear examples, of which one is partially listed here as well: - -```go -package main - -import ( - "log" - - "github.com/xanzy/go-gitlab" -) - -func main() { - git, err := gitlab.NewClient("yourtokengoeshere") - if err != nil { - log.Fatalf("Failed to create client: %v", err) - } - - // Create new project - p := &gitlab.CreateProjectOptions{ - Name: gitlab.Ptr("My Project"), - Description: gitlab.Ptr("Just a test project to play with"), - MergeRequestsAccessLevel: gitlab.Ptr(gitlab.EnabledAccessControl), - SnippetsAccessLevel: gitlab.Ptr(gitlab.EnabledAccessControl), - Visibility: gitlab.Ptr(gitlab.PublicVisibility), - } - project, _, err := git.Projects.CreateProject(p) - if err != nil { - log.Fatal(err) - } - - // Add a new snippet - s := &gitlab.CreateProjectSnippetOptions{ - Title: gitlab.Ptr("Dummy Snippet"), - FileName: gitlab.Ptr("snippet.go"), - Content: gitlab.Ptr("package main...."), - Visibility: gitlab.Ptr(gitlab.PublicVisibility), - } - _, _, err = git.ProjectSnippets.CreateSnippet(project.ID, s) - if err != nil { - log.Fatal(err) - } -} -``` - -For complete usage of go-gitlab, see the full [package docs](https://godoc.org/github.com/xanzy/go-gitlab). - -## ToDo - -- The biggest thing this package still needs is tests :disappointed: - -## Issues - -- If you have an issue: report it on the [issue tracker](https://github.com/xanzy/go-gitlab/issues) - -## Author - -Sander van Harmelen () - -## Contributing - -Contributions are always welcome. For more information, check out the [contributing guide](https://github.com/xanzy/go-gitlab/blob/master/CONTRIBUTING.md) - -## License - -Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at diff --git a/vendor/github.com/xanzy/go-gitlab/settings.go b/vendor/github.com/xanzy/go-gitlab/settings.go deleted file mode 100644 index f4d67a4f04..0000000000 --- a/vendor/github.com/xanzy/go-gitlab/settings.go +++ /dev/null @@ -1,965 +0,0 @@ -// -// Copyright 2021, Sander van Harmelen -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -package gitlab - -import ( - "encoding/json" - "net/http" - "time" -) - -// SettingsService handles communication with the application SettingsService -// related methods of the GitLab API. -// -// GitLab API docs: https://docs.gitlab.com/ee/api/settings.html -type SettingsService struct { - client *Client -} - -// Settings represents the GitLab application settings. -// -// GitLab API docs: https://docs.gitlab.com/ee/api/settings.html -// -// The available parameters have been modeled directly after the code, as the -// documentation seems to be inaccurate. -// -// https://gitlab.com/gitlab-org/gitlab/-/blob/v14.9.3-ee/lib/api/settings.rb -// https://gitlab.com/gitlab-org/gitlab/-/blob/v14.9.3-ee/lib/api/entities/application_setting.rb#L5 -// https://gitlab.com/gitlab-org/gitlab/-/blob/v14.9.3-ee/app/helpers/application_settings_helper.rb#L192 -// https://gitlab.com/gitlab-org/gitlab/-/blob/v14.9.3-ee/ee/lib/ee/api/helpers/settings_helpers.rb#L10 -// https://gitlab.com/gitlab-org/gitlab/-/blob/v14.9.3-ee/ee/app/helpers/ee/application_settings_helper.rb#L20 -type Settings struct { - ID int `json:"id"` - AbuseNotificationEmail string `json:"abuse_notification_email"` - AdminMode bool `json:"admin_mode"` - AfterSignOutPath string `json:"after_sign_out_path"` - AfterSignUpText string `json:"after_sign_up_text"` - AkismetAPIKey string `json:"akismet_api_key"` - AkismetEnabled bool `json:"akismet_enabled"` - AllowAccountDeletion bool `json:"allow_account_deletion"` - AllowGroupOwnersToManageLDAP bool `json:"allow_group_owners_to_manage_ldap"` - AllowLocalRequestsFromSystemHooks bool `json:"allow_local_requests_from_system_hooks"` - AllowLocalRequestsFromWebHooksAndServices bool `json:"allow_local_requests_from_web_hooks_and_services"` - AllowProjectCreationForGuestAndBelow bool `json:"allow_project_creation_for_guest_and_below"` - AllowRunnerRegistrationToken bool `json:"allow_runner_registration_token"` - ArchiveBuildsInHumanReadable string `json:"archive_builds_in_human_readable"` - ASCIIDocMaxIncludes int `json:"asciidoc_max_includes"` - AssetProxyAllowlist []string `json:"asset_proxy_allowlist"` - AssetProxyEnabled bool `json:"asset_proxy_enabled"` - AssetProxyURL string `json:"asset_proxy_url"` - AssetProxySecretKey string `json:"asset_proxy_secret_key"` - AuthorizedKeysEnabled bool `json:"authorized_keys_enabled"` - AutoBanUserOnExcessiveProjectsDownload bool `json:"auto_ban_user_on_excessive_projects_download"` - AutoDevOpsDomain string `json:"auto_devops_domain"` - AutoDevOpsEnabled bool `json:"auto_devops_enabled"` - AutomaticPurchasedStorageAllocation bool `json:"automatic_purchased_storage_allocation"` - BulkImportConcurrentPipelineBatchLimit int `json:"bulk_import_concurrent_pipeline_batch_limit"` - BulkImportEnabled bool `json:"bulk_import_enabled"` - BulkImportMaxDownloadFileSize int `json:"bulk_import_max_download_file_size"` - CanCreateGroup bool `json:"can_create_group"` - CheckNamespacePlan bool `json:"check_namespace_plan"` - CIMaxIncludes int `json:"ci_max_includes"` - CIMaxTotalYAMLSizeBytes int `json:"ci_max_total_yaml_size_bytes"` - CommitEmailHostname string `json:"commit_email_hostname"` - ConcurrentBitbucketImportJobsLimit int `json:"concurrent_bitbucket_import_jobs_limit"` - ConcurrentBitbucketServerImportJobsLimit int `json:"concurrent_bitbucket_server_import_jobs_limit"` - ConcurrentGitHubImportJobsLimit int `json:"concurrent_github_import_jobs_limit"` - ContainerExpirationPoliciesEnableHistoricEntries bool `json:"container_expiration_policies_enable_historic_entries"` - ContainerRegistryCleanupTagsServiceMaxListSize int `json:"container_registry_cleanup_tags_service_max_list_size"` - ContainerRegistryDeleteTagsServiceTimeout int `json:"container_registry_delete_tags_service_timeout"` - ContainerRegistryExpirationPoliciesCaching bool `json:"container_registry_expiration_policies_caching"` - ContainerRegistryExpirationPoliciesWorkerCapacity int `json:"container_registry_expiration_policies_worker_capacity"` - ContainerRegistryImportCreatedBefore *time.Time `json:"container_registry_import_created_before"` - ContainerRegistryImportMaxRetries int `json:"container_registry_import_max_retries"` - ContainerRegistryImportMaxStepDuration int `json:"container_registry_import_max_step_duration"` - ContainerRegistryImportMaxTagsCount int `json:"container_registry_import_max_tags_count"` - ContainerRegistryImportStartMaxRetries int `json:"container_registry_import_start_max_retries"` - ContainerRegistryImportTargetPlan string `json:"container_registry_import_target_plan"` - ContainerRegistryTokenExpireDelay int `json:"container_registry_token_expire_delay"` - CreatedAt *time.Time `json:"created_at"` - CustomHTTPCloneURLRoot string `json:"custom_http_clone_url_root"` - DNSRebindingProtectionEnabled bool `json:"dns_rebinding_protection_enabled"` - DSAKeyRestriction int `json:"dsa_key_restriction"` - DeactivateDormantUsers bool `json:"deactivate_dormant_users"` - DeactivateDormantUsersPeriod int `json:"deactivate_dormant_users_period"` - DecompressArchiveFileTimeout int `json:"decompress_archive_file_timeout"` - DefaultArtifactsExpireIn string `json:"default_artifacts_expire_in"` - DefaultBranchName string `json:"default_branch_name"` - DefaultBranchProtection int `json:"default_branch_protection"` - DefaultBranchProtectionDefaults BranchProtectionDefaults `json:"default_branch_protection_defaults,omitempty"` - DefaultCiConfigPath string `json:"default_ci_config_path"` - DefaultGroupVisibility VisibilityValue `json:"default_group_visibility"` - DefaultPreferredLanguage string `json:"default_preferred_language"` - DefaultProjectCreation int `json:"default_project_creation"` - DefaultProjectDeletionProtection bool `json:"default_project_deletion_protection"` - DefaultProjectVisibility VisibilityValue `json:"default_project_visibility"` - DefaultProjectsLimit int `json:"default_projects_limit"` - DefaultSnippetVisibility VisibilityValue `json:"default_snippet_visibility"` - DefaultSyntaxHighlightingTheme int `json:"default_syntax_highlighting_theme"` - DelayedGroupDeletion bool `json:"delayed_group_deletion"` - DelayedProjectDeletion bool `json:"delayed_project_deletion"` - DeleteInactiveProjects bool `json:"delete_inactive_projects"` - DeleteUnconfirmedUsers bool `json:"delete_unconfirmed_users"` - DeletionAdjournedPeriod int `json:"deletion_adjourned_period"` - DiagramsnetEnabled bool `json:"diagramsnet_enabled"` - DiagramsnetURL string `json:"diagramsnet_url"` - DiffMaxFiles int `json:"diff_max_files"` - DiffMaxLines int `json:"diff_max_lines"` - DiffMaxPatchBytes int `json:"diff_max_patch_bytes"` - DisableAdminOAuthScopes bool `json:"disable_admin_oauth_scopes"` - DisableFeedToken bool `json:"disable_feed_token"` - DisableOverridingApproversPerMergeRequest bool `json:"disable_overriding_approvers_per_merge_request"` - DisablePersonalAccessTokens bool `json:"disable_personal_access_tokens"` - DisabledOauthSignInSources []string `json:"disabled_oauth_sign_in_sources"` - DomainAllowlist []string `json:"domain_allowlist"` - DomainDenylist []string `json:"domain_denylist"` - DomainDenylistEnabled bool `json:"domain_denylist_enabled"` - DownstreamPipelineTriggerLimitPerProjectUserSHA int `json:"downstream_pipeline_trigger_limit_per_project_user_sha"` - DuoFeaturesEnabled bool `json:"duo_features_enabled"` - ECDSAKeyRestriction int `json:"ecdsa_key_restriction"` - ECDSASKKeyRestriction int `json:"ecdsa_sk_key_restriction"` - EKSAccessKeyID string `json:"eks_access_key_id"` - EKSAccountID string `json:"eks_account_id"` - EKSIntegrationEnabled bool `json:"eks_integration_enabled"` - EKSSecretAccessKey string `json:"eks_secret_access_key"` - Ed25519KeyRestriction int `json:"ed25519_key_restriction"` - Ed25519SKKeyRestriction int `json:"ed25519_sk_key_restriction"` - ElasticsearchAWS bool `json:"elasticsearch_aws"` - ElasticsearchAWSAccessKey string `json:"elasticsearch_aws_access_key"` - ElasticsearchAWSRegion string `json:"elasticsearch_aws_region"` - ElasticsearchAWSSecretAccessKey string `json:"elasticsearch_aws_secret_access_key"` - ElasticsearchAnalyzersKuromojiEnabled bool `json:"elasticsearch_analyzers_kuromoji_enabled"` - ElasticsearchAnalyzersKuromojiSearch bool `json:"elasticsearch_analyzers_kuromoji_search"` - ElasticsearchAnalyzersSmartCNEnabled bool `json:"elasticsearch_analyzers_smartcn_enabled"` - ElasticsearchAnalyzersSmartCNSearch bool `json:"elasticsearch_analyzers_smartcn_search"` - ElasticsearchClientRequestTimeout int `json:"elasticsearch_client_request_timeout"` - ElasticsearchIndexedFieldLengthLimit int `json:"elasticsearch_indexed_field_length_limit"` - ElasticsearchIndexedFileSizeLimitKB int `json:"elasticsearch_indexed_file_size_limit_kb"` - ElasticsearchIndexing bool `json:"elasticsearch_indexing"` - ElasticsearchLimitIndexing bool `json:"elasticsearch_limit_indexing"` - ElasticsearchMaxBulkConcurrency int `json:"elasticsearch_max_bulk_concurrency"` - ElasticsearchMaxBulkSizeMB int `json:"elasticsearch_max_bulk_size_mb"` - ElasticsearchMaxCodeIndexingConcurrency int `json:"elasticsearch_max_code_indexing_concurrency"` - ElasticsearchNamespaceIDs []int `json:"elasticsearch_namespace_ids"` - ElasticsearchPassword string `json:"elasticsearch_password"` - ElasticsearchPauseIndexing bool `json:"elasticsearch_pause_indexing"` - ElasticsearchProjectIDs []int `json:"elasticsearch_project_ids"` - ElasticsearchReplicas int `json:"elasticsearch_replicas"` - ElasticsearchRequeueWorkers bool `json:"elasticsearch_requeue_workers"` - ElasticsearchSearch bool `json:"elasticsearch_search"` - ElasticsearchShards int `json:"elasticsearch_shards"` - ElasticsearchURL []string `json:"elasticsearch_url"` - ElasticsearchUsername string `json:"elasticsearch_username"` - ElasticsearchWorkerNumberOfShards int `json:"elasticsearch_worker_number_of_shards"` - EmailAdditionalText string `json:"email_additional_text"` - EmailAuthorInBody bool `json:"email_author_in_body"` - EmailConfirmationSetting string `json:"email_confirmation_setting"` - EmailRestrictions string `json:"email_restrictions"` - EmailRestrictionsEnabled bool `json:"email_restrictions_enabled"` - EnableArtifactExternalRedirectWarningPage bool `json:"enable_artifact_external_redirect_warning_page"` - EnabledGitAccessProtocol string `json:"enabled_git_access_protocol"` - EnforceNamespaceStorageLimit bool `json:"enforce_namespace_storage_limit"` - EnforcePATExpiration bool `json:"enforce_pat_expiration"` - EnforceSSHKeyExpiration bool `json:"enforce_ssh_key_expiration"` - EnforceTerms bool `json:"enforce_terms"` - ExternalAuthClientCert string `json:"external_auth_client_cert"` - ExternalAuthClientKey string `json:"external_auth_client_key"` - ExternalAuthClientKeyPass string `json:"external_auth_client_key_pass"` - ExternalAuthorizationServiceDefaultLabel string `json:"external_authorization_service_default_label"` - ExternalAuthorizationServiceEnabled bool `json:"external_authorization_service_enabled"` - ExternalAuthorizationServiceTimeout float64 `json:"external_authorization_service_timeout"` - ExternalAuthorizationServiceURL string `json:"external_authorization_service_url"` - ExternalPipelineValidationServiceTimeout int `json:"external_pipeline_validation_service_timeout"` - ExternalPipelineValidationServiceToken string `json:"external_pipeline_validation_service_token"` - ExternalPipelineValidationServiceURL string `json:"external_pipeline_validation_service_url"` - FailedLoginAttemptsUnlockPeriodInMinutes int `json:"failed_login_attempts_unlock_period_in_minutes"` - FileTemplateProjectID int `json:"file_template_project_id"` - FirstDayOfWeek int `json:"first_day_of_week"` - FlocEnabled bool `json:"floc_enabled"` - GeoNodeAllowedIPs string `json:"geo_node_allowed_ips"` - GeoStatusTimeout int `json:"geo_status_timeout"` - GitRateLimitUsersAlertlist []string `json:"git_rate_limit_users_alertlist"` - GitTwoFactorSessionExpiry int `json:"git_two_factor_session_expiry"` - GitalyTimeoutDefault int `json:"gitaly_timeout_default"` - GitalyTimeoutFast int `json:"gitaly_timeout_fast"` - GitalyTimeoutMedium int `json:"gitaly_timeout_medium"` - GitlabDedicatedInstance bool `json:"gitlab_dedicated_instance"` - GitlabEnvironmentToolkitInstance bool `json:"gitlab_environment_toolkit_instance"` - GitlabShellOperationLimit int `json:"gitlab_shell_operation_limit"` - GitpodEnabled bool `json:"gitpod_enabled"` - GitpodURL string `json:"gitpod_url"` - GitRateLimitUsersAllowlist []string `json:"git_rate_limit_users_allowlist"` - GloballyAllowedIPs string `json:"globally_allowed_ips"` - GrafanaEnabled bool `json:"grafana_enabled"` - GrafanaURL string `json:"grafana_url"` - GravatarEnabled bool `json:"gravatar_enabled"` - GroupDownloadExportLimit int `json:"group_download_export_limit"` - GroupExportLimit int `json:"group_export_limit"` - GroupImportLimit int `json:"group_import_limit"` - GroupOwnersCanManageDefaultBranchProtection bool `json:"group_owners_can_manage_default_branch_protection"` - GroupRunnerTokenExpirationInterval int `json:"group_runner_token_expiration_interval"` - HTMLEmailsEnabled bool `json:"html_emails_enabled"` - HashedStorageEnabled bool `json:"hashed_storage_enabled"` - HelpPageDocumentationBaseURL string `json:"help_page_documentation_base_url"` - HelpPageHideCommercialContent bool `json:"help_page_hide_commercial_content"` - HelpPageSupportURL string `json:"help_page_support_url"` - HelpPageText string `json:"help_page_text"` - HelpText string `json:"help_text"` - HideThirdPartyOffers bool `json:"hide_third_party_offers"` - HomePageURL string `json:"home_page_url"` - HousekeepingBitmapsEnabled bool `json:"housekeeping_bitmaps_enabled"` - HousekeepingEnabled bool `json:"housekeeping_enabled"` - HousekeepingFullRepackPeriod int `json:"housekeeping_full_repack_period"` - HousekeepingGcPeriod int `json:"housekeeping_gc_period"` - HousekeepingIncrementalRepackPeriod int `json:"housekeeping_incremental_repack_period"` - HousekeepingOptimizeRepositoryPeriod int `json:"housekeeping_optimize_repository_period"` - ImportSources []string `json:"import_sources"` - InactiveProjectsDeleteAfterMonths int `json:"inactive_projects_delete_after_months"` - InactiveProjectsMinSizeMB int `json:"inactive_projects_min_size_mb"` - InactiveProjectsSendWarningEmailAfterMonths int `json:"inactive_projects_send_warning_email_after_months"` - IncludeOptionalMetricsInServicePing bool `json:"include_optional_metrics_in_service_ping"` - InProductMarketingEmailsEnabled bool `json:"in_product_marketing_emails_enabled"` - InvisibleCaptchaEnabled bool `json:"invisible_captcha_enabled"` - IssuesCreateLimit int `json:"issues_create_limit"` - JiraConnectApplicationKey string `json:"jira_connect_application_key"` - JiraConnectPublicKeyStorageEnabled bool `json:"jira_connect_public_key_storage_enabled"` - JiraConnectProxyURL string `json:"jira_connect_proxy_url"` - KeepLatestArtifact bool `json:"keep_latest_artifact"` - KrokiEnabled bool `json:"kroki_enabled"` - KrokiFormats map[string]bool `json:"kroki_formats"` - KrokiURL string `json:"kroki_url"` - LocalMarkdownVersion int `json:"local_markdown_version"` - LockDuoFeaturesEnabled bool `json:"lock_duo_features_enabled"` - LockMembershipsToLDAP bool `json:"lock_memberships_to_ldap"` - LoginRecaptchaProtectionEnabled bool `json:"login_recaptcha_protection_enabled"` - MailgunEventsEnabled bool `json:"mailgun_events_enabled"` - MailgunSigningKey string `json:"mailgun_signing_key"` - MaintenanceMode bool `json:"maintenance_mode"` - MaintenanceModeMessage string `json:"maintenance_mode_message"` - MavenPackageRequestsForwarding bool `json:"maven_package_requests_forwarding"` - MaxArtifactsSize int `json:"max_artifacts_size"` - MaxAttachmentSize int `json:"max_attachment_size"` - MaxDecompressedArchiveSize int `json:"max_decompressed_archive_size"` - MaxExportSize int `json:"max_export_size"` - MaxImportRemoteFileSize int `json:"max_import_remote_file_size"` - MaxImportSize int `json:"max_import_size"` - MaxLoginAttempts int `json:"max_login_attempts"` - MaxNumberOfRepositoryDownloads int `json:"max_number_of_repository_downloads"` - MaxNumberOfRepositoryDownloadsWithinTimePeriod int `json:"max_number_of_repository_downloads_within_time_period"` - MaxPagesSize int `json:"max_pages_size"` - MaxPersonalAccessTokenLifetime int `json:"max_personal_access_token_lifetime"` - MaxSSHKeyLifetime int `json:"max_ssh_key_lifetime"` - MaxTerraformStateSizeBytes int `json:"max_terraform_state_size_bytes"` - MaxYAMLDepth int `json:"max_yaml_depth"` - MaxYAMLSizeBytes int `json:"max_yaml_size_bytes"` - MetricsMethodCallThreshold int `json:"metrics_method_call_threshold"` - MinimumPasswordLength int `json:"minimum_password_length"` - MirrorAvailable bool `json:"mirror_available"` - MirrorCapacityThreshold int `json:"mirror_capacity_threshold"` - MirrorMaxCapacity int `json:"mirror_max_capacity"` - MirrorMaxDelay int `json:"mirror_max_delay"` - NPMPackageRequestsForwarding bool `json:"npm_package_requests_forwarding"` - NotesCreateLimit int `json:"notes_create_limit"` - NotifyOnUnknownSignIn bool `json:"notify_on_unknown_sign_in"` - NugetSkipMetadataURLValidation bool `json:"nuget_skip_metadata_url_validation"` - OutboundLocalRequestsAllowlistRaw string `json:"outbound_local_requests_allowlist_raw"` - OutboundLocalRequestsWhitelist []string `json:"outbound_local_requests_whitelist"` - PackageMetadataPURLTypes []int `json:"package_metadata_purl_types"` - PackageRegistryAllowAnyoneToPullOption bool `json:"package_registry_allow_anyone_to_pull_option"` - PackageRegistryCleanupPoliciesWorkerCapacity int `json:"package_registry_cleanup_policies_worker_capacity"` - PagesDomainVerificationEnabled bool `json:"pages_domain_verification_enabled"` - PasswordAuthenticationEnabledForGit bool `json:"password_authentication_enabled_for_git"` - PasswordAuthenticationEnabledForWeb bool `json:"password_authentication_enabled_for_web"` - PasswordNumberRequired bool `json:"password_number_required"` - PasswordSymbolRequired bool `json:"password_symbol_required"` - PasswordUppercaseRequired bool `json:"password_uppercase_required"` - PasswordLowercaseRequired bool `json:"password_lowercase_required"` - PerformanceBarAllowedGroupID int `json:"performance_bar_allowed_group_id"` - PerformanceBarAllowedGroupPath string `json:"performance_bar_allowed_group_path"` - PerformanceBarEnabled bool `json:"performance_bar_enabled"` - PersonalAccessTokenPrefix string `json:"personal_access_token_prefix"` - PipelineLimitPerProjectUserSha int `json:"pipeline_limit_per_project_user_sha"` - PlantumlEnabled bool `json:"plantuml_enabled"` - PlantumlURL string `json:"plantuml_url"` - PollingIntervalMultiplier float64 `json:"polling_interval_multiplier,string"` - PreventMergeRequestsAuthorApproval bool `json:"prevent_merge_request_author_approval"` - PreventMergeRequestsCommittersApproval bool `json:"prevent_merge_request_committers_approval"` - ProjectDownloadExportLimit int `json:"project_download_export_limit"` - ProjectExportEnabled bool `json:"project_export_enabled"` - ProjectExportLimit int `json:"project_export_limit"` - ProjectImportLimit int `json:"project_import_limit"` - ProjectJobsAPIRateLimit int `json:"project_jobs_api_rate_limit"` - ProjectRunnerTokenExpirationInterval int `json:"project_runner_token_expiration_interval"` - ProjectsAPIRateLimitUnauthenticated int `json:"projects_api_rate_limit_unauthenticated"` - PrometheusMetricsEnabled bool `json:"prometheus_metrics_enabled"` - ProtectedCIVariables bool `json:"protected_ci_variables"` - PseudonymizerEnabled bool `json:"pseudonymizer_enabled"` - PushEventActivitiesLimit int `json:"push_event_activities_limit"` - PushEventHooksLimit int `json:"push_event_hooks_limit"` - PyPIPackageRequestsForwarding bool `json:"pypi_package_requests_forwarding"` - RSAKeyRestriction int `json:"rsa_key_restriction"` - RateLimitingResponseText string `json:"rate_limiting_response_text"` - RawBlobRequestLimit int `json:"raw_blob_request_limit"` - RecaptchaEnabled bool `json:"recaptcha_enabled"` - RecaptchaPrivateKey string `json:"recaptcha_private_key"` - RecaptchaSiteKey string `json:"recaptcha_site_key"` - ReceiveMaxInputSize int `json:"receive_max_input_size"` - ReceptiveClusterAgentsEnabled bool `json:"receptive_cluster_agents_enabled"` - RememberMeEnabled bool `json:"remember_me_enabled"` - RepositoryChecksEnabled bool `json:"repository_checks_enabled"` - RepositorySizeLimit int `json:"repository_size_limit"` - RepositoryStorages []string `json:"repository_storages"` - RepositoryStoragesWeighted map[string]int `json:"repository_storages_weighted"` - RequireAdminApprovalAfterUserSignup bool `json:"require_admin_approval_after_user_signup"` - RequireAdminTwoFactorAuthentication bool `json:"require_admin_two_factor_authentication"` - RequirePersonalAccessTokenExpiry bool `json:"require_personal_access_token_expiry"` - RequireTwoFactorAuthentication bool `json:"require_two_factor_authentication"` - RestrictedVisibilityLevels []VisibilityValue `json:"restricted_visibility_levels"` - RunnerTokenExpirationInterval int `json:"runner_token_expiration_interval"` - SearchRateLimit int `json:"search_rate_limit"` - SearchRateLimitUnauthenticated int `json:"search_rate_limit_unauthenticated"` - SecretDetectionRevocationTokenTypesURL string `json:"secret_detection_revocation_token_types_url"` - SecretDetectionTokenRevocationEnabled bool `json:"secret_detection_token_revocation_enabled"` - SecretDetectionTokenRevocationToken string `json:"secret_detection_token_revocation_token"` - SecretDetectionTokenRevocationURL string `json:"secret_detection_token_revocation_url"` - SecurityApprovalPoliciesLimit int `json:"security_approval_policies_limit"` - SecurityPolicyGlobalGroupApproversEnabled bool `json:"security_policy_global_group_approvers_enabled"` - SecurityTXTContent string `json:"security_txt_content"` - SendUserConfirmationEmail bool `json:"send_user_confirmation_email"` - SentryClientsideDSN string `json:"sentry_clientside_dsn"` - SentryDSN string `json:"sentry_dsn"` - SentryEnabled bool `json:"sentry_enabled"` - SentryEnvironment string `json:"sentry_environment"` - ServiceAccessTokensExpirationEnforced bool `json:"service_access_tokens_expiration_enforced"` - SessionExpireDelay int `json:"session_expire_delay"` - SharedRunnersEnabled bool `json:"shared_runners_enabled"` - SharedRunnersMinutes int `json:"shared_runners_minutes"` - SharedRunnersText string `json:"shared_runners_text"` - SidekiqJobLimiterCompressionThresholdBytes int `json:"sidekiq_job_limiter_compression_threshold_bytes"` - SidekiqJobLimiterLimitBytes int `json:"sidekiq_job_limiter_limit_bytes"` - SidekiqJobLimiterMode string `json:"sidekiq_job_limiter_mode"` - SignInText string `json:"sign_in_text"` - SignupEnabled bool `json:"signup_enabled"` - SilentAdminExportsEnabled bool `json:"silent_admin_exports_enabled"` - SilentModeEnabled bool `json:"silent_mode_enabled"` - SlackAppEnabled bool `json:"slack_app_enabled"` - SlackAppID string `json:"slack_app_id"` - SlackAppSecret string `json:"slack_app_secret"` - SlackAppSigningSecret string `json:"slack_app_signing_secret"` - SlackAppVerificationToken string `json:"slack_app_verification_token"` - SnippetSizeLimit int `json:"snippet_size_limit"` - SnowplowAppID string `json:"snowplow_app_id"` - SnowplowCollectorHostname string `json:"snowplow_collector_hostname"` - SnowplowCookieDomain string `json:"snowplow_cookie_domain"` - SnowplowDatabaseCollectorHostname string `json:"snowplow_database_collector_hostname"` - SnowplowEnabled bool `json:"snowplow_enabled"` - SourcegraphEnabled bool `json:"sourcegraph_enabled"` - SourcegraphPublicOnly bool `json:"sourcegraph_public_only"` - SourcegraphURL string `json:"sourcegraph_url"` - SpamCheckAPIKey string `json:"spam_check_api_key"` - SpamCheckEndpointEnabled bool `json:"spam_check_endpoint_enabled"` - SpamCheckEndpointURL string `json:"spam_check_endpoint_url"` - StaticObjectsExternalStorageAuthToken string `json:"static_objects_external_storage_auth_token"` - StaticObjectsExternalStorageURL string `json:"static_objects_external_storage_url"` - SuggestPipelineEnabled bool `json:"suggest_pipeline_enabled"` - TerminalMaxSessionTime int `json:"terminal_max_session_time"` - Terms string `json:"terms"` - ThrottleAuthenticatedAPIEnabled bool `json:"throttle_authenticated_api_enabled"` - ThrottleAuthenticatedAPIPeriodInSeconds int `json:"throttle_authenticated_api_period_in_seconds"` - ThrottleAuthenticatedAPIRequestsPerPeriod int `json:"throttle_authenticated_api_requests_per_period"` - ThrottleAuthenticatedDeprecatedAPIEnabled bool `json:"throttle_authenticated_deprecated_api_enabled"` - ThrottleAuthenticatedDeprecatedAPIPeriodInSeconds int `json:"throttle_authenticated_deprecated_api_period_in_seconds"` - ThrottleAuthenticatedDeprecatedAPIRequestsPerPeriod int `json:"throttle_authenticated_deprecated_api_requests_per_period"` - ThrottleAuthenticatedFilesAPIEnabled bool `json:"throttle_authenticated_files_api_enabled"` - ThrottleAuthenticatedFilesAPIPeriodInSeconds int `json:"throttle_authenticated_files_api_period_in_seconds"` - ThrottleAuthenticatedFilesAPIRequestsPerPeriod int `json:"throttle_authenticated_files_api_requests_per_period"` - ThrottleAuthenticatedGitLFSEnabled bool `json:"throttle_authenticated_git_lfs_enabled"` - ThrottleAuthenticatedGitLFSPeriodInSeconds int `json:"throttle_authenticated_git_lfs_period_in_seconds"` - ThrottleAuthenticatedGitLFSRequestsPerPeriod int `json:"throttle_authenticated_git_lfs_requests_per_period"` - ThrottleAuthenticatedPackagesAPIEnabled bool `json:"throttle_authenticated_packages_api_enabled"` - ThrottleAuthenticatedPackagesAPIPeriodInSeconds int `json:"throttle_authenticated_packages_api_period_in_seconds"` - ThrottleAuthenticatedPackagesAPIRequestsPerPeriod int `json:"throttle_authenticated_packages_api_requests_per_period"` - ThrottleAuthenticatedWebEnabled bool `json:"throttle_authenticated_web_enabled"` - ThrottleAuthenticatedWebPeriodInSeconds int `json:"throttle_authenticated_web_period_in_seconds"` - ThrottleAuthenticatedWebRequestsPerPeriod int `json:"throttle_authenticated_web_requests_per_period"` - ThrottleIncidentManagementNotificationEnabled bool `json:"throttle_incident_management_notification_enabled"` - ThrottleIncidentManagementNotificationPerPeriod int `json:"throttle_incident_management_notification_per_period"` - ThrottleIncidentManagementNotificationPeriodInSeconds int `json:"throttle_incident_management_notification_period_in_seconds"` - ThrottleProtectedPathsEnabled bool `json:"throttle_protected_paths_enabled"` - ThrottleProtectedPathsPeriodInSeconds int `json:"throttle_protected_paths_period_in_seconds"` - ThrottleProtectedPathsRequestsPerPeriod int `json:"throttle_protected_paths_requests_per_period"` - ThrottleUnauthenticatedAPIEnabled bool `json:"throttle_unauthenticated_api_enabled"` - ThrottleUnauthenticatedAPIPeriodInSeconds int `json:"throttle_unauthenticated_api_period_in_seconds"` - ThrottleUnauthenticatedAPIRequestsPerPeriod int `json:"throttle_unauthenticated_api_requests_per_period"` - ThrottleUnauthenticatedDeprecatedAPIEnabled bool `json:"throttle_unauthenticated_deprecated_api_enabled"` - ThrottleUnauthenticatedDeprecatedAPIPeriodInSeconds int `json:"throttle_unauthenticated_deprecated_api_period_in_seconds"` - ThrottleUnauthenticatedDeprecatedAPIRequestsPerPeriod int `json:"throttle_unauthenticated_deprecated_api_requests_per_period"` - ThrottleUnauthenticatedFilesAPIEnabled bool `json:"throttle_unauthenticated_files_api_enabled"` - ThrottleUnauthenticatedFilesAPIPeriodInSeconds int `json:"throttle_unauthenticated_files_api_period_in_seconds"` - ThrottleUnauthenticatedFilesAPIRequestsPerPeriod int `json:"throttle_unauthenticated_files_api_requests_per_period"` - ThrottleUnauthenticatedGitLFSEnabled bool `json:"throttle_unauthenticated_git_lfs_enabled"` - ThrottleUnauthenticatedGitLFSPeriodInSeconds int `json:"throttle_unauthenticated_git_lfs_period_in_seconds"` - ThrottleUnauthenticatedGitLFSRequestsPerPeriod int `json:"throttle_unauthenticated_git_lfs_requests_per_period"` - ThrottleUnauthenticatedPackagesAPIEnabled bool `json:"throttle_unauthenticated_packages_api_enabled"` - ThrottleUnauthenticatedPackagesAPIPeriodInSeconds int `json:"throttle_unauthenticated_packages_api_period_in_seconds"` - ThrottleUnauthenticatedPackagesAPIRequestsPerPeriod int `json:"throttle_unauthenticated_packages_api_requests_per_period"` - ThrottleUnauthenticatedWebEnabled bool `json:"throttle_unauthenticated_web_enabled"` - ThrottleUnauthenticatedWebPeriodInSeconds int `json:"throttle_unauthenticated_web_period_in_seconds"` - ThrottleUnauthenticatedWebRequestsPerPeriod int `json:"throttle_unauthenticated_web_requests_per_period"` - TimeTrackingLimitToHours bool `json:"time_tracking_limit_to_hours"` - TwoFactorGracePeriod int `json:"two_factor_grace_period"` - UnconfirmedUsersDeleteAfterDays int `json:"unconfirmed_users_delete_after_days"` - UniqueIPsLimitEnabled bool `json:"unique_ips_limit_enabled"` - UniqueIPsLimitPerUser int `json:"unique_ips_limit_per_user"` - UniqueIPsLimitTimeWindow int `json:"unique_ips_limit_time_window"` - UpdateRunnerVersionsEnabled bool `json:"update_runner_versions_enabled"` - UpdatedAt *time.Time `json:"updated_at"` - UpdatingNameDisabledForUsers bool `json:"updating_name_disabled_for_users"` - UsagePingEnabled bool `json:"usage_ping_enabled"` - UsagePingFeaturesEnabled bool `json:"usage_ping_features_enabled"` - UseClickhouseForAnalytics bool `json:"use_clickhouse_for_analytics"` - UserDeactivationEmailsEnabled bool `json:"user_deactivation_emails_enabled"` - UserDefaultExternal bool `json:"user_default_external"` - UserDefaultInternalRegex string `json:"user_default_internal_regex"` - UserDefaultsToPrivateProfile bool `json:"user_defaults_to_private_profile"` - UserOauthApplications bool `json:"user_oauth_applications"` - UserShowAddSSHKeyMessage bool `json:"user_show_add_ssh_key_message"` - UsersGetByIDLimit int `json:"users_get_by_id_limit"` - UsersGetByIDLimitAllowlistRaw string `json:"users_get_by_id_limit_allowlist_raw"` - ValidRunnerRegistrars []string `json:"valid_runner_registrars"` - VersionCheckEnabled bool `json:"version_check_enabled"` - WebIDEClientsidePreviewEnabled bool `json:"web_ide_clientside_preview_enabled"` - WhatsNewVariant string `json:"whats_new_variant"` - WikiPageMaxContentBytes int `json:"wiki_page_max_content_bytes"` - - // Deprecated: Use AbuseNotificationEmail instead. - AdminNotificationEmail string `json:"admin_notification_email"` - // Deprecated: Use AllowLocalRequestsFromWebHooksAndServices instead. - AllowLocalRequestsFromHooksAndServices bool `json:"allow_local_requests_from_hooks_and_services"` - // Deprecated: Use AssetProxyAllowlist instead. - AssetProxyWhitelist []string `json:"asset_proxy_whitelist"` - // Deprecated: Use ThrottleUnauthenticatedWebEnabled or ThrottleUnauthenticatedAPIEnabled instead. (Deprecated in GitLab 14.3) - ThrottleUnauthenticatedEnabled bool `json:"throttle_unauthenticated_enabled"` - // Deprecated: Use ThrottleUnauthenticatedWebPeriodInSeconds or ThrottleUnauthenticatedAPIPeriodInSeconds instead. (Deprecated in GitLab 14.3) - ThrottleUnauthenticatedPeriodInSeconds int `json:"throttle_unauthenticated_period_in_seconds"` - // Deprecated: Use ThrottleUnauthenticatedWebRequestsPerPeriod or ThrottleUnauthenticatedAPIRequestsPerPeriod instead. (Deprecated in GitLab 14.3) - ThrottleUnauthenticatedRequestsPerPeriod int `json:"throttle_unauthenticated_requests_per_period"` - // Deprecated: Replaced by SearchRateLimit in GitLab 14.9 (removed in 15.0). - UserEmailLookupLimit int `json:"user_email_lookup_limit"` -} - -// BranchProtectionDefaults represents default Git protected branch permissions. -// -// GitLab API docs: -// https://docs.gitlab.com/ee/api/groups.html#options-for-default_branch_protection_defaults -type BranchProtectionDefaults struct { - AllowedToPush []int `json:"allowed_to_push,omitempty"` - AllowForcePush bool `json:"allow_force_push,omitempty"` - AllowedToMerge []int `json:"allowed_to_merge,omitempty"` - DeveloperCanInitialPush bool `json:"developer_can_initial_push,omitempty"` -} - -// Settings requires a custom unmarshaller in order to properly unmarshal -// `container_registry_import_created_before` which is either a time.Time or -// an empty string if no value is set. -func (s *Settings) UnmarshalJSON(data []byte) error { - type Alias Settings - - raw := make(map[string]interface{}) - err := json.Unmarshal(data, &raw) - if err != nil { - return err - } - - // If empty string, remove the value to leave it nil in the response. - if v, ok := raw["container_registry_import_created_before"]; ok && v == "" { - delete(raw, "container_registry_import_created_before") - - data, err = json.Marshal(raw) - if err != nil { - return err - } - } - - return json.Unmarshal(data, (*Alias)(s)) -} - -func (s Settings) String() string { - return Stringify(s) -} - -// GetSettings gets the current application settings. -// -// GitLab API docs: -// https://docs.gitlab.com/ee/api/settings.html#get-current-application-settings -func (s *SettingsService) GetSettings(options ...RequestOptionFunc) (*Settings, *Response, error) { - req, err := s.client.NewRequest(http.MethodGet, "application/settings", nil, options) - if err != nil { - return nil, nil, err - } - - as := new(Settings) - resp, err := s.client.Do(req, as) - if err != nil { - return nil, resp, err - } - - return as, resp, nil -} - -// UpdateSettingsOptions represents the available UpdateSettings() options. -// -// GitLab API docs: -// https://docs.gitlab.com/ee/api/settings.html#change-application-settings -type UpdateSettingsOptions struct { - AbuseNotificationEmail *string `url:"abuse_notification_email,omitempty" json:"abuse_notification_email,omitempty"` - AdminMode *bool `url:"admin_mode,omitempty" json:"admin_mode,omitempty"` - AdminNotificationEmail *string `url:"admin_notification_email,omitempty" json:"admin_notification_email,omitempty"` - AfterSignOutPath *string `url:"after_sign_out_path,omitempty" json:"after_sign_out_path,omitempty"` - AfterSignUpText *string `url:"after_sign_up_text,omitempty" json:"after_sign_up_text,omitempty"` - AkismetAPIKey *string `url:"akismet_api_key,omitempty" json:"akismet_api_key,omitempty"` - AkismetEnabled *bool `url:"akismet_enabled,omitempty" json:"akismet_enabled,omitempty"` - AllowAccountDeletion *bool `url:"allow_account_deletion,omitempty" json:"allow_account_deletion,omitempty"` - AllowGroupOwnersToManageLDAP *bool `url:"allow_group_owners_to_manage_ldap,omitempty" json:"allow_group_owners_to_manage_ldap,omitempty"` - AllowLocalRequestsFromHooksAndServices *bool `url:"allow_local_requests_from_hooks_and_services,omitempty" json:"allow_local_requests_from_hooks_and_services,omitempty"` - AllowLocalRequestsFromSystemHooks *bool `url:"allow_local_requests_from_system_hooks,omitempty" json:"allow_local_requests_from_system_hooks,omitempty"` - AllowLocalRequestsFromWebHooksAndServices *bool `url:"allow_local_requests_from_web_hooks_and_services,omitempty" json:"allow_local_requests_from_web_hooks_and_services,omitempty"` - AllowProjectCreationForGuestAndBelow *bool `url:"allow_project_creation_for_guest_and_below,omitempty" json:"allow_project_creation_for_guest_and_below,omitempty"` - AllowRunnerRegistrationToken *bool `url:"allow_runner_registration_token,omitempty" json:"allow_runner_registration_token,omitempty"` - ArchiveBuildsInHumanReadable *string `url:"archive_builds_in_human_readable,omitempty" json:"archive_builds_in_human_readable,omitempty"` - ASCIIDocMaxIncludes *int `url:"asciidoc_max_includes,omitempty" json:"asciidoc_max_includes,omitempty"` - AssetProxyAllowlist *[]string `url:"asset_proxy_allowlist,omitempty" json:"asset_proxy_allowlist,omitempty"` - AssetProxyEnabled *bool `url:"asset_proxy_enabled,omitempty" json:"asset_proxy_enabled,omitempty"` - AssetProxySecretKey *string `url:"asset_proxy_secret_key,omitempty" json:"asset_proxy_secret_key,omitempty"` - AssetProxyURL *string `url:"asset_proxy_url,omitempty" json:"asset_proxy_url,omitempty"` - AssetProxyWhitelist *[]string `url:"asset_proxy_whitelist,omitempty" json:"asset_proxy_whitelist,omitempty"` - AuthorizedKeysEnabled *bool `url:"authorized_keys_enabled,omitempty" json:"authorized_keys_enabled,omitempty"` - AutoBanUserOnExcessiveProjectsDownload *bool `url:"auto_ban_user_on_excessive_projects_download,omitempty" json:"auto_ban_user_on_excessive_projects_download,omitempty"` - AutoDevOpsDomain *string `url:"auto_devops_domain,omitempty" json:"auto_devops_domain,omitempty"` - AutoDevOpsEnabled *bool `url:"auto_devops_enabled,omitempty" json:"auto_devops_enabled,omitempty"` - AutomaticPurchasedStorageAllocation *bool `url:"automatic_purchased_storage_allocation,omitempty" json:"automatic_purchased_storage_allocation,omitempty"` - BulkImportConcurrentPipelineBatchLimit *int `url:"bulk_import_concurrent_pipeline_batch_limit,omitempty" json:"bulk_import_concurrent_pipeline_batch_limit,omitempty"` - BulkImportEnabled *bool `url:"bulk_import_enabled,omitempty" json:"bulk_import_enabled,omitempty"` - BulkImportMaxDownloadFileSize *int `url:"bulk_import_max_download_file_size,omitempty" json:"bulk_import_max_download_file_size,omitempty"` - CanCreateGroup *bool `url:"can_create_group,omitempty" json:"can_create_group,omitempty"` - CheckNamespacePlan *bool `url:"check_namespace_plan,omitempty" json:"check_namespace_plan,omitempty"` - CIMaxIncludes *int `url:"ci_max_includes,omitempty" json:"ci_max_includes,omitempty"` - CIMaxTotalYAMLSizeBytes *int `url:"ci_max_total_yaml_size_bytes,omitempty" json:"ci_max_total_yaml_size_bytes,omitempty"` - CommitEmailHostname *string `url:"commit_email_hostname,omitempty" json:"commit_email_hostname,omitempty"` - ConcurrentBitbucketImportJobsLimit *int `url:"concurrent_bitbucket_import_jobs_limit,omitempty" json:"concurrent_bitbucket_import_jobs_limit,omitempty"` - ConcurrentBitbucketServerImportJobsLimit *int `url:"concurrent_bitbucket_server_import_jobs_limit,omitempty" json:"concurrent_bitbucket_server_import_jobs_limit,omitempty"` - ConcurrentGitHubImportJobsLimit *int `url:"concurrent_github_import_jobs_limit,omitempty" json:"concurrent_github_import_jobs_limit,omitempty"` - ContainerExpirationPoliciesEnableHistoricEntries *bool `url:"container_expiration_policies_enable_historic_entries,omitempty" json:"container_expiration_policies_enable_historic_entries,omitempty"` - ContainerRegistryCleanupTagsServiceMaxListSize *int `url:"container_registry_cleanup_tags_service_max_list_size,omitempty" json:"container_registry_cleanup_tags_service_max_list_size,omitempty"` - ContainerRegistryDeleteTagsServiceTimeout *int `url:"container_registry_delete_tags_service_timeout,omitempty" json:"container_registry_delete_tags_service_timeout,omitempty"` - ContainerRegistryExpirationPoliciesCaching *bool `url:"container_registry_expiration_policies_caching,omitempty" json:"container_registry_expiration_policies_caching,omitempty"` - ContainerRegistryExpirationPoliciesWorkerCapacity *int `url:"container_registry_expiration_policies_worker_capacity,omitempty" json:"container_registry_expiration_policies_worker_capacity,omitempty"` - ContainerRegistryImportCreatedBefore *time.Time `url:"container_registry_import_created_before,omitempty" json:"container_registry_import_created_before,omitempty"` - ContainerRegistryImportMaxRetries *int `url:"container_registry_import_max_retries,omitempty" json:"container_registry_import_max_retries,omitempty"` - ContainerRegistryImportMaxStepDuration *int `url:"container_registry_import_max_step_duration,omitempty" json:"container_registry_import_max_step_duration,omitempty"` - ContainerRegistryImportMaxTagsCount *int `url:"container_registry_import_max_tags_count,omitempty" json:"container_registry_import_max_tags_count,omitempty"` - ContainerRegistryImportStartMaxRetries *int `url:"container_registry_import_start_max_retries,omitempty" json:"container_registry_import_start_max_retries,omitempty"` - ContainerRegistryImportTargetPlan *string `url:"container_registry_import_target_plan,omitempty" json:"container_registry_import_target_plan,omitempty"` - ContainerRegistryTokenExpireDelay *int `url:"container_registry_token_expire_delay,omitempty" json:"container_registry_token_expire_delay,omitempty"` - CustomHTTPCloneURLRoot *string `url:"custom_http_clone_url_root,omitempty" json:"custom_http_clone_url_root,omitempty"` - DNSRebindingProtectionEnabled *bool `url:"dns_rebinding_protection_enabled,omitempty" json:"dns_rebinding_protection_enabled,omitempty"` - DSAKeyRestriction *int `url:"dsa_key_restriction,omitempty" json:"dsa_key_restriction,omitempty"` - DeactivateDormantUsers *bool `url:"deactivate_dormant_users,omitempty" json:"deactivate_dormant_users,omitempty"` - DeactivateDormantUsersPeriod *int `url:"deactivate_dormant_users_period,omitempty" json:"deactivate_dormant_users_period,omitempty"` - DecompressArchiveFileTimeout *int `url:"decompress_archive_file_timeout,omitempty" json:"decompress_archive_file_timeout,omitempty"` - DefaultArtifactsExpireIn *string `url:"default_artifacts_expire_in,omitempty" json:"default_artifacts_expire_in,omitempty"` - DefaultBranchName *string `url:"default_branch_name,omitempty" json:"default_branch_name,omitempty"` - DefaultBranchProtection *int `url:"default_branch_protection,omitempty" json:"default_branch_protection,omitempty"` - DefaultBranchProtectionDefaults *BranchProtectionDefaultsOptions `url:"default_branch_protection_defaults,omitempty" json:"default_branch_protection_defaults,omitempty"` - DefaultCiConfigPath *string `url:"default_ci_config_path,omitempty" json:"default_ci_config_path,omitempty"` - DefaultGroupVisibility *VisibilityValue `url:"default_group_visibility,omitempty" json:"default_group_visibility,omitempty"` - DefaultPreferredLanguage *string `url:"default_preferred_language,omitempty" json:"default_preferred_language,omitempty"` - DefaultProjectCreation *int `url:"default_project_creation,omitempty" json:"default_project_creation,omitempty"` - DefaultProjectDeletionProtection *bool `url:"default_project_deletion_protection,omitempty" json:"default_project_deletion_protection,omitempty"` - DefaultProjectVisibility *VisibilityValue `url:"default_project_visibility,omitempty" json:"default_project_visibility,omitempty"` - DefaultProjectsLimit *int `url:"default_projects_limit,omitempty" json:"default_projects_limit,omitempty"` - DefaultSnippetVisibility *VisibilityValue `url:"default_snippet_visibility,omitempty" json:"default_snippet_visibility,omitempty"` - DefaultSyntaxHighlightingTheme *int `url:"default_syntax_highlighting_theme,omitempty" json:"default_syntax_highlighting_theme,omitempty"` - DelayedGroupDeletion *bool `url:"delayed_group_deletion,omitempty" json:"delayed_group_deletion,omitempty"` - DelayedProjectDeletion *bool `url:"delayed_project_deletion,omitempty" json:"delayed_project_deletion,omitempty"` - DeleteInactiveProjects *bool `url:"delete_inactive_projects,omitempty" json:"delete_inactive_projects,omitempty"` - DeleteUnconfirmedUsers *bool `url:"delete_unconfirmed_users,omitempty" json:"delete_unconfirmed_users,omitempty"` - DeletionAdjournedPeriod *int `url:"deletion_adjourned_period,omitempty" json:"deletion_adjourned_period,omitempty"` - DiagramsnetEnabled *bool `url:"diagramsnet_enabled,omitempty" json:"diagramsnet_enabled,omitempty"` - DiagramsnetURL *string `url:"diagramsnet_url,omitempty" json:"diagramsnet_url,omitempty"` - DiffMaxFiles *int `url:"diff_max_files,omitempty" json:"diff_max_files,omitempty"` - DiffMaxLines *int `url:"diff_max_lines,omitempty" json:"diff_max_lines,omitempty"` - DiffMaxPatchBytes *int `url:"diff_max_patch_bytes,omitempty" json:"diff_max_patch_bytes,omitempty"` - DisableFeedToken *bool `url:"disable_feed_token,omitempty" json:"disable_feed_token,omitempty"` - DisableAdminOAuthScopes *bool `url:"disable_admin_oauth_scopes,omitempty" json:"disable_admin_oauth_scopes,omitempty"` - DisableOverridingApproversPerMergeRequest *bool `url:"disable_overriding_approvers_per_merge_request,omitempty" json:"disable_overriding_approvers_per_merge_request,omitempty"` - DisablePersonalAccessTokens *bool `url:"disable_personal_access_tokens,omitempty" json:"disable_personal_access_tokens,omitempty"` - DisabledOauthSignInSources *[]string `url:"disabled_oauth_sign_in_sources,omitempty" json:"disabled_oauth_sign_in_sources,omitempty"` - DomainAllowlist *[]string `url:"domain_allowlist,omitempty" json:"domain_allowlist,omitempty"` - DomainDenylist *[]string `url:"domain_denylist,omitempty" json:"domain_denylist,omitempty"` - DomainDenylistEnabled *bool `url:"domain_denylist_enabled,omitempty" json:"domain_denylist_enabled,omitempty"` - DownstreamPipelineTriggerLimitPerProjectUserSHA *int `url:"downstream_pipeline_trigger_limit_per_project_user_sha,omitempty" json:"downstream_pipeline_trigger_limit_per_project_user_sha,omitempty"` - DuoFeaturesEnabled *bool `url:"duo_features_enabled,omitempty" json:"duo_features_enabled,omitempty"` - ECDSAKeyRestriction *int `url:"ecdsa_key_restriction,omitempty" json:"ecdsa_key_restriction,omitempty"` - ECDSASKKeyRestriction *int `url:"ecdsa_sk_key_restriction,omitempty" json:"ecdsa_sk_key_restriction,omitempty"` - EKSAccessKeyID *string `url:"eks_access_key_id,omitempty" json:"eks_access_key_id,omitempty"` - EKSAccountID *string `url:"eks_account_id,omitempty" json:"eks_account_id,omitempty"` - EKSIntegrationEnabled *bool `url:"eks_integration_enabled,omitempty" json:"eks_integration_enabled,omitempty"` - EKSSecretAccessKey *string `url:"eks_secret_access_key,omitempty" json:"eks_secret_access_key,omitempty"` - Ed25519KeyRestriction *int `url:"ed25519_key_restriction,omitempty" json:"ed25519_key_restriction,omitempty"` - Ed25519SKKeyRestriction *int `url:"ed25519_sk_key_restriction,omitempty" json:"ed25519_sk_key_restriction,omitempty"` - ElasticsearchAWS *bool `url:"elasticsearch_aws,omitempty" json:"elasticsearch_aws,omitempty"` - ElasticsearchAWSAccessKey *string `url:"elasticsearch_aws_access_key,omitempty" json:"elasticsearch_aws_access_key,omitempty"` - ElasticsearchAWSRegion *string `url:"elasticsearch_aws_region,omitempty" json:"elasticsearch_aws_region,omitempty"` - ElasticsearchAWSSecretAccessKey *string `url:"elasticsearch_aws_secret_access_key,omitempty" json:"elasticsearch_aws_secret_access_key,omitempty"` - ElasticsearchAnalyzersKuromojiEnabled *bool `url:"elasticsearch_analyzers_kuromoji_enabled,omitempty" json:"elasticsearch_analyzers_kuromoji_enabled,omitempty"` - ElasticsearchAnalyzersKuromojiSearch *int `url:"elasticsearch_analyzers_kuromoji_search,omitempty" json:"elasticsearch_analyzers_kuromoji_search,omitempty"` - ElasticsearchAnalyzersSmartCNEnabled *bool `url:"elasticsearch_analyzers_smartcn_enabled,omitempty" json:"elasticsearch_analyzers_smartcn_enabled,omitempty"` - ElasticsearchAnalyzersSmartCNSearch *int `url:"elasticsearch_analyzers_smartcn_search,omitempty" json:"elasticsearch_analyzers_smartcn_search,omitempty"` - ElasticsearchClientRequestTimeout *int `url:"elasticsearch_client_request_timeout,omitempty" json:"elasticsearch_client_request_timeout,omitempty"` - ElasticsearchIndexedFieldLengthLimit *int `url:"elasticsearch_indexed_field_length_limit,omitempty" json:"elasticsearch_indexed_field_length_limit,omitempty"` - ElasticsearchIndexedFileSizeLimitKB *int `url:"elasticsearch_indexed_file_size_limit_kb,omitempty" json:"elasticsearch_indexed_file_size_limit_kb,omitempty"` - ElasticsearchIndexing *bool `url:"elasticsearch_indexing,omitempty" json:"elasticsearch_indexing,omitempty"` - ElasticsearchLimitIndexing *bool `url:"elasticsearch_limit_indexing,omitempty" json:"elasticsearch_limit_indexing,omitempty"` - ElasticsearchMaxBulkConcurrency *int `url:"elasticsearch_max_bulk_concurrency,omitempty" json:"elasticsearch_max_bulk_concurrency,omitempty"` - ElasticsearchMaxBulkSizeMB *int `url:"elasticsearch_max_bulk_size_mb,omitempty" json:"elasticsearch_max_bulk_size_mb,omitempty"` - ElasticsearchMaxCodeIndexingConcurrency *int `url:"elasticsearch_max_code_indexing_concurrency,omitempty" json:"elasticsearch_max_code_indexing_concurrency,omitempty"` - ElasticsearchNamespaceIDs *[]int `url:"elasticsearch_namespace_ids,omitempty" json:"elasticsearch_namespace_ids,omitempty"` - ElasticsearchPassword *string `url:"elasticsearch_password,omitempty" json:"elasticsearch_password,omitempty"` - ElasticsearchPauseIndexing *bool `url:"elasticsearch_pause_indexing,omitempty" json:"elasticsearch_pause_indexing,omitempty"` - ElasticsearchProjectIDs *[]int `url:"elasticsearch_project_ids,omitempty" json:"elasticsearch_project_ids,omitempty"` - ElasticsearchReplicas *int `url:"elasticsearch_replicas,omitempty" json:"elasticsearch_replicas,omitempty"` - ElasticsearchRequeueWorkers *bool `url:"elasticsearch_requeue_workers,omitempty" json:"elasticsearch_requeue_workers,omitempty"` - ElasticsearchSearch *bool `url:"elasticsearch_search,omitempty" json:"elasticsearch_search,omitempty"` - ElasticsearchShards *int `url:"elasticsearch_shards,omitempty" json:"elasticsearch_shards,omitempty"` - ElasticsearchURL *string `url:"elasticsearch_url,omitempty" json:"elasticsearch_url,omitempty"` - ElasticsearchUsername *string `url:"elasticsearch_username,omitempty" json:"elasticsearch_username,omitempty"` - ElasticsearchWorkerNumberOfShards *int `url:"elasticsearch_worker_number_of_shards,omitempty" json:"elasticsearch_worker_number_of_shards,omitempty"` - EmailAdditionalText *string `url:"email_additional_text,omitempty" json:"email_additional_text,omitempty"` - EmailAuthorInBody *bool `url:"email_author_in_body,omitempty" json:"email_author_in_body,omitempty"` - EmailConfirmationSetting *string `url:"email_confirmation_setting,omitempty" json:"email_confirmation_setting,omitempty"` - EmailRestrictions *string `url:"email_restrictions,omitempty" json:"email_restrictions,omitempty"` - EmailRestrictionsEnabled *bool `url:"email_restrictions_enabled,omitempty" json:"email_restrictions_enabled,omitempty"` - EnableArtifactExternalRedirectWarningPage *bool `url:"enable_artifact_external_redirect_warning_page,omitempty" json:"enable_artifact_external_redirect_warning_page,omitempty"` - EnabledGitAccessProtocol *string `url:"enabled_git_access_protocol,omitempty" json:"enabled_git_access_protocol,omitempty"` - EnforceNamespaceStorageLimit *bool `url:"enforce_namespace_storage_limit,omitempty" json:"enforce_namespace_storage_limit,omitempty"` - EnforcePATExpiration *bool `url:"enforce_pat_expiration,omitempty" json:"enforce_pat_expiration,omitempty"` - EnforceSSHKeyExpiration *bool `url:"enforce_ssh_key_expiration,omitempty" json:"enforce_ssh_key_expiration,omitempty"` - EnforceTerms *bool `url:"enforce_terms,omitempty" json:"enforce_terms,omitempty"` - ExternalAuthClientCert *string `url:"external_auth_client_cert,omitempty" json:"external_auth_client_cert,omitempty"` - ExternalAuthClientKey *string `url:"external_auth_client_key,omitempty" json:"external_auth_client_key,omitempty"` - ExternalAuthClientKeyPass *string `url:"external_auth_client_key_pass,omitempty" json:"external_auth_client_key_pass,omitempty"` - ExternalAuthorizationServiceDefaultLabel *string `url:"external_authorization_service_default_label,omitempty" json:"external_authorization_service_default_label,omitempty"` - ExternalAuthorizationServiceEnabled *bool `url:"external_authorization_service_enabled,omitempty" json:"external_authorization_service_enabled,omitempty"` - ExternalAuthorizationServiceTimeout *float64 `url:"external_authorization_service_timeout,omitempty" json:"external_authorization_service_timeout,omitempty"` - ExternalAuthorizationServiceURL *string `url:"external_authorization_service_url,omitempty" json:"external_authorization_service_url,omitempty"` - ExternalPipelineValidationServiceTimeout *int `url:"external_pipeline_validation_service_timeout,omitempty" json:"external_pipeline_validation_service_timeout,omitempty"` - ExternalPipelineValidationServiceToken *string `url:"external_pipeline_validation_service_token,omitempty" json:"external_pipeline_validation_service_token,omitempty"` - ExternalPipelineValidationServiceURL *string `url:"external_pipeline_validation_service_url,omitempty" json:"external_pipeline_validation_service_url,omitempty"` - FailedLoginAttemptsUnlockPeriodInMinutes *int `url:"failed_login_attempts_unlock_period_in_minutes,omitempty" json:"failed_login_attempts_unlock_period_in_minutes,omitempty"` - FileTemplateProjectID *int `url:"file_template_project_id,omitempty" json:"file_template_project_id,omitempty"` - FirstDayOfWeek *int `url:"first_day_of_week,omitempty" json:"first_day_of_week,omitempty"` - FlocEnabled *bool `url:"floc_enabled,omitempty" json:"floc_enabled,omitempty"` - GeoNodeAllowedIPs *string `url:"geo_node_allowed_ips,omitempty" json:"geo_node_allowed_ips,omitempty"` - GeoStatusTimeout *int `url:"geo_status_timeout,omitempty" json:"geo_status_timeout,omitempty"` - GitRateLimitUsersAlertlist *[]string `url:"git_rate_limit_users_alertlist,omitempty" json:"git_rate_limit_users_alertlist,omitempty"` - GitTwoFactorSessionExpiry *int `url:"git_two_factor_session_expiry,omitempty" json:"git_two_factor_session_expiry,omitempty"` - GitalyTimeoutDefault *int `url:"gitaly_timeout_default,omitempty" json:"gitaly_timeout_default,omitempty"` - GitalyTimeoutFast *int `url:"gitaly_timeout_fast,omitempty" json:"gitaly_timeout_fast,omitempty"` - GitalyTimeoutMedium *int `url:"gitaly_timeout_medium,omitempty" json:"gitaly_timeout_medium,omitempty"` - GitlabDedicatedInstance *bool `url:"gitlab_dedicated_instance,omitempty" json:"gitlab_dedicated_instance,omitempty"` - GitlabEnvironmentToolkitInstance *bool `url:"gitlab_environment_toolkit_instance,omitempty" json:"gitlab_environment_toolkit_instance,omitempty"` - GitlabShellOperationLimit *int `url:"gitlab_shell_operation_limit,omitempty" json:"gitlab_shell_operation_limit,omitempty"` - GitpodEnabled *bool `url:"gitpod_enabled,omitempty" json:"gitpod_enabled,omitempty"` - GitpodURL *string `url:"gitpod_url,omitempty" json:"gitpod_url,omitempty"` - GitRateLimitUsersAllowlist *[]string `url:"git_rate_limit_users_allowlist,omitempty" json:"git_rate_limit_users_allowlist,omitempty"` - GloballyAllowedIPs *string `url:"globally_allowed_ips,omitempty" json:"globally_allowed_ips,omitempty"` - GrafanaEnabled *bool `url:"grafana_enabled,omitempty" json:"grafana_enabled,omitempty"` - GrafanaURL *string `url:"grafana_url,omitempty" json:"grafana_url,omitempty"` - GravatarEnabled *bool `url:"gravatar_enabled,omitempty" json:"gravatar_enabled,omitempty"` - GroupDownloadExportLimit *int `url:"group_download_export_limit,omitempty" json:"group_download_export_limit,omitempty"` - GroupExportLimit *int `url:"group_export_limit,omitempty" json:"group_export_limit,omitempty"` - GroupImportLimit *int `url:"group_import_limit,omitempty" json:"group_import_limit,omitempty"` - GroupOwnersCanManageDefaultBranchProtection *bool `url:"group_owners_can_manage_default_branch_protection,omitempty" json:"group_owners_can_manage_default_branch_protection,omitempty"` - GroupRunnerTokenExpirationInterval *int `url:"group_runner_token_expiration_interval,omitempty" json:"group_runner_token_expiration_interval,omitempty"` - HTMLEmailsEnabled *bool `url:"html_emails_enabled,omitempty" json:"html_emails_enabled,omitempty"` - HashedStorageEnabled *bool `url:"hashed_storage_enabled,omitempty" json:"hashed_storage_enabled,omitempty"` - HelpPageDocumentationBaseURL *string `url:"help_page_documentation_base_url,omitempty" json:"help_page_documentation_base_url,omitempty"` - HelpPageHideCommercialContent *bool `url:"help_page_hide_commercial_content,omitempty" json:"help_page_hide_commercial_content,omitempty"` - HelpPageSupportURL *string `url:"help_page_support_url,omitempty" json:"help_page_support_url,omitempty"` - HelpPageText *string `url:"help_page_text,omitempty" json:"help_page_text,omitempty"` - HelpText *string `url:"help_text,omitempty" json:"help_text,omitempty"` - HideThirdPartyOffers *bool `url:"hide_third_party_offers,omitempty" json:"hide_third_party_offers,omitempty"` - HomePageURL *string `url:"home_page_url,omitempty" json:"home_page_url,omitempty"` - HousekeepingBitmapsEnabled *bool `url:"housekeeping_bitmaps_enabled,omitempty" json:"housekeeping_bitmaps_enabled,omitempty"` - HousekeepingEnabled *bool `url:"housekeeping_enabled,omitempty" json:"housekeeping_enabled,omitempty"` - HousekeepingFullRepackPeriod *int `url:"housekeeping_full_repack_period,omitempty" json:"housekeeping_full_repack_period,omitempty"` - HousekeepingGcPeriod *int `url:"housekeeping_gc_period,omitempty" json:"housekeeping_gc_period,omitempty"` - HousekeepingIncrementalRepackPeriod *int `url:"housekeeping_incremental_repack_period,omitempty" json:"housekeeping_incremental_repack_period,omitempty"` - HousekeepingOptimizeRepositoryPeriod *int `url:"housekeeping_optimize_repository_period,omitempty" json:"housekeeping_optimize_repository_period,omitempty"` - ImportSources *[]string `url:"import_sources,omitempty" json:"import_sources,omitempty"` - InactiveProjectsDeleteAfterMonths *int `url:"inactive_projects_delete_after_months,omitempty" json:"inactive_projects_delete_after_months,omitempty"` - InactiveProjectsMinSizeMB *int `url:"inactive_projects_min_size_mb,omitempty" json:"inactive_projects_min_size_mb,omitempty"` - InactiveProjectsSendWarningEmailAfterMonths *int `url:"inactive_projects_send_warning_email_after_months,omitempty" json:"inactive_projects_send_warning_email_after_months,omitempty"` - IncludeOptionalMetricsInServicePing *bool `url:"include_optional_metrics_in_service_ping,omitempty" json:"include_optional_metrics_in_service_ping,omitempty"` - InProductMarketingEmailsEnabled *bool `url:"in_product_marketing_emails_enabled,omitempty" json:"in_product_marketing_emails_enabled,omitempty"` - InvisibleCaptchaEnabled *bool `url:"invisible_captcha_enabled,omitempty" json:"invisible_captcha_enabled,omitempty"` - IssuesCreateLimit *int `url:"issues_create_limit,omitempty" json:"issues_create_limit,omitempty"` - JiraConnectApplicationKey *string `url:"jira_connect_application_key,omitempty" json:"jira_connect_application_key,omitempty"` - JiraConnectPublicKeyStorageEnabled *bool `url:"jira_connect_public_key_storage_enabled,omitempty" json:"jira_connect_public_key_storage_enabled,omitempty"` - JiraConnectProxyURL *string `url:"jira_connect_proxy_url,omitempty" json:"jira_connect_proxy_url,omitempty"` - KeepLatestArtifact *bool `url:"keep_latest_artifact,omitempty" json:"keep_latest_artifact,omitempty"` - KrokiEnabled *bool `url:"kroki_enabled,omitempty" json:"kroki_enabled,omitempty"` - KrokiFormats *map[string]bool `url:"kroki_formats,omitempty" json:"kroki_formats,omitempty"` - KrokiURL *string `url:"kroki_url,omitempty" json:"kroki_url,omitempty"` - LocalMarkdownVersion *int `url:"local_markdown_version,omitempty" json:"local_markdown_version,omitempty"` - LockDuoFeaturesEnabled *bool `url:"lock_duo_features_enabled,omitempty" json:"lock_duo_features_enabled,omitempty"` - LockMembershipsToLDAP *bool `url:"lock_memberships_to_ldap,omitempty" json:"lock_memberships_to_ldap,omitempty"` - LoginRecaptchaProtectionEnabled *bool `url:"login_recaptcha_protection_enabled,omitempty" json:"login_recaptcha_protection_enabled,omitempty"` - MailgunEventsEnabled *bool `url:"mailgun_events_enabled,omitempty" json:"mailgun_events_enabled,omitempty"` - MailgunSigningKey *string `url:"mailgun_signing_key,omitempty" json:"mailgun_signing_key,omitempty"` - MaintenanceMode *bool `url:"maintenance_mode,omitempty" json:"maintenance_mode,omitempty"` - MaintenanceModeMessage *string `url:"maintenance_mode_message,omitempty" json:"maintenance_mode_message,omitempty"` - MavenPackageRequestsForwarding *bool `url:"maven_package_requests_forwarding,omitempty" json:"maven_package_requests_forwarding,omitempty"` - MaxArtifactsSize *int `url:"max_artifacts_size,omitempty" json:"max_artifacts_size,omitempty"` - MaxAttachmentSize *int `url:"max_attachment_size,omitempty" json:"max_attachment_size,omitempty"` - MaxDecompressedArchiveSize *int `url:"max_decompressed_archive_size,omitempty" json:"max_decompressed_archive_size,omitempty"` - MaxExportSize *int `url:"max_export_size,omitempty" json:"max_export_size,omitempty"` - MaxImportRemoteFileSize *int `url:"max_import_remote_file_size,omitempty" json:"max_import_remote_file_size,omitempty"` - MaxImportSize *int `url:"max_import_size,omitempty" json:"max_import_size,omitempty"` - MaxLoginAttempts *int `url:"max_login_attempts,omitempty" json:"max_login_attempts,omitempty"` - MaxNumberOfRepositoryDownloads *int `url:"max_number_of_repository_downloads,omitempty" json:"max_number_of_repository_downloads,omitempty"` - MaxNumberOfRepositoryDownloadsWithinTimePeriod *int `url:"max_number_of_repository_downloads_within_time_period,omitempty" json:"max_number_of_repository_downloads_within_time_period,omitempty"` - MaxPagesSize *int `url:"max_pages_size,omitempty" json:"max_pages_size,omitempty"` - MaxPersonalAccessTokenLifetime *int `url:"max_personal_access_token_lifetime,omitempty" json:"max_personal_access_token_lifetime,omitempty"` - MaxSSHKeyLifetime *int `url:"max_ssh_key_lifetime,omitempty" json:"max_ssh_key_lifetime,omitempty"` - MaxTerraformStateSizeBytes *int `url:"max_terraform_state_size_bytes,omitempty" json:"max_terraform_state_size_bytes,omitempty"` - MaxYAMLDepth *int `url:"max_yaml_depth,omitempty" json:"max_yaml_depth,omitempty"` - MaxYAMLSizeBytes *int `url:"max_yaml_size_bytes,omitempty" json:"max_yaml_size_bytes,omitempty"` - MetricsMethodCallThreshold *int `url:"metrics_method_call_threshold,omitempty" json:"metrics_method_call_threshold,omitempty"` - MinimumPasswordLength *int `url:"minimum_password_length,omitempty" json:"minimum_password_length,omitempty"` - MirrorAvailable *bool `url:"mirror_available,omitempty" json:"mirror_available,omitempty"` - MirrorCapacityThreshold *int `url:"mirror_capacity_threshold,omitempty" json:"mirror_capacity_threshold,omitempty"` - MirrorMaxCapacity *int `url:"mirror_max_capacity,omitempty" json:"mirror_max_capacity,omitempty"` - MirrorMaxDelay *int `url:"mirror_max_delay,omitempty" json:"mirror_max_delay,omitempty"` - NPMPackageRequestsForwarding *bool `url:"npm_package_requests_forwarding,omitempty" json:"npm_package_requests_forwarding,omitempty"` - NotesCreateLimit *int `url:"notes_create_limit,omitempty" json:"notes_create_limit,omitempty"` - NotifyOnUnknownSignIn *bool `url:"notify_on_unknown_sign_in,omitempty" json:"notify_on_unknown_sign_in,omitempty"` - NugetSkipMetadataURLValidation *bool `url:"nuget_skip_metadata_url_validation,omitempty" json:"nuget_skip_metadata_url_validation,omitempty"` - OutboundLocalRequestsAllowlistRaw *string `url:"outbound_local_requests_allowlist_raw,omitempty" json:"outbound_local_requests_allowlist_raw,omitempty"` - OutboundLocalRequestsWhitelist *[]string `url:"outbound_local_requests_whitelist,omitempty" json:"outbound_local_requests_whitelist,omitempty"` - PackageMetadataPURLTypes *[]int `url:"package_metadata_purl_types,omitempty" json:"package_metadata_purl_types,omitempty"` - PackageRegistryAllowAnyoneToPullOption *bool `url:"package_registry_allow_anyone_to_pull_option,omitempty" json:"package_registry_allow_anyone_to_pull_option,omitempty"` - PackageRegistryCleanupPoliciesWorkerCapacity *int `url:"package_registry_cleanup_policies_worker_capacity,omitempty" json:"package_registry_cleanup_policies_worker_capacity,omitempty"` - PagesDomainVerificationEnabled *bool `url:"pages_domain_verification_enabled,omitempty" json:"pages_domain_verification_enabled,omitempty"` - PasswordAuthenticationEnabledForGit *bool `url:"password_authentication_enabled_for_git,omitempty" json:"password_authentication_enabled_for_git,omitempty"` - PasswordAuthenticationEnabledForWeb *bool `url:"password_authentication_enabled_for_web,omitempty" json:"password_authentication_enabled_for_web,omitempty"` - PasswordNumberRequired *bool `url:"password_number_required,omitempty" json:"password_number_required,omitempty"` - PasswordSymbolRequired *bool `url:"password_symbol_required,omitempty" json:"password_symbol_required,omitempty"` - PasswordUppercaseRequired *bool `url:"password_uppercase_required,omitempty" json:"password_uppercase_required,omitempty"` - PasswordLowercaseRequired *bool `url:"password_lowercase_required,omitempty" json:"password_lowercase_required,omitempty"` - PerformanceBarAllowedGroupID *int `url:"performance_bar_allowed_group_id,omitempty" json:"performance_bar_allowed_group_id,omitempty"` - PerformanceBarAllowedGroupPath *string `url:"performance_bar_allowed_group_path,omitempty" json:"performance_bar_allowed_group_path,omitempty"` - PerformanceBarEnabled *bool `url:"performance_bar_enabled,omitempty" json:"performance_bar_enabled,omitempty"` - PersonalAccessTokenPrefix *string `url:"personal_access_token_prefix,omitempty" json:"personal_access_token_prefix,omitempty"` - PlantumlEnabled *bool `url:"plantuml_enabled,omitempty" json:"plantuml_enabled,omitempty"` - PlantumlURL *string `url:"plantuml_url,omitempty" json:"plantuml_url,omitempty"` - PipelineLimitPerProjectUserSha *int `url:"pipeline_limit_per_project_user_sha,omitempty" json:"pipeline_limit_per_project_user_sha,omitempty"` - PollingIntervalMultiplier *float64 `url:"polling_interval_multiplier,omitempty" json:"polling_interval_multiplier,omitempty"` - PreventMergeRequestsAuthorApproval *bool `url:"prevent_merge_requests_author_approval,omitempty" json:"prevent_merge_requests_author_approval,omitempty"` - PreventMergeRequestsCommittersApproval *bool `url:"prevent_merge_requests_committers_approval,omitempty" json:"prevent_merge_requests_committers_approval,omitempty"` - ProjectDownloadExportLimit *int `url:"project_download_export_limit,omitempty" json:"project_download_export_limit,omitempty"` - ProjectExportEnabled *bool `url:"project_export_enabled,omitempty" json:"project_export_enabled,omitempty"` - ProjectExportLimit *int `url:"project_export_limit,omitempty" json:"project_export_limit,omitempty"` - ProjectImportLimit *int `url:"project_import_limit,omitempty" json:"project_import_limit,omitempty"` - ProjectJobsAPIRateLimit *int `url:"project_jobs_api_rate_limit,omitempty" json:"project_jobs_api_rate_limit,omitempty"` - ProjectRunnerTokenExpirationInterval *int `url:"project_runner_token_expiration_interval,omitempty" json:"project_runner_token_expiration_interval,omitempty"` - ProjectsAPIRateLimitUnauthenticated *int `url:"projects_api_rate_limit_unauthenticated,omitempty" json:"projects_api_rate_limit_unauthenticated,omitempty"` - PrometheusMetricsEnabled *bool `url:"prometheus_metrics_enabled,omitempty" json:"prometheus_metrics_enabled,omitempty"` - ProtectedCIVariables *bool `url:"protected_ci_variables,omitempty" json:"protected_ci_variables,omitempty"` - PseudonymizerEnabled *bool `url:"pseudonymizer_enabled,omitempty" json:"pseudonymizer_enabled,omitempty"` - PushEventActivitiesLimit *int `url:"push_event_activities_limit,omitempty" json:"push_event_activities_limit,omitempty"` - PushEventHooksLimit *int `url:"push_event_hooks_limit,omitempty" json:"push_event_hooks_limit,omitempty"` - PyPIPackageRequestsForwarding *bool `url:"pypi_package_requests_forwarding,omitempty" json:"pypi_package_requests_forwarding,omitempty"` - RSAKeyRestriction *int `url:"rsa_key_restriction,omitempty" json:"rsa_key_restriction,omitempty"` - RateLimitingResponseText *string `url:"rate_limiting_response_text,omitempty" json:"rate_limiting_response_text,omitempty"` - RawBlobRequestLimit *int `url:"raw_blob_request_limit,omitempty" json:"raw_blob_request_limit,omitempty"` - RecaptchaEnabled *bool `url:"recaptcha_enabled,omitempty" json:"recaptcha_enabled,omitempty"` - RecaptchaPrivateKey *string `url:"recaptcha_private_key,omitempty" json:"recaptcha_private_key,omitempty"` - RecaptchaSiteKey *string `url:"recaptcha_site_key,omitempty" json:"recaptcha_site_key,omitempty"` - ReceiveMaxInputSize *int `url:"receive_max_input_size,omitempty" json:"receive_max_input_size,omitempty"` - ReceptiveClusterAgentsEnabled *bool `url:"receptive_cluster_agents_enabled,omitempty" json:"receptive_cluster_agents_enabled,omitempty"` - RememberMeEnabled *bool `url:"remember_me_enabled,omitempty" json:"remember_me_enabled,omitempty"` - RepositoryChecksEnabled *bool `url:"repository_checks_enabled,omitempty" json:"repository_checks_enabled,omitempty"` - RepositorySizeLimit *int `url:"repository_size_limit,omitempty" json:"repository_size_limit,omitempty"` - RepositoryStorages *[]string `url:"repository_storages,omitempty" json:"repository_storages,omitempty"` - RepositoryStoragesWeighted *map[string]int `url:"repository_storages_weighted,omitempty" json:"repository_storages_weighted,omitempty"` - RequireAdminApprovalAfterUserSignup *bool `url:"require_admin_approval_after_user_signup,omitempty" json:"require_admin_approval_after_user_signup,omitempty"` - RequireAdminTwoFactorAuthentication *bool `url:"require_admin_two_factor_authentication,omitempty" json:"require_admin_two_factor_authentication,omitempty"` - RequirePersonalAccessTokenExpiry *bool `url:"require_personal_access_token_expiry,omitempty" json:"require_personal_access_token_expiry,omitempty"` - RequireTwoFactorAuthentication *bool `url:"require_two_factor_authentication,omitempty" json:"require_two_factor_authentication,omitempty"` - RestrictedVisibilityLevels *[]VisibilityValue `url:"restricted_visibility_levels,omitempty" json:"restricted_visibility_levels,omitempty"` - RunnerTokenExpirationInterval *int `url:"runner_token_expiration_interval,omitempty" json:"runner_token_expiration_interval,omitempty"` - SearchRateLimit *int `url:"search_rate_limit,omitempty" json:"search_rate_limit,omitempty"` - SearchRateLimitUnauthenticated *int `url:"search_rate_limit_unauthenticated,omitempty" json:"search_rate_limit_unauthenticated,omitempty"` - SecretDetectionRevocationTokenTypesURL *string `url:"secret_detection_revocation_token_types_url,omitempty" json:"secret_detection_revocation_token_types_url,omitempty"` - SecretDetectionTokenRevocationEnabled *bool `url:"secret_detection_token_revocation_enabled,omitempty" json:"secret_detection_token_revocation_enabled,omitempty"` - SecretDetectionTokenRevocationToken *string `url:"secret_detection_token_revocation_token,omitempty" json:"secret_detection_token_revocation_token,omitempty"` - SecretDetectionTokenRevocationURL *string `url:"secret_detection_token_revocation_url,omitempty" json:"secret_detection_token_revocation_url,omitempty"` - SecurityApprovalPoliciesLimit *int `url:"security_approval_policies_limit,omitempty" json:"security_approval_policies_limit,omitempty"` - SecurityPolicyGlobalGroupApproversEnabled *bool `url:"security_policy_global_group_approvers_enabled,omitempty" json:"security_policy_global_group_approvers_enabled,omitempty"` - SecurityTXTContent *string `url:"security_txt_content,omitempty" json:"security_txt_content,omitempty"` - SendUserConfirmationEmail *bool `url:"send_user_confirmation_email,omitempty" json:"send_user_confirmation_email,omitempty"` - SentryClientsideDSN *string `url:"sentry_clientside_dsn,omitempty" json:"sentry_clientside_dsn,omitempty"` - SentryDSN *string `url:"sentry_dsn,omitempty" json:"sentry_dsn,omitempty"` - SentryEnabled *string `url:"sentry_enabled,omitempty" json:"sentry_enabled,omitempty"` - SentryEnvironment *string `url:"sentry_environment,omitempty" json:"sentry_environment,omitempty"` - ServiceAccessTokensExpirationEnforced *bool `url:"service_access_tokens_expiration_enforced,omitempty" json:"service_access_tokens_expiration_enforced,omitempty"` - SessionExpireDelay *int `url:"session_expire_delay,omitempty" json:"session_expire_delay,omitempty"` - SharedRunnersEnabled *bool `url:"shared_runners_enabled,omitempty" json:"shared_runners_enabled,omitempty"` - SharedRunnersMinutes *int `url:"shared_runners_minutes,omitempty" json:"shared_runners_minutes,omitempty"` - SharedRunnersText *string `url:"shared_runners_text,omitempty" json:"shared_runners_text,omitempty"` - SidekiqJobLimiterCompressionThresholdBytes *int `url:"sidekiq_job_limiter_compression_threshold_bytes,omitempty" json:"sidekiq_job_limiter_compression_threshold_bytes,omitempty"` - SidekiqJobLimiterLimitBytes *int `url:"sidekiq_job_limiter_limit_bytes,omitempty" json:"sidekiq_job_limiter_limit_bytes,omitempty"` - SidekiqJobLimiterMode *string `url:"sidekiq_job_limiter_mode,omitempty" json:"sidekiq_job_limiter_mode,omitempty"` - SignInText *string `url:"sign_in_text,omitempty" json:"sign_in_text,omitempty"` - SignupEnabled *bool `url:"signup_enabled,omitempty" json:"signup_enabled,omitempty"` - SilentAdminExportsEnabled *bool `url:"silent_admin_exports_enabled,omitempty" json:"silent_admin_exports_enabled,omitempty"` - SilentModeEnabled *bool `url:"silent_mode_enabled,omitempty" json:"silent_mode_enabled,omitempty"` - SlackAppEnabled *bool `url:"slack_app_enabled,omitempty" json:"slack_app_enabled,omitempty"` - SlackAppID *string `url:"slack_app_id,omitempty" json:"slack_app_id,omitempty"` - SlackAppSecret *string `url:"slack_app_secret,omitempty" json:"slack_app_secret,omitempty"` - SlackAppSigningSecret *string `url:"slack_app_signing_secret,omitempty" json:"slack_app_signing_secret,omitempty"` - SlackAppVerificationToken *string `url:"slack_app_verification_token,omitempty" json:"slack_app_verification_token,omitempty"` - SnippetSizeLimit *int `url:"snippet_size_limit,omitempty" json:"snippet_size_limit,omitempty"` - SnowplowAppID *string `url:"snowplow_app_id,omitempty" json:"snowplow_app_id,omitempty"` - SnowplowCollectorHostname *string `url:"snowplow_collector_hostname,omitempty" json:"snowplow_collector_hostname,omitempty"` - SnowplowCookieDomain *string `url:"snowplow_cookie_domain,omitempty" json:"snowplow_cookie_domain,omitempty"` - SnowplowDatabaseCollectorHostname *string `url:"snowplow_database_collector_hostname,omitempty" json:"snowplow_database_collector_hostname,omitempty"` - SnowplowEnabled *bool `url:"snowplow_enabled,omitempty" json:"snowplow_enabled,omitempty"` - SourcegraphEnabled *bool `url:"sourcegraph_enabled,omitempty" json:"sourcegraph_enabled,omitempty"` - SourcegraphPublicOnly *bool `url:"sourcegraph_public_only,omitempty" json:"sourcegraph_public_only,omitempty"` - SourcegraphURL *string `url:"sourcegraph_url,omitempty" json:"sourcegraph_url,omitempty"` - SpamCheckAPIKey *string `url:"spam_check_api_key,omitempty" json:"spam_check_api_key,omitempty"` - SpamCheckEndpointEnabled *bool `url:"spam_check_endpoint_enabled,omitempty" json:"spam_check_endpoint_enabled,omitempty"` - SpamCheckEndpointURL *string `url:"spam_check_endpoint_url,omitempty" json:"spam_check_endpoint_url,omitempty"` - StaticObjectsExternalStorageAuthToken *string `url:"static_objects_external_storage_auth_token,omitempty" json:"static_objects_external_storage_auth_token,omitempty"` - StaticObjectsExternalStorageURL *string `url:"static_objects_external_storage_url,omitempty" json:"static_objects_external_storage_url,omitempty"` - SuggestPipelineEnabled *bool `url:"suggest_pipeline_enabled,omitempty" json:"suggest_pipeline_enabled,omitempty"` - TerminalMaxSessionTime *int `url:"terminal_max_session_time,omitempty" json:"terminal_max_session_time,omitempty"` - Terms *string `url:"terms,omitempty" json:"terms,omitempty"` - ThrottleAuthenticatedAPIEnabled *bool `url:"throttle_authenticated_api_enabled,omitempty" json:"throttle_authenticated_api_enabled,omitempty"` - ThrottleAuthenticatedAPIPeriodInSeconds *int `url:"throttle_authenticated_api_period_in_seconds,omitempty" json:"throttle_authenticated_api_period_in_seconds,omitempty"` - ThrottleAuthenticatedAPIRequestsPerPeriod *int `url:"throttle_authenticated_api_requests_per_period,omitempty" json:"throttle_authenticated_api_requests_per_period,omitempty"` - ThrottleAuthenticatedDeprecatedAPIEnabled *bool `url:"throttle_authenticated_deprecated_api_enabled,omitempty" json:"throttle_authenticated_deprecated_api_enabled,omitempty"` - ThrottleAuthenticatedDeprecatedAPIPeriodInSeconds *int `url:"throttle_authenticated_deprecated_api_period_in_seconds,omitempty" json:"throttle_authenticated_deprecated_api_period_in_seconds,omitempty"` - ThrottleAuthenticatedDeprecatedAPIRequestsPerPeriod *int `url:"throttle_authenticated_deprecated_api_requests_per_period,omitempty" json:"throttle_authenticated_deprecated_api_requests_per_period,omitempty"` - ThrottleAuthenticatedFilesAPIEnabled *bool `url:"throttle_authenticated_files_api_enabled,omitempty" json:"throttle_authenticated_files_api_enabled,omitempty"` - ThrottleAuthenticatedFilesAPIPeriodInSeconds *int `url:"throttle_authenticated_files_api_period_in_seconds,omitempty" json:"throttle_authenticated_files_api_period_in_seconds,omitempty"` - ThrottleAuthenticatedFilesAPIRequestsPerPeriod *int `url:"throttle_authenticated_files_api_requests_per_period,omitempty" json:"throttle_authenticated_files_api_requests_per_period,omitempty"` - ThrottleAuthenticatedGitLFSEnabled *bool `url:"throttle_authenticated_git_lfs_enabled,omitempty" json:"throttle_authenticated_git_lfs_enabled,omitempty"` - ThrottleAuthenticatedGitLFSPeriodInSeconds *int `url:"throttle_authenticated_git_lfs_period_in_seconds,omitempty" json:"throttle_authenticated_git_lfs_period_in_seconds,omitempty"` - ThrottleAuthenticatedGitLFSRequestsPerPeriod *int `url:"throttle_authenticated_git_lfs_requests_per_period,omitempty" json:"throttle_authenticated_git_lfs_requests_per_period,omitempty"` - ThrottleAuthenticatedPackagesAPIEnabled *bool `url:"throttle_authenticated_packages_api_enabled,omitempty" json:"throttle_authenticated_packages_api_enabled,omitempty"` - ThrottleAuthenticatedPackagesAPIPeriodInSeconds *int `url:"throttle_authenticated_packages_api_period_in_seconds,omitempty" json:"throttle_authenticated_packages_api_period_in_seconds,omitempty"` - ThrottleAuthenticatedPackagesAPIRequestsPerPeriod *int `url:"throttle_authenticated_packages_api_requests_per_period,omitempty" json:"throttle_authenticated_packages_api_requests_per_period,omitempty"` - ThrottleAuthenticatedWebEnabled *bool `url:"throttle_authenticated_web_enabled,omitempty" json:"throttle_authenticated_web_enabled,omitempty"` - ThrottleAuthenticatedWebPeriodInSeconds *int `url:"throttle_authenticated_web_period_in_seconds,omitempty" json:"throttle_authenticated_web_period_in_seconds,omitempty"` - ThrottleAuthenticatedWebRequestsPerPeriod *int `url:"throttle_authenticated_web_requests_per_period,omitempty" json:"throttle_authenticated_web_requests_per_period,omitempty"` - ThrottleIncidentManagementNotificationEnabled *bool `url:"throttle_incident_management_notification_enabled,omitempty" json:"throttle_incident_management_notification_enabled,omitempty"` - ThrottleIncidentManagementNotificationPerPeriod *int `url:"throttle_incident_management_notification_per_period,omitempty" json:"throttle_incident_management_notification_per_period,omitempty"` - ThrottleIncidentManagementNotificationPeriodInSeconds *int `url:"throttle_incident_management_notification_period_in_seconds,omitempty" json:"throttle_incident_management_notification_period_in_seconds,omitempty"` - ThrottleProtectedPathsEnabled *bool `url:"throttle_protected_paths_enabled_enabled,omitempty" json:"throttle_protected_paths_enabled,omitempty"` - ThrottleProtectedPathsPeriodInSeconds *int `url:"throttle_protected_paths_enabled_period_in_seconds,omitempty" json:"throttle_protected_paths_period_in_seconds,omitempty"` - ThrottleProtectedPathsRequestsPerPeriod *int `url:"throttle_protected_paths_enabled_requests_per_period,omitempty" json:"throttle_protected_paths_per_period,omitempty"` - ThrottleUnauthenticatedAPIEnabled *bool `url:"throttle_unauthenticated_api_enabled,omitempty" json:"throttle_unauthenticated_api_enabled,omitempty"` - ThrottleUnauthenticatedAPIPeriodInSeconds *int `url:"throttle_unauthenticated_api_period_in_seconds,omitempty" json:"throttle_unauthenticated_api_period_in_seconds,omitempty"` - ThrottleUnauthenticatedAPIRequestsPerPeriod *int `url:"throttle_unauthenticated_api_requests_per_period,omitempty" json:"throttle_unauthenticated_api_requests_per_period,omitempty"` - ThrottleUnauthenticatedDeprecatedAPIEnabled *bool `url:"throttle_unauthenticated_deprecated_api_enabled,omitempty" json:"throttle_unauthenticated_deprecated_api_enabled,omitempty"` - ThrottleUnauthenticatedDeprecatedAPIPeriodInSeconds *int `url:"throttle_unauthenticated_deprecated_api_period_in_seconds,omitempty" json:"throttle_unauthenticated_deprecated_api_period_in_seconds,omitempty"` - ThrottleUnauthenticatedDeprecatedAPIRequestsPerPeriod *int `url:"throttle_unauthenticated_deprecated_api_requests_per_period,omitempty" json:"throttle_unauthenticated_deprecated_api_requests_per_period,omitempty"` - ThrottleUnauthenticatedEnabled *bool `url:"throttle_unauthenticated_enabled,omitempty" json:"throttle_unauthenticated_enabled,omitempty"` - ThrottleUnauthenticatedFilesAPIEnabled *bool `url:"throttle_unauthenticated_files_api_enabled,omitempty" json:"throttle_unauthenticated_files_api_enabled,omitempty"` - ThrottleUnauthenticatedFilesAPIPeriodInSeconds *int `url:"throttle_unauthenticated_files_api_period_in_seconds,omitempty" json:"throttle_unauthenticated_files_api_period_in_seconds,omitempty"` - ThrottleUnauthenticatedFilesAPIRequestsPerPeriod *int `url:"throttle_unauthenticated_files_api_requests_per_period,omitempty" json:"throttle_unauthenticated_files_api_requests_per_period,omitempty"` - ThrottleUnauthenticatedGitLFSEnabled *bool `url:"throttle_unauthenticated_git_lfs_enabled,omitempty" json:"throttle_unauthenticated_git_lfs_enabled,omitempty"` - ThrottleUnauthenticatedGitLFSPeriodInSeconds *int `url:"throttle_unauthenticated_git_lfs_period_in_seconds,omitempty" json:"throttle_unauthenticated_git_lfs_period_in_seconds,omitempty"` - ThrottleUnauthenticatedGitLFSRequestsPerPeriod *int `url:"throttle_unauthenticated_git_lfs_requests_per_period,omitempty" json:"throttle_unauthenticated_git_lfs_requests_per_period,omitempty"` - ThrottleUnauthenticatedPackagesAPIEnabled *bool `url:"throttle_unauthenticated_packages_api_enabled,omitempty" json:"throttle_unauthenticated_packages_api_enabled,omitempty"` - ThrottleUnauthenticatedPackagesAPIPeriodInSeconds *int `url:"throttle_unauthenticated_packages_api_period_in_seconds,omitempty" json:"throttle_unauthenticated_packages_api_period_in_seconds,omitempty"` - ThrottleUnauthenticatedPackagesAPIRequestsPerPeriod *int `url:"throttle_unauthenticated_packages_api_requests_per_period,omitempty" json:"throttle_unauthenticated_packages_api_requests_per_period,omitempty"` - ThrottleUnauthenticatedPeriodInSeconds *int `url:"throttle_unauthenticated_period_in_seconds,omitempty" json:"throttle_unauthenticated_period_in_seconds,omitempty"` - ThrottleUnauthenticatedRequestsPerPeriod *int `url:"throttle_unauthenticated_requests_per_period,omitempty" json:"throttle_unauthenticated_requests_per_period,omitempty"` - ThrottleUnauthenticatedWebEnabled *bool `url:"throttle_unauthenticated_web_enabled,omitempty" json:"throttle_unauthenticated_web_enabled,omitempty"` - ThrottleUnauthenticatedWebPeriodInSeconds *int `url:"throttle_unauthenticated_web_period_in_seconds,omitempty" json:"throttle_unauthenticated_web_period_in_seconds,omitempty"` - ThrottleUnauthenticatedWebRequestsPerPeriod *int `url:"throttle_unauthenticated_web_requests_per_period,omitempty" json:"throttle_unauthenticated_web_requests_per_period,omitempty"` - TimeTrackingLimitToHours *bool `url:"time_tracking_limit_to_hours,omitempty" json:"time_tracking_limit_to_hours,omitempty"` - TwoFactorGracePeriod *int `url:"two_factor_grace_period,omitempty" json:"two_factor_grace_period,omitempty"` - UnconfirmedUsersDeleteAfterDays *int `url:"unconfirmed_users_delete_after_days,omitempty" json:"unconfirmed_users_delete_after_days,omitempty"` - UniqueIPsLimitEnabled *bool `url:"unique_ips_limit_enabled,omitempty" json:"unique_ips_limit_enabled,omitempty"` - UniqueIPsLimitPerUser *int `url:"unique_ips_limit_per_user,omitempty" json:"unique_ips_limit_per_user,omitempty"` - UniqueIPsLimitTimeWindow *int `url:"unique_ips_limit_time_window,omitempty" json:"unique_ips_limit_time_window,omitempty"` - UpdateRunnerVersionsEnabled *bool `url:"update_runner_versions_enabled,omitempty" json:"update_runner_versions_enabled,omitempty"` - UpdatingNameDisabledForUsers *bool `url:"updating_name_disabled_for_users,omitempty" json:"updating_name_disabled_for_users,omitempty"` - UsagePingEnabled *bool `url:"usage_ping_enabled,omitempty" json:"usage_ping_enabled,omitempty"` - UsagePingFeaturesEnabled *bool `url:"usage_ping_features_enabled,omitempty" json:"usage_ping_features_enabled,omitempty"` - UseClickhouseForAnalytics *bool `url:"use_clickhouse_for_analytics,omitempty" json:"use_clickhouse_for_analytics,omitempty"` - UserDeactivationEmailsEnabled *bool `url:"user_deactivation_emails_enabled,omitempty" json:"user_deactivation_emails_enabled,omitempty"` - UserDefaultExternal *bool `url:"user_default_external,omitempty" json:"user_default_external,omitempty"` - UserDefaultInternalRegex *string `url:"user_default_internal_regex,omitempty" json:"user_default_internal_regex,omitempty"` - UserDefaultsToPrivateProfile *bool `url:"user_defaults_to_private_profile,omitempty" json:"user_defaults_to_private_profile,omitempty"` - UserEmailLookupLimit *int `url:"user_email_lookup_limit,omitempty" json:"user_email_lookup_limit,omitempty"` - UserOauthApplications *bool `url:"user_oauth_applications,omitempty" json:"user_oauth_applications,omitempty"` - UserShowAddSSHKeyMessage *bool `url:"user_show_add_ssh_key_message,omitempty" json:"user_show_add_ssh_key_message,omitempty"` - UsersGetByIDLimit *int `url:"users_get_by_id_limit,omitempty" json:"users_get_by_id_limit,omitempty"` - UsersGetByIDLimitAllowlistRaw *string `url:"users_get_by_id_limit_allowlist_raw,omitempty" json:"users_get_by_id_limit_allowlist_raw,omitempty"` - ValidRunnerRegistrars *[]string `url:"valid_runner_registrars,omitempty" json:"valid_runner_registrars,omitempty"` - VersionCheckEnabled *bool `url:"version_check_enabled,omitempty" json:"version_check_enabled,omitempty"` - WebIDEClientsidePreviewEnabled *bool `url:"web_ide_clientside_preview_enabled,omitempty" json:"web_ide_clientside_preview_enabled,omitempty"` - WhatsNewVariant *string `url:"whats_new_variant,omitempty" json:"whats_new_variant,omitempty"` - WikiPageMaxContentBytes *int `url:"wiki_page_max_content_bytes,omitempty" json:"wiki_page_max_content_bytes,omitempty"` -} - -// BranchProtectionDefaultsOptions represents default Git protected branch permissions options. -// -// GitLab API docs: -// https://docs.gitlab.com/ee/api/groups.html#options-for-default_branch_protection_defaults -type BranchProtectionDefaultsOptions struct { - AllowedToPush *[]int `url:"allowed_to_push,omitempty" json:"allowed_to_push,omitempty"` - AllowForcePush *bool `url:"allow_force_push,omitempty" json:"allow_force_push,omitempty"` - AllowedToMerge *[]int `url:"allowed_to_merge,omitempty" json:"allowed_to_merge,omitempty"` - DeveloperCanInitialPush *bool `url:"developer_can_initial_push,omitempty" json:"developer_can_initial_push,omitempty"` -} - -// UpdateSettings updates the application settings. -// -// GitLab API docs: -// https://docs.gitlab.com/ee/api/settings.html#change-application-settings -func (s *SettingsService) UpdateSettings(opt *UpdateSettingsOptions, options ...RequestOptionFunc) (*Settings, *Response, error) { - req, err := s.client.NewRequest(http.MethodPut, "application/settings", opt, options) - if err != nil { - return nil, nil, err - } - - as := new(Settings) - resp, err := s.client.Do(req, as) - if err != nil { - return nil, resp, err - } - - return as, resp, nil -} diff --git a/vendor/github.com/zeebo/errs/AUTHORS b/vendor/github.com/zeebo/errs/AUTHORS index a970ee5773..6246e7403d 100644 --- a/vendor/github.com/zeebo/errs/AUTHORS +++ b/vendor/github.com/zeebo/errs/AUTHORS @@ -1,4 +1,5 @@ Egon Elbre Jeff Wendling JT Olio -Kaloyan Raev \ No newline at end of file +Kaloyan Raev +paul cannon diff --git a/vendor/github.com/zeebo/errs/README.md b/vendor/github.com/zeebo/errs/README.md index be6bc0b406..0f72bf7b01 100644 --- a/vendor/github.com/zeebo/errs/README.md +++ b/vendor/github.com/zeebo/errs/README.md @@ -152,7 +152,7 @@ func checkForNeatThings() { } ``` -It knows about both the `Cause() error` and `Unwrap() error` methods that are +It knows about both the `Unwrap() error` and `Unwrap() []error` methods that are often used in the community, and will call them as many times as possible. ### Defer diff --git a/vendor/github.com/zeebo/errs/errs.go b/vendor/github.com/zeebo/errs/errs.go index fec20c6072..9a42e3da87 100644 --- a/vendor/github.com/zeebo/errs/errs.go +++ b/vendor/github.com/zeebo/errs/errs.go @@ -14,16 +14,11 @@ type Namer interface{ Name() (string, bool) } // Causer is implemented by all errors returned in this package. It returns // the underlying cause of the error, or nil if there is no underlying cause. +// +// Deprecated: check for the 'Unwrap()' interface from the stdlib errors package +// instead. type Causer interface{ Cause() error } -// unwrapper is implemented by all errors returned in this package. It returns -// the underlying cause of the error, or nil if there is no underlying error. -type unwrapper interface{ Unwrap() error } - -// ungrouper is implemented by combinedError returned in this package. It -// returns all underlying errors, or nil if there is no underlying error. -type ungrouper interface{ Ungroup() []error } - // New returns an error not contained in any class. This is the same as calling // fmt.Errorf(...) except it captures a stack trace on creation. func New(format string, args ...interface{}) error { @@ -45,23 +40,38 @@ func WrapP(err *error) { } } -// Often, we call Cause as much as possible. Since comparing arbitrary +// Often, we call Unwrap as much as possible. Since comparing arbitrary // interfaces with equality isn't panic safe, we only loop up to 100 // times to ensure that a poor implementation that causes a cycle does // not run forever. -const maxCause = 100 +const maxUnwrap = 100 -// Unwrap returns the underlying error, if any, or just the error. +// Unwrap returns the final, most underlying error, if any, or just the error. +// +// Deprecated: Prefer errors.Is() and errors.As(). func Unwrap(err error) error { - for i := 0; err != nil && i < maxCause; i++ { + for i := 0; err != nil && i < maxUnwrap; i++ { var nerr error switch e := err.(type) { case Causer: nerr = e.Cause() - case unwrapper: + case interface{ Unwrap() error }: nerr = e.Unwrap() + + case interface{ Ungroup() []error }: + // consider the first error to be the "main" error. + errs := e.Ungroup() + if len(errs) > 0 { + nerr = errs[0] + } + case interface{ Unwrap() []error }: + // consider the first error to be the "main" error. + errs := e.Unwrap() + if len(errs) > 0 { + nerr = errs[0] + } } if nerr == nil { @@ -75,81 +85,47 @@ func Unwrap(err error) error { // Classes returns all the classes that have wrapped the error. func Classes(err error) (classes []*Class) { - causes := 0 - for { - switch e := err.(type) { - case *errorT: - if e.class != nil { - classes = append(classes, e.class) - } - err = e.err - continue - - case Causer: - err = e.Cause() - - case unwrapper: - err = e.Unwrap() - - default: - return classes - } - - if causes >= maxCause { - return classes + IsFunc(err, func(err error) bool { + if e, ok := err.(*errorT); ok { + classes = append(classes, e.class) } - causes++ - } -} - -// Is checks if any of the underlying errors matches target -func Is(err, target error) bool { - return IsFunc(err, func(err error) bool { - return err == target + return false }) + return classes } // IsFunc checks if any of the underlying errors matches the func func IsFunc(err error, is func(err error) bool) bool { - causes := 0 - errs := []error{err} - - for len(errs) > 0 { - var next []error - for _, err := range errs { - if is(err) { - return true - } + for { + if is(err) { + return true + } - switch e := err.(type) { - case ungrouper: - ungrouped := e.Ungroup() - for _, unerr := range ungrouped { - if unerr != nil { - next = append(next, unerr) - } - } - case Causer: - cause := e.Cause() - if cause != nil { - next = append(next, cause) + switch u := err.(type) { + case interface{ Unwrap() error }: + err = u.Unwrap() + case Causer: + err = u.Cause() + + case interface{ Ungroup() []error }: + for _, err := range u.Ungroup() { + if IsFunc(err, is) { + return true } - case unwrapper: - unwrapped := e.Unwrap() - if unwrapped != nil { - next = append(next, unwrapped) + } + return false + case interface{ Unwrap() []error }: + for _, err := range u.Unwrap() { + if IsFunc(err, is) { + return true } } + return false - if causes >= maxCause { - return false - } - causes++ + default: + return false } - errs = next } - - return false } // @@ -160,7 +136,8 @@ func IsFunc(err error, is func(err error) bool) bool { // errors are part of the class. type Class string -// Has returns true if the passed in error was wrapped by this class. +// Has returns true if the passed in error (or any error wrapped by it) has +// this class. func (c *Class) Has(err error) bool { return IsFunc(err, func(err error) bool { errt, ok := err.(*errorT) @@ -188,6 +165,22 @@ func (c *Class) WrapP(err *error) { } } +// Instance creates a class membership object which implements the error +// interface and allows errors.Is() to check whether given errors are +// (or contain) an instance of this class. +// +// This makes possible a construct like the following: +// +// if errors.Is(err, MyClass.Instance()) { +// fmt.Printf("err is an instance of MyClass") +// } +// +// ..without requiring the Class type to implement the error interface itself, +// as that would open the door to sundry misunderstandings and misusage. +func (c *Class) Instance() error { + return (*classMembershipChecker)(c) +} + // create constructs the error, or just adds the class to the error, keeping // track of the stack if it needs to construct it. func (c *Class) create(depth int, err error) error { @@ -218,6 +211,12 @@ func (c *Class) create(depth int, err error) error { return errt } +type classMembershipChecker Class + +func (cmc *classMembershipChecker) Error() string { + panic("classMembershipChecker used as concrete error! don't do that") +} + // // errors // @@ -259,15 +258,13 @@ func (e *errorT) Format(f fmt.State, c rune) { } } -// Cause implements the interface wrapping errors are expected to implement -// to allow getting at underlying causes. +// Cause implements the interface wrapping errors were previously +// expected to implement to allow getting at underlying causes. func (e *errorT) Cause() error { return e.err } -// Unwrap implements the draft design for error inspection. Since this is -// on an unexported type, it should not be hard to maintain going forward -// given that it also is the exact same semantics as Cause. +// Unwrap returns the immediate underlying error. func (e *errorT) Unwrap() error { return e.err } @@ -280,6 +277,14 @@ func (e *errorT) Name() (string, bool) { return string(*e.class), true } +// Is determines whether an error is an instance of the given error class. +// +// Use with (*Class).Instance(). +func (e *errorT) Is(err error) bool { + cmc, ok := err.(*classMembershipChecker) + return ok && e.class == (*Class)(cmc) +} + // summarizeStack writes stack line entries to the writer. func summarizeStack(w io.Writer, pcs []uintptr) { frames := runtime.CallersFrames(pcs) diff --git a/vendor/github.com/zeebo/errs/group.go b/vendor/github.com/zeebo/errs/group.go index e5997ec55d..22b824aaf8 100644 --- a/vendor/github.com/zeebo/errs/group.go +++ b/vendor/github.com/zeebo/errs/group.go @@ -56,23 +56,8 @@ func (group Group) sanitize() Group { // combinedError is a list of non-empty errors type combinedError []error -// Cause returns the first error. -func (group combinedError) Cause() error { - if len(group) > 0 { - return group[0] - } - return nil -} - // Unwrap returns the first error. -func (group combinedError) Unwrap() error { - return group.Cause() -} - -// Ungroup returns all errors. -func (group combinedError) Ungroup() []error { - return group -} +func (group combinedError) Unwrap() []error { return group } // Error returns error string delimited by semicolons. func (group combinedError) Error() string { return fmt.Sprintf("%v", group) } diff --git a/vendor/github.com/zeebo/errs/is_go1.20.go b/vendor/github.com/zeebo/errs/is_go1.20.go new file mode 100644 index 0000000000..6f8799aa48 --- /dev/null +++ b/vendor/github.com/zeebo/errs/is_go1.20.go @@ -0,0 +1,8 @@ +//go:build go1.20 + +package errs + +import "errors" + +// Is checks if any of the underlying errors matches target +func Is(err, target error) bool { return errors.Is(err, target) } diff --git a/vendor/github.com/zeebo/errs/is_go_other.go b/vendor/github.com/zeebo/errs/is_go_other.go new file mode 100644 index 0000000000..92f3b5b61f --- /dev/null +++ b/vendor/github.com/zeebo/errs/is_go_other.go @@ -0,0 +1,17 @@ +//go:build !go1.20 +// +build !go1.20 + +package errs + +// Is checks if any of the underlying errors matches target +func Is(err, target error) bool { + return IsFunc(err, func(err error) bool { + if err == target { + return true + } + if x, ok := err.(interface{ Is(error) bool }); ok && x.Is(target) { + return true + } + return false + }) +} diff --git a/vendor/github.com/xanzy/go-gitlab/.gitignore b/vendor/gitlab.com/gitlab-org/api/client-go/.gitignore similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/.gitignore rename to vendor/gitlab.com/gitlab-org/api/client-go/.gitignore diff --git a/vendor/gitlab.com/gitlab-org/api/client-go/.gitlab-ci.yml b/vendor/gitlab.com/gitlab-org/api/client-go/.gitlab-ci.yml new file mode 100644 index 0000000000..dfbfd9f8be --- /dev/null +++ b/vendor/gitlab.com/gitlab-org/api/client-go/.gitlab-ci.yml @@ -0,0 +1,147 @@ +workflow: + rules: + - if: $CI_PIPELINE_SOURCE == "merge_request_event" + - if: $CI_PIPELINE_SOURCE == "schedule" + - if: $CI_COMMIT_TAG + - if: $CI_COMMIT_REF_PROTECTED == "true" + +include: + - component: ${CI_SERVER_FQDN}/gitlab-org/components/danger-review/danger-review@2.0.0 + inputs: + job_stage: lint + job_allow_failure: true + +stages: + - lint + - test + - deploy + +.go:versions: + parallel: + matrix: + - GOLANG_IMAGE_VERSION: + - '1.22' + - '1.23' + - '1.24' + +.go:base: + # From: https://docs.gitlab.com/ee/ci/caching/#cache-go-dependencies + variables: + GOPATH: $CI_PROJECT_DIR/.go + GOLANGCI_LINT_CACHE: $CI_PROJECT_DIR/.golangci-lint + before_script: + - mkdir -p "${GOPATH}" "${GOLANGCI_LINT_CACHE}" + cache: + paths: + - $GOPATH/pkg/mod/ + - $GOLANGCI_LINT_CACHE/ + key: + files: + - go.sum + # We want to speed up CI a bit. + # Community contributors are recommended to use the Community fork + # which has access to this runners. + # For other forks to free tier namespaces this might fail, + # which is a good reminder to use the Community fork and not + # to accidentally burn to personal compute minutes. + tags: + - saas-linux-large-amd64 + # We only need to run Go-related jobs when actual Go files changed + # or when running either on the default branch or for a tag. + rules: + - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH' + - if: $CI_COMMIT_TAG + - changes: + - '**/*.go' + - testdata/** + - go.mod + - go.sum + - .gitlab-ci.yml + +golangci-lint: + extends: + - .go:base + stage: lint + needs: [] + variables: + REPORT_FILENAME: 'gl-code-quality-report.json' + image: golangci/golangci-lint:v1.64.5 + script: + - golangci-lint run --print-issued-lines=false --out-format code-climate:$REPORT_FILENAME,line-number + artifacts: + reports: + codequality: $REPORT_FILENAME + paths: [$REPORT_FILENAME] + when: always + +tests:unit: + extends: + - .go:base + - .go:versions + stage: test + needs: [] + image: golang:$GOLANG_IMAGE_VERSION + variables: + # configure tooling versions + GOTESTSUM_VERSION: 'v1.12.0' + GOCOVER_COBERTURA_VERSION: 'v1.2.1-0.20240107185409-0818f3538137' + + # configure artifact files + JUNIT_FILENAME: tests.xml + COVERPROFILE_FILENAME: coverage.out + COVERPROFILE_XML_FILENAME: coverage.xml + script: + - go run gotest.tools/gotestsum@${GOTESTSUM_VERSION} --format=standard-quiet --junitfile=$JUNIT_FILENAME -- -race -coverprofile=$COVERPROFILE_FILENAME -covermode=atomic ./... + - go run github.com/boumenot/gocover-cobertura@${GOCOVER_COBERTURA_VERSION} < $COVERPROFILE_FILENAME > $COVERPROFILE_XML_FILENAME + - go tool cover -func $COVERPROFILE_FILENAME + coverage: '/total:.+\(statements\).+\d+\.\d+/' + artifacts: + paths: + - $JUNIT_FILENAME + - $COVERPROFILE_XML_FILENAME + reports: + junit: $JUNIT_FILENAME + coverage_report: + path: $COVERPROFILE_XML_FILENAME + coverage_format: cobertura + when: always + +generate-release-notes: + stage: deploy + needs: [] + image: alpine:3.21.2 + before_script: + - apk add --update jq curl git + script: + - | + if [ -z "$CI_COMMIT_TAG" ]; then + last_stable_version_sha="$(git tag | grep -E '^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$' | sort -Vr | head -n1)" + version="${last_stable_version_sha}+${CI_COMMIT_SHA}" + else + version="$CI_COMMIT_TAG" + fi + urlencoded_version="$(jq -rn --arg x "${version}" '$x|@uri')" + - echo "Generating release notes for ${version} (urlencoded=${urlencoded_version}) ..." + - 'curl --fail-with-body --header "JOB-TOKEN: $CI_JOB_TOKEN" "$CI_API_V4_URL/projects/$CI_PROJECT_ID/repository/changelog?version=${urlencoded_version}" | jq -r .notes > release-notes.md' + - cat release-notes.md + artifacts: + paths: + - release-notes.md + +release: + stage: deploy + rules: + - if: $CI_COMMIT_TAG + needs: + - golangci-lint + - tests:unit + - job: generate-release-notes + artifacts: true + image: registry.gitlab.com/gitlab-org/release-cli:latest + script: + - echo "Create release for $CI_COMMIT_TAG" + release: + tag_name: '$CI_COMMIT_TAG' + tag_message: 'Version $CI_COMMIT_TAG' + name: '$CI_COMMIT_TAG' + description: release-notes.md diff --git a/vendor/github.com/xanzy/go-gitlab/.golangci.yml b/vendor/gitlab.com/gitlab-org/api/client-go/.golangci.yml similarity index 91% rename from vendor/github.com/xanzy/go-gitlab/.golangci.yml rename to vendor/gitlab.com/gitlab-org/api/client-go/.golangci.yml index 7c05feeefc..49c2c7aa90 100644 --- a/vendor/github.com/xanzy/go-gitlab/.golangci.yml +++ b/vendor/gitlab.com/gitlab-org/api/client-go/.golangci.yml @@ -19,21 +19,24 @@ linters-settings: locale: US ignore-words: - noteable + revive: + enable-all-rules: false + rules: + - name: deep-exit linters: enable: - asciicheck - dogsled - errorlint - - exportloopref - goconst - gosimple - govet - ineffassign - - megacheck - misspell - nakedret - nolintlint + - revive - staticcheck - typecheck - unconvert diff --git a/vendor/gitlab.com/gitlab-org/api/client-go/.tool-versions b/vendor/gitlab.com/gitlab-org/api/client-go/.tool-versions new file mode 100644 index 0000000000..3c1fdba6ba --- /dev/null +++ b/vendor/gitlab.com/gitlab-org/api/client-go/.tool-versions @@ -0,0 +1 @@ +golang 1.22.10 diff --git a/vendor/github.com/xanzy/go-gitlab/CONTRIBUTING.md b/vendor/gitlab.com/gitlab-org/api/client-go/CONTRIBUTING.md similarity index 53% rename from vendor/github.com/xanzy/go-gitlab/CONTRIBUTING.md rename to vendor/gitlab.com/gitlab-org/api/client-go/CONTRIBUTING.md index 32bd822745..76f086c3f5 100644 --- a/vendor/github.com/xanzy/go-gitlab/CONTRIBUTING.md +++ b/vendor/gitlab.com/gitlab-org/api/client-go/CONTRIBUTING.md @@ -4,21 +4,31 @@ We want to make contributing to this project as easy as possible. ## Reporting Issues -If you have an issue, please report it on the [issue tracker](https://github.com/xanzy/go-gitlab/issues). +If you have an issue, please report it on the +[issue tracker](https://gitlab.com/gitlab-org/api/client-go/-/issues). -When you are up for writing a PR to solve the issue you encountered, it's not -needed to first open a separate issue. In that case only opening a PR with a +When you are up for writing a MR to solve the issue you encountered, it's not +needed to first open a separate issue. In that case only opening a MR with a description of the issue you are trying to solve is just fine. ## Contributing Code -Pull requests are always welcome. When in doubt if your contribution fits within +Merge requests are always welcome. When in doubt if your contribution fits within the rest of the project, feel free to first open an issue to discuss your idea. This is not needed when fixing a bug or adding an enhancement, as long as the enhancement you are trying to add can be found in the public GitLab API docs as this project only supports what is in the public API docs. +### Use community fork to contribute + +To contribute to this project we recommend that you use the +[community fork](https://gitlab.com/gitlab-community/api/client-go). +Have a look at the +[community fork README](https://gitlab.com/gitlab-community#gitlab-community-forks) +to learn more about what it is and why you should prefer it over +creating your own fork to contribute. + ## Coding style We try to follow the Go best practices, where it makes sense, and use @@ -26,20 +36,20 @@ We try to follow the Go best practices, where it makes sense, and use As a general rule of thumb we prefer to keep line width for comments below 80 chars and for code (where possible and sensible) below 100 chars. -Before making a PR, please look at the rest this package and try to make sure +Before making a MR, please look at the rest this package and try to make sure your contribution is consistent with the rest of the coding style. -New struct field or methods should be placed (as much as possible) in the same +New `struct` fields or methods should be placed (as much as possible) in the same order as the ordering used in the public API docs. The idea is that this makes it easier to find things. -### Setting up your local development environment to Contribute to `go-gitlab` +### Setting up your local development environment to contribute -1. [Fork](https://github.com/xanzy/go-gitlab/fork), then clone the repository. +1. [Fork](https://gitlab.com/gitlab-org/api/client-go), then clone the repository. ```sh - git clone https://github.com//go-gitlab.git + git clone https://gitlab.com//client-go.git # or via ssh - git clone git@github.com:/go-gitlab.git + git clone git@gitlab.com:/client-go.git ``` 1. Install dependencies: ```sh @@ -50,4 +60,4 @@ easier to find things. ```sh make test && make fmt ``` -1. Open up your pull request +1. Open up your merge request diff --git a/vendor/gitlab.com/gitlab-org/api/client-go/Dangerfile b/vendor/gitlab.com/gitlab-org/api/client-go/Dangerfile new file mode 100644 index 0000000000..13606f2727 --- /dev/null +++ b/vendor/gitlab.com/gitlab-org/api/client-go/Dangerfile @@ -0,0 +1,11 @@ +require 'gitlab-dangerfiles' + +# see https://docs.gitlab.com/ee/development/dangerbot.html#enable-danger-on-a-project +# see https://gitlab.com/gitlab-org/ruby/gems/gitlab-dangerfiles +Gitlab::Dangerfiles.for_project(self, 'gitlab-api-client-go') do |dangerfiles| + # Import all plugins from the gem + dangerfiles.import_plugins + + # Import a defined set of danger rules + dangerfiles.import_dangerfiles(only: %w[simple_roulette changelog metadata type_label z_add_labels z_retry_link]) +end diff --git a/vendor/cuelang.org/go/internal/third_party/yaml/LICENSE b/vendor/gitlab.com/gitlab-org/api/client-go/LICENSE similarity index 100% rename from vendor/cuelang.org/go/internal/third_party/yaml/LICENSE rename to vendor/gitlab.com/gitlab-org/api/client-go/LICENSE diff --git a/vendor/github.com/xanzy/go-gitlab/Makefile b/vendor/gitlab.com/gitlab-org/api/client-go/Makefile similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/Makefile rename to vendor/gitlab.com/gitlab-org/api/client-go/Makefile diff --git a/vendor/gitlab.com/gitlab-org/api/client-go/README.md b/vendor/gitlab.com/gitlab-org/api/client-go/README.md new file mode 100644 index 0000000000..23c554abee --- /dev/null +++ b/vendor/gitlab.com/gitlab-org/api/client-go/README.md @@ -0,0 +1,113 @@ +# GitLab client-go (former `github.com/xanzy/go-gitlab`) + +A GitLab API client enabling Go programs to interact with GitLab in a simple and uniform way. + +## Usage + +```go +import "gitlab.com/gitlab-org/api/client-go" +``` + +Construct a new GitLab client, then use the various services on the client to +access different parts of the GitLab API. For example, to list all +users: + +```go +git, err := gitlab.NewClient("yourtokengoeshere") +if err != nil { + log.Fatalf("Failed to create client: %v", err) +} +users, _, err := git.Users.ListUsers(&gitlab.ListUsersOptions{}) +``` + +There are a few `With...` option functions that can be used to customize +the API client. For example, to set a custom base URL: + +```go +git, err := gitlab.NewClient("yourtokengoeshere", gitlab.WithBaseURL("https://git.mydomain.com/api/v4")) +if err != nil { + log.Fatalf("Failed to create client: %v", err) +} +users, _, err := git.Users.ListUsers(&gitlab.ListUsersOptions{}) +``` + +Some API methods have optional parameters that can be passed. For example, +to list all projects for user "svanharmelen": + +```go +git := gitlab.NewClient("yourtokengoeshere") +opt := &gitlab.ListProjectsOptions{Search: gitlab.Ptr("svanharmelen")} +projects, _, err := git.Projects.ListProjects(opt) +``` + +### Examples + +The [examples](/examples) directory +contains a couple for clear examples, of which one is partially listed here as well: + +```go +package main + +import ( + "log" + + "gitlab.com/gitlab-org/api/client-go" +) + +func main() { + git, err := gitlab.NewClient("yourtokengoeshere") + if err != nil { + log.Fatalf("Failed to create client: %v", err) + } + + // Create new project + p := &gitlab.CreateProjectOptions{ + Name: gitlab.Ptr("My Project"), + Description: gitlab.Ptr("Just a test project to play with"), + MergeRequestsAccessLevel: gitlab.Ptr(gitlab.EnabledAccessControl), + SnippetsAccessLevel: gitlab.Ptr(gitlab.EnabledAccessControl), + Visibility: gitlab.Ptr(gitlab.PublicVisibility), + } + project, _, err := git.Projects.CreateProject(p) + if err != nil { + log.Fatal(err) + } + + // Add a new snippet + s := &gitlab.CreateProjectSnippetOptions{ + Title: gitlab.Ptr("Dummy Snippet"), + FileName: gitlab.Ptr("snippet.go"), + Content: gitlab.Ptr("package main...."), + Visibility: gitlab.Ptr(gitlab.PublicVisibility), + } + _, _, err = git.ProjectSnippets.CreateSnippet(project.ID, s) + if err != nil { + log.Fatal(err) + } +} +``` + +For complete usage of go-gitlab, see the full [package docs](https://godoc.org/gitlab.com/gitlab-org/api/client-go). + +## Contributing + +Contributions are always welcome. For more information, check out the +[contributing guide](/CONTRIBUTING.md). + +## Maintenance + +This is a community maintained project. If you have a paid GitLab subscription, +please note that this project is not packaged as a part of GitLab, and falls outside +of the scope of support. + +For more information, see GitLab's +[Statement of Support](https://about.gitlab.com/support/statement-of-support.html). +Please fill out an issue in this projects issue tracker and someone from the community +will respond as soon as they are available to help you. + +### Known GitLab Projects using this package + +- [GitLab Terraform Provider](https://gitlab.com/gitlab-org/terraform-provider-gitlab) + maintained by the community with support from ~"group::environments" +- [GitLab CLI (`glab`)](https://gitlab.com/gitlab-org/cli) + maintained by ~"group::code review" diff --git a/vendor/github.com/xanzy/go-gitlab/access_requests.go b/vendor/gitlab.com/gitlab-org/api/client-go/access_requests.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/access_requests.go rename to vendor/gitlab.com/gitlab-org/api/client-go/access_requests.go diff --git a/vendor/github.com/xanzy/go-gitlab/appearance.go b/vendor/gitlab.com/gitlab-org/api/client-go/appearance.go similarity index 96% rename from vendor/github.com/xanzy/go-gitlab/appearance.go rename to vendor/gitlab.com/gitlab-org/api/client-go/appearance.go index f21893c0e0..8597fa9b53 100644 --- a/vendor/github.com/xanzy/go-gitlab/appearance.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/appearance.go @@ -38,6 +38,7 @@ type Appearance struct { Logo string `json:"logo"` HeaderLogo string `json:"header_logo"` Favicon string `json:"favicon"` + MemberGuidelines string `json:"member_guidelines"` NewProjectGuidelines string `json:"new_project_guidelines"` ProfileImageGuidelines string `json:"profile_image_guidelines"` HeaderMessage string `json:"header_message"` @@ -80,6 +81,7 @@ type ChangeAppearanceOptions struct { Logo *string `url:"logo,omitempty" json:"logo,omitempty"` HeaderLogo *string `url:"header_logo,omitempty" json:"header_logo,omitempty"` Favicon *string `url:"favicon,omitempty" json:"favicon,omitempty"` + MemberGuidelines *string `url:"member_guidelines,omitempty" json:"member_guidelines,omitempty"` NewProjectGuidelines *string `url:"new_project_guidelines,omitempty" json:"new_project_guidelines,omitempty"` ProfileImageGuidelines *string `url:"profile_image_guidelines,omitempty" json:"profile_image_guidelines,omitempty"` HeaderMessage *string `url:"header_message,omitempty" json:"header_message,omitempty"` diff --git a/vendor/github.com/xanzy/go-gitlab/applications.go b/vendor/gitlab.com/gitlab-org/api/client-go/applications.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/applications.go rename to vendor/gitlab.com/gitlab-org/api/client-go/applications.go diff --git a/vendor/github.com/xanzy/go-gitlab/audit_events.go b/vendor/gitlab.com/gitlab-org/api/client-go/audit_events.go similarity index 98% rename from vendor/github.com/xanzy/go-gitlab/audit_events.go rename to vendor/gitlab.com/gitlab-org/api/client-go/audit_events.go index de312e5606..f51415c70c 100644 --- a/vendor/github.com/xanzy/go-gitlab/audit_events.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/audit_events.go @@ -14,6 +14,7 @@ type AuditEvent struct { AuthorID int `json:"author_id"` EntityID int `json:"entity_id"` EntityType string `json:"entity_type"` + EventName string `json:"event_name"` Details AuditEventDetails `json:"details"` CreatedAt *time.Time `json:"created_at"` EventType string `json:"event_type"` @@ -42,6 +43,7 @@ type AuditEventDetails struct { IPAddress string `json:"ip_address"` EntityPath string `json:"entity_path"` FailedLogin string `json:"failed_login"` + EventName string `json:"event_name"` } // AuditEventsService handles communication with the project/group/instance diff --git a/vendor/github.com/xanzy/go-gitlab/avatar.go b/vendor/gitlab.com/gitlab-org/api/client-go/avatar.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/avatar.go rename to vendor/gitlab.com/gitlab-org/api/client-go/avatar.go diff --git a/vendor/github.com/xanzy/go-gitlab/award_emojis.go b/vendor/gitlab.com/gitlab-org/api/client-go/award_emojis.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/award_emojis.go rename to vendor/gitlab.com/gitlab-org/api/client-go/award_emojis.go diff --git a/vendor/github.com/xanzy/go-gitlab/boards.go b/vendor/gitlab.com/gitlab-org/api/client-go/boards.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/boards.go rename to vendor/gitlab.com/gitlab-org/api/client-go/boards.go diff --git a/vendor/github.com/xanzy/go-gitlab/branches.go b/vendor/gitlab.com/gitlab-org/api/client-go/branches.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/branches.go rename to vendor/gitlab.com/gitlab-org/api/client-go/branches.go diff --git a/vendor/github.com/xanzy/go-gitlab/broadcast_messages.go b/vendor/gitlab.com/gitlab-org/api/client-go/broadcast_messages.go similarity index 96% rename from vendor/github.com/xanzy/go-gitlab/broadcast_messages.go rename to vendor/gitlab.com/gitlab-org/api/client-go/broadcast_messages.go index 3d0c61d9fc..2fbe9924e6 100644 --- a/vendor/github.com/xanzy/go-gitlab/broadcast_messages.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/broadcast_messages.go @@ -30,7 +30,7 @@ type BroadcastMessagesService struct { client *Client } -// BroadcastMessage represents a GitLab issue board. +// BroadcastMessage represents a GitLab broadcast message. // // GitLab API docs: // https://docs.gitlab.com/ee/api/broadcast_messages.html#get-all-broadcast-messages @@ -45,6 +45,7 @@ type BroadcastMessage struct { TargetPath string `json:"target_path"` BroadcastType string `json:"broadcast_type"` Dismissable bool `json:"dismissable"` + Theme string `json:"theme"` // Deprecated: This parameter was removed in GitLab 15.6. Color string `json:"color"` @@ -111,6 +112,7 @@ type CreateBroadcastMessageOptions struct { TargetPath *string `url:"target_path,omitempty" json:"target_path,omitempty"` BroadcastType *string `url:"broadcast_type,omitempty" json:"broadcast_type,omitempty"` Dismissable *bool `url:"dismissable,omitempty" json:"dismissable,omitempty"` + Theme *string `url:"theme,omitempty" json:"theme,omitempty"` // Deprecated: This parameter was removed in GitLab 15.6. Color *string `url:"color,omitempty" json:"color,omitempty"` @@ -149,6 +151,7 @@ type UpdateBroadcastMessageOptions struct { TargetPath *string `url:"target_path,omitempty" json:"target_path,omitempty"` BroadcastType *string `url:"broadcast_type,omitempty" json:"broadcast_type,omitempty"` Dismissable *bool `url:"dismissable,omitempty" json:"dismissable,omitempty"` + Theme *string `url:"theme,omitempty" json:"theme,omitempty"` // Deprecated: This parameter was removed in GitLab 15.6. Color *string `url:"color,omitempty" json:"color,omitempty"` diff --git a/vendor/gitlab.com/gitlab-org/api/client-go/bulk_imports.go b/vendor/gitlab.com/gitlab-org/api/client-go/bulk_imports.go new file mode 100644 index 0000000000..4786135e3a --- /dev/null +++ b/vendor/gitlab.com/gitlab-org/api/client-go/bulk_imports.go @@ -0,0 +1,72 @@ +package gitlab + +import ( + "net/http" + "time" +) + +// BulkImportsService handles communication with GitLab's direct transfer API. +// +// GitLab API docs: https://docs.gitlab.com/ee/api/bulk_imports.html +type BulkImportsService struct { + client *Client +} + +// BulkImportStartMigrationConfiguration represents the available configuration options to start a migration. +// +// GitLab API docs: https://docs.gitlab.com/ee/api/bulk_imports.html#start-a-new-group-or-project-migration +type BulkImportStartMigrationConfiguration struct { + URL *string `json:"url,omitempty"` + AccessToken *string `json:"access_token,omitempty"` +} + +// BulkImportStartMigrationEntity represents the available entity options to start a migration. +// +// GitLab API docs: https://docs.gitlab.com/ee/api/bulk_imports.html#start-a-new-group-or-project-migration +type BulkImportStartMigrationEntity struct { + SourceType *string `json:"source_type,omitempty"` + SourceFullPath *string `json:"source_full_path,omitempty"` + DestinationSlug *string `json:"destination_slug,omitempty"` + DestinationNamespace *string `json:"destination_namespace,omitempty"` + MigrateProjects *bool `json:"migrate_projects,omitempty"` + MigrateMemberships *bool `json:"migrate_memberships,omitempty"` +} + +// BulkImportStartMigrationOptions represents the available start migration options. +// +// GitLab API docs: https://docs.gitlab.com/ee/api/bulk_imports.html#start-a-new-group-or-project-migration +type BulkImportStartMigrationOptions struct { + Configuration *BulkImportStartMigrationConfiguration `json:"configuration,omitempty"` + Entities []BulkImportStartMigrationEntity `json:"entities,omitempty"` +} + +// BulkImportStartMigrationResponse represents the start migration response. +// +// GitLab API docs: https://docs.gitlab.com/ee/api/bulk_imports.html#start-a-new-group-or-project-migration +type BulkImportStartMigrationResponse struct { + ID int `json:"id"` + Status string `json:"status"` + SourceType string `json:"source_type"` + SourceURL string `json:"source_url"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + HasFailures bool `json:"has_failures"` +} + +// StartMigration starts a migration. +// +// GitLab API docs: https://docs.gitlab.com/ee/api/bulk_imports.html#start-a-new-group-or-project-migration +func (b *BulkImportsService) StartMigration(startMigrationOptions *BulkImportStartMigrationOptions, options ...RequestOptionFunc) (*BulkImportStartMigrationResponse, *Response, error) { + request, err := b.client.NewRequest(http.MethodPost, "bulk_imports", startMigrationOptions, options) + if err != nil { + return nil, nil, err + } + + startMigrationResponse := new(BulkImportStartMigrationResponse) + response, err := b.client.Do(request, startMigrationResponse) + if err != nil { + return nil, response, err + } + + return startMigrationResponse, response, nil +} diff --git a/vendor/github.com/xanzy/go-gitlab/ci_yml_templates.go b/vendor/gitlab.com/gitlab-org/api/client-go/ci_yml_templates.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/ci_yml_templates.go rename to vendor/gitlab.com/gitlab-org/api/client-go/ci_yml_templates.go diff --git a/vendor/github.com/xanzy/go-gitlab/client_options.go b/vendor/gitlab.com/gitlab-org/api/client-go/client_options.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/client_options.go rename to vendor/gitlab.com/gitlab-org/api/client-go/client_options.go diff --git a/vendor/github.com/xanzy/go-gitlab/cluster_agents.go b/vendor/gitlab.com/gitlab-org/api/client-go/cluster_agents.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/cluster_agents.go rename to vendor/gitlab.com/gitlab-org/api/client-go/cluster_agents.go diff --git a/vendor/github.com/xanzy/go-gitlab/commits.go b/vendor/gitlab.com/gitlab-org/api/client-go/commits.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/commits.go rename to vendor/gitlab.com/gitlab-org/api/client-go/commits.go diff --git a/vendor/github.com/xanzy/go-gitlab/container_registry.go b/vendor/gitlab.com/gitlab-org/api/client-go/container_registry.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/container_registry.go rename to vendor/gitlab.com/gitlab-org/api/client-go/container_registry.go diff --git a/vendor/github.com/xanzy/go-gitlab/custom_attributes.go b/vendor/gitlab.com/gitlab-org/api/client-go/custom_attributes.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/custom_attributes.go rename to vendor/gitlab.com/gitlab-org/api/client-go/custom_attributes.go diff --git a/vendor/gitlab.com/gitlab-org/api/client-go/dependency_list_export.go b/vendor/gitlab.com/gitlab-org/api/client-go/dependency_list_export.go new file mode 100644 index 0000000000..c1e786e8d9 --- /dev/null +++ b/vendor/gitlab.com/gitlab-org/api/client-go/dependency_list_export.go @@ -0,0 +1,122 @@ +package gitlab + +import ( + "bytes" + "fmt" + "io" + "net/http" +) + +type DependencyListExportService struct { + client *Client +} + +// CreateDependencyListExportOptions represents the available CreateDependencyListExport() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/dependency_list_export.html#create-a-pipeline-level-dependency-list-export +type CreateDependencyListExportOptions struct { + ExportType *string `url:"export_type" json:"export_type"` +} + +// DependencyListExport represents a request for a GitLab project's dependency list. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/dependency_list_export.html#create-a-pipeline-level-dependency-list-export +type DependencyListExport struct { + ID int `json:"id"` + HasFinished bool `json:"has_finished"` + Self string `json:"self"` + Download string `json:"download"` +} + +const defaultExportType = "sbom" + +// CreateDependencyListExport creates a new CycloneDX JSON export for all the project dependencies +// detected in a pipeline. +// +// If an authenticated user does not have permission to read_dependency, this request returns a 403 +// Forbidden status code. +// +// SBOM exports can be only accessed by the export’s author. +// +// GitLab docs: +// https://docs.gitlab.com/ee/api/dependency_list_export.html#create-a-pipeline-level-dependency-list-export +func (s *DependencyListExportService) CreateDependencyListExport(pipelineID int, opt *CreateDependencyListExportOptions, options ...RequestOptionFunc) (*DependencyListExport, *Response, error) { + // POST /pipelines/:id/dependency_list_exports + createExportPath := fmt.Sprintf("pipelines/%d/dependency_list_exports", pipelineID) + + if opt == nil { + opt = &CreateDependencyListExportOptions{} + } + if opt.ExportType == nil { + opt.ExportType = Ptr(defaultExportType) + } + + req, err := s.client.NewRequest(http.MethodPost, createExportPath, opt, options) + if err != nil { + return nil, nil, err + } + + export := new(DependencyListExport) + resp, err := s.client.Do(req, &export) + if err != nil { + return nil, resp, err + } + + return export, resp, nil +} + +// GetDependencyListExport gets metadata about a single dependency list export. +// +// GitLab docs: +// https://docs.gitlab.com/ee/api/dependency_list_export.html#get-single-dependency-list-export +func (s *DependencyListExportService) GetDependencyListExport(id int, options ...RequestOptionFunc) (*DependencyListExport, *Response, error) { + // GET /dependency_list_exports/:id + getExportPath := fmt.Sprintf("dependency_list_exports/%d", id) + + req, err := s.client.NewRequest(http.MethodGet, getExportPath, nil, options) + if err != nil { + return nil, nil, err + } + + export := new(DependencyListExport) + resp, err := s.client.Do(req, &export) + if err != nil { + return nil, resp, err + } + + return export, resp, nil +} + +// DownloadDependencyListExport downloads a single dependency list export. +// +// The github.com/CycloneDX/cyclonedx-go package can be used to parse the data from the returned io.Reader. +// +// sbom := new(cdx.BOM) +// decoder := cdx.NewBOMDecoder(reader, cdx.BOMFileFormatJSON) +// +// if err = decoder.Decode(sbom); err != nil { +// panic(err) +// } +// +// GitLab docs: +// https://docs.gitlab.com/ee/api/dependency_list_export.html#download-dependency-list-export +func (s *DependencyListExportService) DownloadDependencyListExport(id int, options ...RequestOptionFunc) (io.Reader, *Response, error) { + // GET /dependency_list_exports/:id/download + downloadExportPath := fmt.Sprintf("dependency_list_exports/%d/download", id) + + req, err := s.client.NewRequest(http.MethodGet, downloadExportPath, nil, options) + if err != nil { + return nil, nil, err + } + + var sbomBuffer bytes.Buffer + resp, err := s.client.Do(req, &sbomBuffer) + if err != nil { + return nil, resp, err + } + + return &sbomBuffer, resp, nil +} diff --git a/vendor/github.com/xanzy/go-gitlab/deploy_keys.go b/vendor/gitlab.com/gitlab-org/api/client-go/deploy_keys.go similarity index 91% rename from vendor/github.com/xanzy/go-gitlab/deploy_keys.go rename to vendor/gitlab.com/gitlab-org/api/client-go/deploy_keys.go index e343bef980..341689b2d6 100644 --- a/vendor/github.com/xanzy/go-gitlab/deploy_keys.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/deploy_keys.go @@ -62,11 +62,14 @@ func (k DeployKeyProject) String() string { // ProjectDeployKey represents a GitLab project deploy key. type ProjectDeployKey struct { - ID int `json:"id"` - Title string `json:"title"` - Key string `json:"key"` - CreatedAt *time.Time `json:"created_at"` - CanPush bool `json:"can_push"` + ID int `json:"id"` + Title string `json:"title"` + Key string `json:"key"` + Fingerprint string `json:"fingerprint"` + FingerprintSHA256 string `json:"fingerprint_sha256"` + CreatedAt *time.Time `json:"created_at"` + CanPush bool `json:"can_push"` + ExpiresAt *time.Time `json:"expires_at"` } func (k ProjectDeployKey) String() string { @@ -162,11 +165,12 @@ func (s *DeployKeysService) GetDeployKey(pid interface{}, deployKey int, options // AddDeployKeyOptions represents the available ADDDeployKey() options. // // GitLab API docs: -// https://docs.gitlab.com/ee/api/deploy_keys.html#add-deploy-key +// https://docs.gitlab.com/ee/api/deploy_keys.html#add-deploy-key-for-a-project type AddDeployKeyOptions struct { - Title *string `url:"title,omitempty" json:"title,omitempty"` - Key *string `url:"key,omitempty" json:"key,omitempty"` - CanPush *bool `url:"can_push,omitempty" json:"can_push,omitempty"` + Key *string `url:"key,omitempty" json:"key,omitempty"` + Title *string `url:"title,omitempty" json:"title,omitempty"` + CanPush *bool `url:"can_push,omitempty" json:"can_push,omitempty"` + ExpiresAt *time.Time `url:"expires_at,omitempty" json:"expires_at,omitempty"` } // AddDeployKey creates a new deploy key for a project. If deploy key already @@ -174,7 +178,7 @@ type AddDeployKeyOptions struct { // original one was is accessible by same user. // // GitLab API docs: -// https://docs.gitlab.com/ee/api/deploy_keys.html#add-deploy-key +// https://docs.gitlab.com/ee/api/deploy_keys.html#add-deploy-key-for-a-project func (s *DeployKeysService) AddDeployKey(pid interface{}, opt *AddDeployKeyOptions, options ...RequestOptionFunc) (*ProjectDeployKey, *Response, error) { project, err := parseID(pid) if err != nil { diff --git a/vendor/github.com/xanzy/go-gitlab/deploy_tokens.go b/vendor/gitlab.com/gitlab-org/api/client-go/deploy_tokens.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/deploy_tokens.go rename to vendor/gitlab.com/gitlab-org/api/client-go/deploy_tokens.go diff --git a/vendor/github.com/xanzy/go-gitlab/deployments.go b/vendor/gitlab.com/gitlab-org/api/client-go/deployments.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/deployments.go rename to vendor/gitlab.com/gitlab-org/api/client-go/deployments.go diff --git a/vendor/github.com/xanzy/go-gitlab/deployments_merge_requests.go b/vendor/gitlab.com/gitlab-org/api/client-go/deployments_merge_requests.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/deployments_merge_requests.go rename to vendor/gitlab.com/gitlab-org/api/client-go/deployments_merge_requests.go diff --git a/vendor/github.com/xanzy/go-gitlab/discussions.go b/vendor/gitlab.com/gitlab-org/api/client-go/discussions.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/discussions.go rename to vendor/gitlab.com/gitlab-org/api/client-go/discussions.go diff --git a/vendor/github.com/xanzy/go-gitlab/dockerfile_templates.go b/vendor/gitlab.com/gitlab-org/api/client-go/dockerfile_templates.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/dockerfile_templates.go rename to vendor/gitlab.com/gitlab-org/api/client-go/dockerfile_templates.go diff --git a/vendor/github.com/xanzy/go-gitlab/dora_metrics.go b/vendor/gitlab.com/gitlab-org/api/client-go/dora_metrics.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/dora_metrics.go rename to vendor/gitlab.com/gitlab-org/api/client-go/dora_metrics.go diff --git a/vendor/github.com/xanzy/go-gitlab/draft_notes.go b/vendor/gitlab.com/gitlab-org/api/client-go/draft_notes.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/draft_notes.go rename to vendor/gitlab.com/gitlab-org/api/client-go/draft_notes.go diff --git a/vendor/github.com/xanzy/go-gitlab/environments.go b/vendor/gitlab.com/gitlab-org/api/client-go/environments.go similarity index 74% rename from vendor/github.com/xanzy/go-gitlab/environments.go rename to vendor/gitlab.com/gitlab-org/api/client-go/environments.go index b6d902f86f..091fbb135d 100644 --- a/vendor/github.com/xanzy/go-gitlab/environments.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/environments.go @@ -34,16 +34,22 @@ type EnvironmentsService struct { // // GitLab API docs: https://docs.gitlab.com/ee/api/environments.html type Environment struct { - ID int `json:"id"` - Name string `json:"name"` - Slug string `json:"slug"` - State string `json:"state"` - Tier string `json:"tier"` - ExternalURL string `json:"external_url"` - Project *Project `json:"project"` - CreatedAt *time.Time `json:"created_at"` - UpdatedAt *time.Time `json:"updated_at"` - LastDeployment *Deployment `json:"last_deployment"` + ID int `json:"id"` + Name string `json:"name"` + Slug string `json:"slug"` + Description string `json:"description"` + State string `json:"state"` + Tier string `json:"tier"` + ExternalURL string `json:"external_url"` + Project *Project `json:"project"` + CreatedAt *time.Time `json:"created_at"` + UpdatedAt *time.Time `json:"updated_at"` + LastDeployment *Deployment `json:"last_deployment"` + ClusterAgent *Agent `json:"cluster_agent"` + KubernetesNamespace string `json:"kubernetes_namespace"` + FluxResourcePath string `json:"flux_resource_path"` + AutoStopAt *time.Time `json:"auto_stop_at"` + AutoStopSetting string `json:"auto_stop_setting"` } func (env Environment) String() string { @@ -117,9 +123,14 @@ func (s *EnvironmentsService) GetEnvironment(pid interface{}, environment int, o // GitLab API docs: // https://docs.gitlab.com/ee/api/environments.html#create-a-new-environment type CreateEnvironmentOptions struct { - Name *string `url:"name,omitempty" json:"name,omitempty"` - ExternalURL *string `url:"external_url,omitempty" json:"external_url,omitempty"` - Tier *string `url:"tier,omitempty" json:"tier,omitempty"` + Name *string `url:"name,omitempty" json:"name,omitempty"` + Description *string `url:"description,omitempty" json:"description,omitempty"` + ExternalURL *string `url:"external_url,omitempty" json:"external_url,omitempty"` + Tier *string `url:"tier,omitempty" json:"tier,omitempty"` + ClusterAgentID *int `url:"cluster_agent_id,omitempty" json:"cluster_agent_id,omitempty"` + KubernetesNamespace *string `url:"kubernetes_namespace,omitempty" json:"kubernetes_namespace,omitempty"` + FluxResourcePath *string `url:"flux_resource_path,omitempty" json:"flux_resource_path,omitempty"` + AutoStopSetting *string `url:"auto_stop_setting,omitempty" json:"auto_stop_setting,omitempty"` } // CreateEnvironment adds an environment to a project. This is an idempotent @@ -155,9 +166,14 @@ func (s *EnvironmentsService) CreateEnvironment(pid interface{}, opt *CreateEnvi // GitLab API docs: // https://docs.gitlab.com/ee/api/environments.html#update-an-existing-environment type EditEnvironmentOptions struct { - Name *string `url:"name,omitempty" json:"name,omitempty"` - ExternalURL *string `url:"external_url,omitempty" json:"external_url,omitempty"` - Tier *string `url:"tier,omitempty" json:"tier,omitempty"` + Name *string `url:"name,omitempty" json:"name,omitempty"` + Description *string `url:"description,omitempty" json:"description,omitempty"` + ExternalURL *string `url:"external_url,omitempty" json:"external_url,omitempty"` + Tier *string `url:"tier,omitempty" json:"tier,omitempty"` + ClusterAgentID *int `url:"cluster_agent_id,omitempty" json:"cluster_agent_id,omitempty"` + KubernetesNamespace *string `url:"kubernetes_namespace,omitempty" json:"kubernetes_namespace,omitempty"` + FluxResourcePath *string `url:"flux_resource_path,omitempty" json:"flux_resource_path,omitempty"` + AutoStopSetting *string `url:"auto_stop_setting,omitempty" json:"auto_stop_setting,omitempty"` } // EditEnvironment updates a project team environment to a specified access level.. diff --git a/vendor/github.com/xanzy/go-gitlab/epic_issues.go b/vendor/gitlab.com/gitlab-org/api/client-go/epic_issues.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/epic_issues.go rename to vendor/gitlab.com/gitlab-org/api/client-go/epic_issues.go diff --git a/vendor/github.com/xanzy/go-gitlab/epics.go b/vendor/gitlab.com/gitlab-org/api/client-go/epics.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/epics.go rename to vendor/gitlab.com/gitlab-org/api/client-go/epics.go diff --git a/vendor/github.com/xanzy/go-gitlab/error_tracking.go b/vendor/gitlab.com/gitlab-org/api/client-go/error_tracking.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/error_tracking.go rename to vendor/gitlab.com/gitlab-org/api/client-go/error_tracking.go diff --git a/vendor/github.com/xanzy/go-gitlab/event_parsing.go b/vendor/gitlab.com/gitlab-org/api/client-go/event_parsing.go similarity index 98% rename from vendor/github.com/xanzy/go-gitlab/event_parsing.go rename to vendor/gitlab.com/gitlab-org/api/client-go/event_parsing.go index 0f474211d3..eb81fa05cb 100644 --- a/vendor/github.com/xanzy/go-gitlab/event_parsing.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/event_parsing.go @@ -91,7 +91,7 @@ func HookEventType(r *http.Request) EventType { // Example usage: // // func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { -// payload, err := ioutil.ReadAll(r.Body) +// payload, err := io.ReadAll(r.Body) // if err != nil { ... } // event, err := gitlab.ParseHook(gitlab.HookEventType(r), payload) // if err != nil { ... } @@ -119,7 +119,7 @@ func ParseHook(eventType EventType, payload []byte) (event interface{}, err erro // Example usage: // // func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { -// payload, err := ioutil.ReadAll(r.Body) +// payload, err := io.ReadAll(r.Body) // if err != nil { ... } // event, err := gitlab.ParseSystemhook(payload) // if err != nil { ... } @@ -203,7 +203,7 @@ func WebhookEventType(r *http.Request) EventType { // Example usage: // // func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { -// payload, err := ioutil.ReadAll(r.Body) +// payload, err := io.ReadAll(r.Body) // if err != nil { ... } // event, err := gitlab.ParseWebhook(gitlab.HookEventType(r), payload) // if err != nil { ... } diff --git a/vendor/github.com/xanzy/go-gitlab/event_systemhook_types.go b/vendor/gitlab.com/gitlab-org/api/client-go/event_systemhook_types.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/event_systemhook_types.go rename to vendor/gitlab.com/gitlab-org/api/client-go/event_systemhook_types.go diff --git a/vendor/github.com/xanzy/go-gitlab/event_webhook_types.go b/vendor/gitlab.com/gitlab-org/api/client-go/event_webhook_types.go similarity index 99% rename from vendor/github.com/xanzy/go-gitlab/event_webhook_types.go rename to vendor/gitlab.com/gitlab-org/api/client-go/event_webhook_types.go index c4a8e4aeb9..deded26550 100644 --- a/vendor/github.com/xanzy/go-gitlab/event_webhook_types.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/event_webhook_types.go @@ -721,6 +721,10 @@ type MergeEvent struct { Previous int `json:"previous"` Current int `json:"current"` } `json:"last_edited_by_id"` + MergeStatus struct { + Previous string `json:"previous"` + Current string `json:"current"` + } `json:"merge_status"` MilestoneID struct { Previous int `json:"previous"` Current int `json:"current"` @@ -882,7 +886,7 @@ type PipelineEvent struct { Email string `json:"email"` } `json:"author"` } `json:"commit"` - SourcePipline struct { + SourcePipeline struct { Project struct { ID int `json:"id"` WebURL string `json:"web_url"` diff --git a/vendor/github.com/xanzy/go-gitlab/events.go b/vendor/gitlab.com/gitlab-org/api/client-go/events.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/events.go rename to vendor/gitlab.com/gitlab-org/api/client-go/events.go diff --git a/vendor/github.com/xanzy/go-gitlab/external_status_checks.go b/vendor/gitlab.com/gitlab-org/api/client-go/external_status_checks.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/external_status_checks.go rename to vendor/gitlab.com/gitlab-org/api/client-go/external_status_checks.go diff --git a/vendor/github.com/xanzy/go-gitlab/feature_flags.go b/vendor/gitlab.com/gitlab-org/api/client-go/feature_flags.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/feature_flags.go rename to vendor/gitlab.com/gitlab-org/api/client-go/feature_flags.go diff --git a/vendor/github.com/xanzy/go-gitlab/freeze_periods.go b/vendor/gitlab.com/gitlab-org/api/client-go/freeze_periods.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/freeze_periods.go rename to vendor/gitlab.com/gitlab-org/api/client-go/freeze_periods.go diff --git a/vendor/github.com/xanzy/go-gitlab/generic_packages.go b/vendor/gitlab.com/gitlab-org/api/client-go/generic_packages.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/generic_packages.go rename to vendor/gitlab.com/gitlab-org/api/client-go/generic_packages.go diff --git a/vendor/github.com/xanzy/go-gitlab/geo_nodes.go b/vendor/gitlab.com/gitlab-org/api/client-go/geo_nodes.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/geo_nodes.go rename to vendor/gitlab.com/gitlab-org/api/client-go/geo_nodes.go diff --git a/vendor/github.com/xanzy/go-gitlab/gitignore_templates.go b/vendor/gitlab.com/gitlab-org/api/client-go/gitignore_templates.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/gitignore_templates.go rename to vendor/gitlab.com/gitlab-org/api/client-go/gitignore_templates.go diff --git a/vendor/github.com/xanzy/go-gitlab/gitlab.go b/vendor/gitlab.com/gitlab-org/api/client-go/gitlab.go similarity index 98% rename from vendor/github.com/xanzy/go-gitlab/gitlab.go rename to vendor/gitlab.com/gitlab-org/api/client-go/gitlab.go index 19ed3eadb9..24a6fd8841 100644 --- a/vendor/github.com/xanzy/go-gitlab/gitlab.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/gitlab.go @@ -117,11 +117,13 @@ type Client struct { Boards *IssueBoardsService Branches *BranchesService BroadcastMessage *BroadcastMessagesService + BulkImports *BulkImportsService CIYMLTemplate *CIYMLTemplatesService ClusterAgents *ClusterAgentsService Commits *CommitsService ContainerRegistry *ContainerRegistryService CustomAttribute *CustomAttributesService + DependencyListExport *DependencyListExportService DeployKeys *DeployKeysService DeployTokens *DeployTokensService DeploymentMergeRequests *DeploymentMergeRequestsService @@ -153,6 +155,7 @@ type Client struct { GroupMilestones *GroupMilestonesService GroupProtectedEnvironments *GroupProtectedEnvironmentsService GroupRepositoryStorageMove *GroupRepositoryStorageMoveService + GroupSecuritySettings *GroupSecuritySettingsService GroupSSHCertificates *GroupSSHCertificatesService GroupVariables *GroupVariablesService GroupWikis *GroupWikisService @@ -195,6 +198,7 @@ type Client struct { ProjectFeatureFlags *ProjectFeatureFlagService ProjectImportExport *ProjectImportExportService ProjectIterations *ProjectIterationsService + ProjectMarkdownUploads *ProjectMarkdownUploadsService ProjectMembers *ProjectMembersService ProjectMirrors *ProjectMirrorService ProjectRepositoryStorageMove *ProjectRepositoryStorageMoveService @@ -355,11 +359,13 @@ func newClient(options ...ClientOptionFunc) (*Client, error) { c.Boards = &IssueBoardsService{client: c} c.Branches = &BranchesService{client: c} c.BroadcastMessage = &BroadcastMessagesService{client: c} + c.BulkImports = &BulkImportsService{client: c} c.CIYMLTemplate = &CIYMLTemplatesService{client: c} c.ClusterAgents = &ClusterAgentsService{client: c} c.Commits = &CommitsService{client: c} c.ContainerRegistry = &ContainerRegistryService{client: c} c.CustomAttribute = &CustomAttributesService{client: c} + c.DependencyListExport = &DependencyListExportService{client: c} c.DeployKeys = &DeployKeysService{client: c} c.DeployTokens = &DeployTokensService{client: c} c.DeploymentMergeRequests = &DeploymentMergeRequestsService{client: c} @@ -391,6 +397,7 @@ func newClient(options ...ClientOptionFunc) (*Client, error) { c.GroupMilestones = &GroupMilestonesService{client: c} c.GroupProtectedEnvironments = &GroupProtectedEnvironmentsService{client: c} c.GroupRepositoryStorageMove = &GroupRepositoryStorageMoveService{client: c} + c.GroupSecuritySettings = &GroupSecuritySettingsService{client: c} c.GroupSSHCertificates = &GroupSSHCertificatesService{client: c} c.GroupVariables = &GroupVariablesService{client: c} c.GroupWikis = &GroupWikisService{client: c} @@ -433,6 +440,7 @@ func newClient(options ...ClientOptionFunc) (*Client, error) { c.ProjectFeatureFlags = &ProjectFeatureFlagService{client: c} c.ProjectImportExport = &ProjectImportExportService{client: c} c.ProjectIterations = &ProjectIterationsService{client: c} + c.ProjectMarkdownUploads = &ProjectMarkdownUploadsService{client: c} c.ProjectMembers = &ProjectMembersService{client: c} c.ProjectMirrors = &ProjectMirrorService{client: c} c.ProjectRepositoryStorageMove = &ProjectRepositoryStorageMoveService{client: c} diff --git a/vendor/github.com/xanzy/go-gitlab/group_access_tokens.go b/vendor/gitlab.com/gitlab-org/api/client-go/group_access_tokens.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/group_access_tokens.go rename to vendor/gitlab.com/gitlab-org/api/client-go/group_access_tokens.go diff --git a/vendor/github.com/xanzy/go-gitlab/group_badges.go b/vendor/gitlab.com/gitlab-org/api/client-go/group_badges.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/group_badges.go rename to vendor/gitlab.com/gitlab-org/api/client-go/group_badges.go diff --git a/vendor/github.com/xanzy/go-gitlab/group_boards.go b/vendor/gitlab.com/gitlab-org/api/client-go/group_boards.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/group_boards.go rename to vendor/gitlab.com/gitlab-org/api/client-go/group_boards.go diff --git a/vendor/github.com/xanzy/go-gitlab/group_clusters.go b/vendor/gitlab.com/gitlab-org/api/client-go/group_clusters.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/group_clusters.go rename to vendor/gitlab.com/gitlab-org/api/client-go/group_clusters.go diff --git a/vendor/github.com/xanzy/go-gitlab/group_epic_boards.go b/vendor/gitlab.com/gitlab-org/api/client-go/group_epic_boards.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/group_epic_boards.go rename to vendor/gitlab.com/gitlab-org/api/client-go/group_epic_boards.go diff --git a/vendor/github.com/xanzy/go-gitlab/group_hooks.go b/vendor/gitlab.com/gitlab-org/api/client-go/group_hooks.go similarity index 95% rename from vendor/github.com/xanzy/go-gitlab/group_hooks.go rename to vendor/gitlab.com/gitlab-org/api/client-go/group_hooks.go index 414a8d0864..320f03840d 100644 --- a/vendor/github.com/xanzy/go-gitlab/group_hooks.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/group_hooks.go @@ -229,6 +229,25 @@ func (s *GroupsService) DeleteGroupHook(pid interface{}, hook int, options ...Re return s.client.Do(req, nil) } +// TriggerTestGroupHook triggers a test hook for a specified group. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/group_webhooks.html#trigger-a-test-group-hook +func (s *GroupsService) TriggerTestGroupHook(pid interface{}, hook int, trigger GroupHookTrigger, options ...RequestOptionFunc) (*Response, error) { + group, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("groups/%s/hooks/%d/test/%s", PathEscape(group), hook, trigger) + + req, err := s.client.NewRequest(http.MethodPost, u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + // SetGroupCustomHeader creates or updates a group custom webhook header. // // GitLab API docs: diff --git a/vendor/github.com/xanzy/go-gitlab/group_import_export.go b/vendor/gitlab.com/gitlab-org/api/client-go/group_import_export.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/group_import_export.go rename to vendor/gitlab.com/gitlab-org/api/client-go/group_import_export.go diff --git a/vendor/github.com/xanzy/go-gitlab/group_iterations.go b/vendor/gitlab.com/gitlab-org/api/client-go/group_iterations.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/group_iterations.go rename to vendor/gitlab.com/gitlab-org/api/client-go/group_iterations.go diff --git a/vendor/github.com/xanzy/go-gitlab/group_labels.go b/vendor/gitlab.com/gitlab-org/api/client-go/group_labels.go similarity index 82% rename from vendor/github.com/xanzy/go-gitlab/group_labels.go rename to vendor/gitlab.com/gitlab-org/api/client-go/group_labels.go index 5a390269b1..8004bb2d0e 100644 --- a/vendor/github.com/xanzy/go-gitlab/group_labels.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/group_labels.go @@ -79,12 +79,12 @@ func (s *GroupLabelsService) ListGroupLabels(gid interface{}, opt *ListGroupLabe // // GitLab API docs: // https://docs.gitlab.com/ee/api/group_labels.html#get-a-single-group-label -func (s *GroupLabelsService) GetGroupLabel(gid interface{}, labelID interface{}, options ...RequestOptionFunc) (*GroupLabel, *Response, error) { +func (s *GroupLabelsService) GetGroupLabel(gid interface{}, lid interface{}, options ...RequestOptionFunc) (*GroupLabel, *Response, error) { group, err := parseID(gid) if err != nil { return nil, nil, err } - label, err := parseID(labelID) + label, err := parseID(lid) if err != nil { return nil, nil, err } @@ -108,7 +108,12 @@ func (s *GroupLabelsService) GetGroupLabel(gid interface{}, labelID interface{}, // // GitLab API docs: // https://docs.gitlab.com/ee/api/group_labels.html#create-a-new-group-label -type CreateGroupLabelOptions CreateLabelOptions +type CreateGroupLabelOptions struct { + Name *string `url:"name,omitempty" json:"name,omitempty"` + Color *string `url:"color,omitempty" json:"color,omitempty"` + Description *string `url:"description,omitempty" json:"description,omitempty"` + Priority *int `url:"priority,omitempty" json:"priority,omitempty"` +} // CreateGroupLabel creates a new label for given group with given name and // color. @@ -140,7 +145,9 @@ func (s *GroupLabelsService) CreateGroupLabel(gid interface{}, opt *CreateGroupL // // GitLab API docs: // https://docs.gitlab.com/ee/api/group_labels.html#delete-a-group-label -type DeleteGroupLabelOptions DeleteLabelOptions +type DeleteGroupLabelOptions struct { + Name *string `url:"name,omitempty" json:"name,omitempty"` +} // DeleteGroupLabel deletes a group label given by its name or ID. // @@ -173,20 +180,34 @@ func (s *GroupLabelsService) DeleteGroupLabel(gid interface{}, lid interface{}, // // GitLab API docs: // https://docs.gitlab.com/ee/api/group_labels.html#update-a-group-label -type UpdateGroupLabelOptions UpdateLabelOptions +type UpdateGroupLabelOptions struct { + Name *string `url:"name,omitempty" json:"name,omitempty"` + NewName *string `url:"new_name,omitempty" json:"new_name,omitempty"` + Color *string `url:"color,omitempty" json:"color,omitempty"` + Description *string `url:"description,omitempty" json:"description,omitempty"` + Priority *int `url:"priority,omitempty" json:"priority,omitempty"` +} // UpdateGroupLabel updates an existing label with new name or now color. At least // one parameter is required, to update the label. // // GitLab API docs: // https://docs.gitlab.com/ee/api/group_labels.html#update-a-group-label -func (s *GroupLabelsService) UpdateGroupLabel(gid interface{}, opt *UpdateGroupLabelOptions, options ...RequestOptionFunc) (*GroupLabel, *Response, error) { +func (s *GroupLabelsService) UpdateGroupLabel(gid interface{}, lid interface{}, opt *UpdateGroupLabelOptions, options ...RequestOptionFunc) (*GroupLabel, *Response, error) { group, err := parseID(gid) if err != nil { return nil, nil, err } u := fmt.Sprintf("groups/%s/labels", PathEscape(group)) + if lid != nil { + label, err := parseID(lid) + if err != nil { + return nil, nil, err + } + u = fmt.Sprintf("groups/%s/labels/%s", PathEscape(group), PathEscape(label)) + } + req, err := s.client.NewRequest(http.MethodPut, u, opt, options) if err != nil { return nil, nil, err @@ -207,12 +228,12 @@ func (s *GroupLabelsService) UpdateGroupLabel(gid interface{}, opt *UpdateGroupL // // GitLab API docs: // https://docs.gitlab.com/ee/api/group_labels.html#subscribe-to-a-group-label -func (s *GroupLabelsService) SubscribeToGroupLabel(gid interface{}, labelID interface{}, options ...RequestOptionFunc) (*GroupLabel, *Response, error) { +func (s *GroupLabelsService) SubscribeToGroupLabel(gid interface{}, lid interface{}, options ...RequestOptionFunc) (*GroupLabel, *Response, error) { group, err := parseID(gid) if err != nil { return nil, nil, err } - label, err := parseID(labelID) + label, err := parseID(lid) if err != nil { return nil, nil, err } @@ -238,12 +259,12 @@ func (s *GroupLabelsService) SubscribeToGroupLabel(gid interface{}, labelID inte // // GitLab API docs: // https://docs.gitlab.com/ee/api/group_labels.html#unsubscribe-from-a-group-label -func (s *GroupLabelsService) UnsubscribeFromGroupLabel(gid interface{}, labelID interface{}, options ...RequestOptionFunc) (*Response, error) { +func (s *GroupLabelsService) UnsubscribeFromGroupLabel(gid interface{}, lid interface{}, options ...RequestOptionFunc) (*Response, error) { group, err := parseID(gid) if err != nil { return nil, err } - label, err := parseID(labelID) + label, err := parseID(lid) if err != nil { return nil, err } diff --git a/vendor/github.com/xanzy/go-gitlab/group_members.go b/vendor/gitlab.com/gitlab-org/api/client-go/group_members.go similarity index 84% rename from vendor/github.com/xanzy/go-gitlab/group_members.go rename to vendor/gitlab.com/gitlab-org/api/client-go/group_members.go index cdf225c3d8..109b2056f9 100644 --- a/vendor/github.com/xanzy/go-gitlab/group_members.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/group_members.go @@ -30,17 +30,6 @@ type GroupMembersService struct { client *Client } -// GroupMemberSAMLIdentity represents the SAML Identity link for the group member. -// -// GitLab API docs: https://docs.gitlab.com/ee/api/members.html#list-all-members-of-a-group-or-project -// Gitlab MR for API change: https://gitlab.com/gitlab-org/gitlab/-/merge_requests/20357 -// Gitlab MR for API Doc change: https://gitlab.com/gitlab-org/gitlab/-/merge_requests/25652 -type GroupMemberSAMLIdentity struct { - ExternUID string `json:"extern_uid"` - Provider string `json:"provider"` - SAMLProviderID int `json:"saml_provider_id"` -} - // GroupMember represents a GitLab group member. // // GitLab API docs: https://docs.gitlab.com/ee/api/members.html @@ -59,6 +48,50 @@ type GroupMember struct { MemberRole *MemberRole `json:"member_role"` } +// GroupMemberSAMLIdentity represents the SAML Identity link for the group member. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/members.html#list-all-members-of-a-group-or-project +type GroupMemberSAMLIdentity struct { + ExternUID string `json:"extern_uid"` + Provider string `json:"provider"` + SAMLProviderID int `json:"saml_provider_id"` +} + +// BillableGroupMember represents a GitLab billable group member. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/members.html#list-all-billable-members-of-a-group +type BillableGroupMember struct { + ID int `json:"id"` + Username string `json:"username"` + Name string `json:"name"` + State string `json:"state"` + AvatarURL string `json:"avatar_url"` + WebURL string `json:"web_url"` + Email string `json:"email"` + LastActivityOn *ISOTime `json:"last_activity_on"` + MembershipType string `json:"membership_type"` + Removable bool `json:"removable"` + CreatedAt *time.Time `json:"created_at"` + IsLastOwner bool `json:"is_last_owner"` + LastLoginAt *time.Time `json:"last_login_at"` +} + +// BillableUserMembership represents a Membership of a billable user of a group +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/members.html#list-memberships-for-a-billable-member-of-a-group +type BillableUserMembership struct { + ID int `json:"id"` + SourceID int `json:"source_id"` + SourceFullName string `json:"source_full_name"` + SourceMembersURL string `json:"source_members_url"` + CreatedAt *time.Time `json:"created_at"` + ExpiresAt *time.Time `json:"expires_at"` + AccessLevel *AccessLevelDetails `json:"access_level"` +} + // ListGroupMembersOptions represents the available ListGroupMembers() and // ListAllGroupMembers() options. // @@ -128,6 +161,7 @@ func (s *GroupsService) ListAllGroupMembers(gid interface{}, opt *ListGroupMembe // https://docs.gitlab.com/ee/api/members.html#add-a-member-to-a-group-or-project type AddGroupMemberOptions struct { UserID *int `url:"user_id,omitempty" json:"user_id,omitempty"` + Username *string `url:"username,omitempty" json:"username,omitempty"` AccessLevel *AccessLevelValue `url:"access_level,omitempty" json:"access_level,omitempty"` ExpiresAt *string `url:"expires_at,omitempty" json:"expires_at"` MemberRoleID *int `url:"member_role_id,omitempty" json:"member_role_id,omitempty"` @@ -184,26 +218,8 @@ func (s *GroupMembersService) GetInheritedGroupMember(gid interface{}, user int, return gm, resp, err } -// BillableGroupMember represents a GitLab billable group member. -// -// GitLab API docs: https://docs.gitlab.com/ee/api/members.html#list-all-billable-members-of-a-group -type BillableGroupMember struct { - ID int `json:"id"` - Username string `json:"username"` - Name string `json:"name"` - State string `json:"state"` - AvatarURL string `json:"avatar_url"` - WebURL string `json:"web_url"` - Email string `json:"email"` - LastActivityOn *ISOTime `json:"last_activity_on"` - MembershipType string `json:"membership_type"` - Removable bool `json:"removable"` - CreatedAt *time.Time `json:"created_at"` - IsLastOwner bool `json:"is_last_owner"` - LastLoginAt *time.Time `json:"last_login_at"` -} - -// ListBillableGroupMembersOptions represents the available ListBillableGroupMembers() options. +// ListBillableGroupMembersOptions represents the available +// ListBillableGroupMembers() options. // // GitLab API docs: // https://docs.gitlab.com/ee/api/members.html#list-all-billable-members-of-a-group @@ -239,6 +255,39 @@ func (s *GroupsService) ListBillableGroupMembers(gid interface{}, opt *ListBilla return bgm, resp, nil } +// ListMembershipsForBillableGroupMemberOptions represents the available +// ListMembershipsForBillableGroupMember() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/members.html#list-memberships-for-a-billable-member-of-a-group +type ListMembershipsForBillableGroupMemberOptions = ListOptions + +// ListMembershipsForBillableGroupMember gets a list of memberships for a +// billable member of a group. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/members.html#list-memberships-for-a-billable-member-of-a-group +func (s *GroupsService) ListMembershipsForBillableGroupMember(gid interface{}, user int, opt *ListMembershipsForBillableGroupMemberOptions, options ...RequestOptionFunc) ([]*BillableUserMembership, *Response, error) { + group, err := parseID(gid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("groups/%s/billable_members/%d/memberships", PathEscape(group), user) + + req, err := s.client.NewRequest(http.MethodGet, u, opt, options) + if err != nil { + return nil, nil, err + } + + var bum []*BillableUserMembership + resp, err := s.client.Do(req, &bum) + if err != nil { + return nil, resp, err + } + + return bum, resp, nil +} + // RemoveBillableGroupMember removes a given group members that count as billable. // // GitLab API docs: @@ -365,7 +414,8 @@ func (s *GroupMembersService) EditGroupMember(gid interface{}, user int, opt *Ed // RemoveGroupMemberOptions represents the available options to remove a group member. // -// GitLab API docs: https://docs.gitlab.com/ee/api/members.html#remove-a-member-from-a-group-or-project +// GitLab API docs: +// https://docs.gitlab.com/ee/api/members.html#remove-a-member-from-a-group-or-project type RemoveGroupMemberOptions struct { SkipSubresources *bool `url:"skip_subresources,omitempty" json:"skip_subresources,omitempty"` UnassignIssuables *bool `url:"unassign_issuables,omitempty" json:"unassign_issuables,omitempty"` diff --git a/vendor/github.com/xanzy/go-gitlab/group_milestones.go b/vendor/gitlab.com/gitlab-org/api/client-go/group_milestones.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/group_milestones.go rename to vendor/gitlab.com/gitlab-org/api/client-go/group_milestones.go diff --git a/vendor/github.com/xanzy/go-gitlab/group_protected_environments.go b/vendor/gitlab.com/gitlab-org/api/client-go/group_protected_environments.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/group_protected_environments.go rename to vendor/gitlab.com/gitlab-org/api/client-go/group_protected_environments.go diff --git a/vendor/github.com/xanzy/go-gitlab/group_repository_storage_move.go b/vendor/gitlab.com/gitlab-org/api/client-go/group_repository_storage_move.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/group_repository_storage_move.go rename to vendor/gitlab.com/gitlab-org/api/client-go/group_repository_storage_move.go diff --git a/vendor/gitlab.com/gitlab-org/api/client-go/group_security_settings.go b/vendor/gitlab.com/gitlab-org/api/client-go/group_security_settings.go new file mode 100644 index 0000000000..c73b67dc1c --- /dev/null +++ b/vendor/gitlab.com/gitlab-org/api/client-go/group_security_settings.go @@ -0,0 +1,82 @@ +// +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "fmt" + "net/http" +) + +// GroupSecuritySettingsService handles communication with the Group Security Settings +// related methods of the GitLab API. +// +// Gitlab API docs: +// https://docs.gitlab.com/ee/api/group_security_settings.html +type GroupSecuritySettingsService struct { + client *Client +} + +// GroupSecuritySettings represents the group security settings data. +// +// Gitlab API docs: +// https://docs.gitlab.com/ee/api/group_security_settings.html +type GroupSecuritySettings struct { + SecretPushProtectionEnabled bool `json:"secret_push_protection_enabled"` + Errors []string `json:"errors"` +} + +// Gets a string representation of the GroupSecuritySettings data. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/group_security_settings.html +func (s GroupSecuritySettings) String() string { + return Stringify(s) +} + +// GetGroupSecuritySettingsOptions represent the request options for updating +// the group security settings. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/group_security_settings.html#update-secret_push_protection_enabled-setting +type UpdateGroupSecuritySettingsOptions struct { + SecretPushProtectionEnabled *bool `url:"secret_push_protection_enabled,omitempty" json:"secret_push_protection_enabled,omitempty"` + ProjectsToExclude *[]int `url:"projects_to_exclude,omitempty" json:"projects_to_exclude,omitempty"` +} + +// UpdateSecretPushProtectionEnabledSetting updates the secret_push_protection_enabled +// setting for the all projects in a group to the provided value. +// +// GitLab API Docs: +// https://docs.gitlab.com/ee/api/group_security_settings.html#update-secret_push_protection_enabled-setting +func (s *GroupSecuritySettingsService) UpdateSecretPushProtectionEnabledSetting(gid interface{}, opt UpdateGroupSecuritySettingsOptions, options ...RequestOptionFunc) (*GroupSecuritySettings, *Response, error) { + group, err := parseID(gid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("groups/%s/security_settings", PathEscape(group)) + + req, err := s.client.NewRequest(http.MethodPut, u, opt, options) + if err != nil { + return nil, nil, err + } + settings := new(GroupSecuritySettings) + resp, err := s.client.Do(req, &settings) + if err != nil { + return nil, resp, err + } + + return settings, resp, err +} diff --git a/vendor/github.com/xanzy/go-gitlab/group_serviceaccounts.go b/vendor/gitlab.com/gitlab-org/api/client-go/group_serviceaccounts.go similarity index 90% rename from vendor/github.com/xanzy/go-gitlab/group_serviceaccounts.go rename to vendor/gitlab.com/gitlab-org/api/client-go/group_serviceaccounts.go index 1360057a25..feba6c8ba1 100644 --- a/vendor/github.com/xanzy/go-gitlab/group_serviceaccounts.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/group_serviceaccounts.go @@ -135,18 +135,27 @@ func (s *GroupsService) CreateServiceAccountPersonalAccessToken(gid interface{}, return pat, resp, nil } +// RotateServiceAccountPersonalAccessTokenOptions represents the available RotateServiceAccountPersonalAccessToken() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/group_service_accounts.html#rotate-a-personal-access-token-for-a-service-account-user +type RotateServiceAccountPersonalAccessTokenOptions struct { + ExpiresAt *ISOTime `url:"expires_at,omitempty" json:"expires_at,omitempty"` +} + // RotateServiceAccountPersonalAccessToken rotates a Personal Access Token for a // service account user for a group. // // GitLab API docs: https://docs.gitlab.com/ee/api/groups.html#create-personal-access-token-for-service-account-user -func (s *GroupsService) RotateServiceAccountPersonalAccessToken(gid interface{}, serviceAccount, token int, options ...RequestOptionFunc) (*PersonalAccessToken, *Response, error) { +func (s *GroupsService) RotateServiceAccountPersonalAccessToken(gid interface{}, serviceAccount, token int, opt *RotateServiceAccountPersonalAccessTokenOptions, options ...RequestOptionFunc) (*PersonalAccessToken, *Response, error) { group, err := parseID(gid) if err != nil { return nil, nil, err } u := fmt.Sprintf("groups/%s/service_accounts/%d/personal_access_tokens/%d/rotate", PathEscape(group), serviceAccount, token) - req, err := s.client.NewRequest(http.MethodPost, u, nil, options) + req, err := s.client.NewRequest(http.MethodPost, u, opt, options) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/xanzy/go-gitlab/group_ssh_certificates.go b/vendor/gitlab.com/gitlab-org/api/client-go/group_ssh_certificates.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/group_ssh_certificates.go rename to vendor/gitlab.com/gitlab-org/api/client-go/group_ssh_certificates.go diff --git a/vendor/github.com/xanzy/go-gitlab/group_variables.go b/vendor/gitlab.com/gitlab-org/api/client-go/group_variables.go similarity index 97% rename from vendor/github.com/xanzy/go-gitlab/group_variables.go rename to vendor/gitlab.com/gitlab-org/api/client-go/group_variables.go index 69fe44592d..86c7d8bf0b 100644 --- a/vendor/github.com/xanzy/go-gitlab/group_variables.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/group_variables.go @@ -41,6 +41,7 @@ type GroupVariable struct { VariableType VariableTypeValue `json:"variable_type"` Protected bool `json:"protected"` Masked bool `json:"masked"` + Hidden bool `json:"hidden"` Raw bool `json:"raw"` EnvironmentScope string `json:"environment_scope"` Description string `json:"description"` @@ -127,6 +128,7 @@ type CreateGroupVariableOptions struct { Description *string `url:"description,omitempty" json:"description,omitempty"` EnvironmentScope *string `url:"environment_scope,omitempty" json:"environment_scope,omitempty"` Masked *bool `url:"masked,omitempty" json:"masked,omitempty"` + MaskedAndHidden *bool `url:"masked_and_hidden,omitempty" json:"masked_and_hidden,omitempty"` Protected *bool `url:"protected,omitempty" json:"protected,omitempty"` Raw *bool `url:"raw,omitempty" json:"raw,omitempty"` VariableType *VariableTypeValue `url:"variable_type,omitempty" json:"variable_type,omitempty"` diff --git a/vendor/github.com/xanzy/go-gitlab/group_wikis.go b/vendor/gitlab.com/gitlab-org/api/client-go/group_wikis.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/group_wikis.go rename to vendor/gitlab.com/gitlab-org/api/client-go/group_wikis.go diff --git a/vendor/github.com/xanzy/go-gitlab/groups.go b/vendor/gitlab.com/gitlab-org/api/client-go/groups.go similarity index 91% rename from vendor/github.com/xanzy/go-gitlab/groups.go rename to vendor/gitlab.com/gitlab-org/api/client-go/groups.go index 34f0cab662..dfbced977b 100644 --- a/vendor/github.com/xanzy/go-gitlab/groups.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/groups.go @@ -39,47 +39,44 @@ type GroupsService struct { // // GitLab API docs: https://docs.gitlab.com/ee/api/groups.html type Group struct { - ID int `json:"id"` - Name string `json:"name"` - Path string `json:"path"` - Description string `json:"description"` - MembershipLock bool `json:"membership_lock"` - Visibility VisibilityValue `json:"visibility"` - LFSEnabled bool `json:"lfs_enabled"` - DefaultBranchProtectionDefaults struct { - AllowedToPush []*GroupAccessLevel `json:"allowed_to_push"` - AllowForcePush bool `json:"allow_force_push"` - AllowedToMerge []*GroupAccessLevel `json:"allowed_to_merge"` - DeveloperCanInitialPush bool `json:"developer_can_initial_push"` - } `json:"default_branch_protection_defaults"` - AvatarURL string `json:"avatar_url"` - WebURL string `json:"web_url"` - RequestAccessEnabled bool `json:"request_access_enabled"` - RepositoryStorage string `json:"repository_storage"` - FullName string `json:"full_name"` - FullPath string `json:"full_path"` - FileTemplateProjectID int `json:"file_template_project_id"` - ParentID int `json:"parent_id"` - Projects []*Project `json:"projects"` - Statistics *Statistics `json:"statistics"` - CustomAttributes []*CustomAttribute `json:"custom_attributes"` - ShareWithGroupLock bool `json:"share_with_group_lock"` - RequireTwoFactorAuth bool `json:"require_two_factor_authentication"` - TwoFactorGracePeriod int `json:"two_factor_grace_period"` - ProjectCreationLevel ProjectCreationLevelValue `json:"project_creation_level"` - AutoDevopsEnabled bool `json:"auto_devops_enabled"` - SubGroupCreationLevel SubGroupCreationLevelValue `json:"subgroup_creation_level"` - EmailsEnabled bool `json:"emails_enabled"` - MentionsDisabled bool `json:"mentions_disabled"` - RunnersToken string `json:"runners_token"` - SharedProjects []*Project `json:"shared_projects"` - SharedRunnersSetting SharedRunnersSettingValue `json:"shared_runners_setting"` - SharedWithGroups []struct { + ID int `json:"id"` + Name string `json:"name"` + Path string `json:"path"` + Description string `json:"description"` + MembershipLock bool `json:"membership_lock"` + Visibility VisibilityValue `json:"visibility"` + LFSEnabled bool `json:"lfs_enabled"` + DefaultBranch string `json:"default_branch"` + DefaultBranchProtectionDefaults *BranchProtectionDefaults `json:"default_branch_protection_defaults"` + AvatarURL string `json:"avatar_url"` + WebURL string `json:"web_url"` + RequestAccessEnabled bool `json:"request_access_enabled"` + RepositoryStorage string `json:"repository_storage"` + FullName string `json:"full_name"` + FullPath string `json:"full_path"` + FileTemplateProjectID int `json:"file_template_project_id"` + ParentID int `json:"parent_id"` + Projects []*Project `json:"projects"` + Statistics *Statistics `json:"statistics"` + CustomAttributes []*CustomAttribute `json:"custom_attributes"` + ShareWithGroupLock bool `json:"share_with_group_lock"` + RequireTwoFactorAuth bool `json:"require_two_factor_authentication"` + TwoFactorGracePeriod int `json:"two_factor_grace_period"` + ProjectCreationLevel ProjectCreationLevelValue `json:"project_creation_level"` + AutoDevopsEnabled bool `json:"auto_devops_enabled"` + SubGroupCreationLevel SubGroupCreationLevelValue `json:"subgroup_creation_level"` + EmailsEnabled bool `json:"emails_enabled"` + MentionsDisabled bool `json:"mentions_disabled"` + RunnersToken string `json:"runners_token"` + SharedProjects []*Project `json:"shared_projects"` + SharedRunnersSetting SharedRunnersSettingValue `json:"shared_runners_setting"` + SharedWithGroups []struct { GroupID int `json:"group_id"` GroupName string `json:"group_name"` GroupFullPath string `json:"group_full_path"` GroupAccessLevel int `json:"group_access_level"` ExpiresAt *ISOTime `json:"expires_at"` + MemberRoleID int `json:"member_role_id"` } `json:"shared_with_groups"` LDAPCN string `json:"ldap_cn"` LDAPAccess AccessLevelValue `json:"ldap_access"` @@ -91,6 +88,7 @@ type Group struct { MarkedForDeletionOn *ISOTime `json:"marked_for_deletion_on"` CreatedAt *time.Time `json:"created_at"` IPRestrictionRanges string `json:"ip_restriction_ranges"` + AllowedEmailDomainsList string `json:"allowed_email_domains_list"` WikiAccessLevel AccessControlValue `json:"wiki_access_level"` // Deprecated: Use EmailsEnabled instead @@ -100,6 +98,17 @@ type Group struct { DefaultBranchProtection int `json:"default_branch_protection"` } +// BranchProtectionDefaults represents default Git protected branch permissions. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/groups.html#options-for-default_branch_protection_defaults +type BranchProtectionDefaults struct { + AllowedToPush []*GroupAccessLevel `json:"allowed_to_push,omitempty"` + AllowForcePush bool `json:"allow_force_push,omitempty"` + AllowedToMerge []*GroupAccessLevel `json:"allowed_to_merge,omitempty"` + DeveloperCanInitialPush bool `json:"developer_can_initial_push,omitempty"` +} + // GroupAccessLevel represents default branch protection defaults access levels. // // GitLab API docs: @@ -358,6 +367,7 @@ type CreateGroupOptions struct { Name *string `url:"name,omitempty" json:"name,omitempty"` Path *string `url:"path,omitempty" json:"path,omitempty"` Avatar *GroupAvatar `url:"-" json:"-"` + DefaultBranch *string `url:"default_branch,omitempty" json:"default_branch,omitempty"` Description *string `url:"description,omitempty" json:"description,omitempty"` MembershipLock *bool `url:"membership_lock,omitempty" json:"membership_lock,omitempty"` Visibility *VisibilityValue `url:"visibility,omitempty" json:"visibility,omitempty"` @@ -375,7 +385,6 @@ type CreateGroupOptions struct { ParentID *int `url:"parent_id,omitempty" json:"parent_id,omitempty"` SharedRunnersMinutesLimit *int `url:"shared_runners_minutes_limit,omitempty" json:"shared_runners_minutes_limit,omitempty"` ExtraSharedRunnersMinutesLimit *int `url:"extra_shared_runners_minutes_limit,omitempty" json:"extra_shared_runners_minutes_limit,omitempty"` - IPRestrictionRanges *string `url:"ip_restriction_ranges,omitempty" json:"ip_restriction_ranges,omitempty"` WikiAccessLevel *AccessControlValue `url:"wiki_access_level,omitempty" json:"wiki_access_level,omitempty"` // Deprecated: Use EmailsEnabled instead @@ -502,6 +511,7 @@ type UpdateGroupOptions struct { Name *string `url:"name,omitempty" json:"name,omitempty"` Path *string `url:"path,omitempty" json:"path,omitempty"` Avatar *GroupAvatar `url:"-" json:"avatar,omitempty"` + DefaultBranch *string `url:"default_branch,omitempty" json:"default_branch,omitempty"` Description *string `url:"description,omitempty" json:"description,omitempty"` MembershipLock *bool `url:"membership_lock,omitempty" json:"membership_lock,omitempty"` Visibility *VisibilityValue `url:"visibility,omitempty" json:"visibility,omitempty"` @@ -523,6 +533,7 @@ type UpdateGroupOptions struct { SharedRunnersSetting *SharedRunnersSettingValue `url:"shared_runners_setting,omitempty" json:"shared_runners_setting,omitempty"` PreventSharingGroupsOutsideHierarchy *bool `url:"prevent_sharing_groups_outside_hierarchy,omitempty" json:"prevent_sharing_groups_outside_hierarchy,omitempty"` IPRestrictionRanges *string `url:"ip_restriction_ranges,omitempty" json:"ip_restriction_ranges,omitempty"` + AllowedEmailDomainsList *string `url:"allowed_email_domains_list,omitempty" json:"allowed_email_domains_list,omitempty"` WikiAccessLevel *AccessControlValue `url:"wiki_access_level,omitempty" json:"wiki_access_level,omitempty"` // Deprecated: Use EmailsEnabled instead @@ -969,9 +980,10 @@ func (s *GroupsService) DeleteGroupSAMLLink(gid interface{}, samlGroupName strin // GitLab API docs: // https://docs.gitlab.com/ee/api/groups.html#share-groups-with-groups type ShareGroupWithGroupOptions struct { - GroupID *int `url:"group_id,omitempty" json:"group_id,omitempty"` - GroupAccess *AccessLevelValue `url:"group_access,omitempty" json:"group_access,omitempty"` - ExpiresAt *ISOTime `url:"expires_at,omitempty" json:"expires_at,omitempty"` + GroupID *int `url:"group_id,omitempty" json:"group_id,omitempty"` + GroupAccess *AccessLevelValue `url:"group_access,omitempty" json:"group_access,omitempty"` + ExpiresAt *ISOTime `url:"expires_at,omitempty" json:"expires_at,omitempty"` + MemberRoleID *int `url:"member_role_id,omitempty" json:"member_role_id,omitempty"` } // ShareGroupWithGroup shares a group with another group. diff --git a/vendor/github.com/xanzy/go-gitlab/import.go b/vendor/gitlab.com/gitlab-org/api/client-go/import.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/import.go rename to vendor/gitlab.com/gitlab-org/api/client-go/import.go diff --git a/vendor/github.com/xanzy/go-gitlab/instance_clusters.go b/vendor/gitlab.com/gitlab-org/api/client-go/instance_clusters.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/instance_clusters.go rename to vendor/gitlab.com/gitlab-org/api/client-go/instance_clusters.go diff --git a/vendor/github.com/xanzy/go-gitlab/instance_variables.go b/vendor/gitlab.com/gitlab-org/api/client-go/instance_variables.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/instance_variables.go rename to vendor/gitlab.com/gitlab-org/api/client-go/instance_variables.go diff --git a/vendor/github.com/xanzy/go-gitlab/invites.go b/vendor/gitlab.com/gitlab-org/api/client-go/invites.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/invites.go rename to vendor/gitlab.com/gitlab-org/api/client-go/invites.go diff --git a/vendor/github.com/xanzy/go-gitlab/issue_links.go b/vendor/gitlab.com/gitlab-org/api/client-go/issue_links.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/issue_links.go rename to vendor/gitlab.com/gitlab-org/api/client-go/issue_links.go diff --git a/vendor/github.com/xanzy/go-gitlab/issues.go b/vendor/gitlab.com/gitlab-org/api/client-go/issues.go similarity index 85% rename from vendor/github.com/xanzy/go-gitlab/issues.go rename to vendor/gitlab.com/gitlab-org/api/client-go/issues.go index eecccc475e..aaa4e85078 100644 --- a/vendor/github.com/xanzy/go-gitlab/issues.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/issues.go @@ -120,6 +120,7 @@ type Issue struct { Epic *Epic `json:"epic"` Iteration *GroupIteration `json:"iteration"` TaskCompletionStatus *TasksCompletionStatus `json:"task_completion_status"` + ServiceDeskReplyTo string `json:"service_desk_reply_to"` } func (i Issue) String() string { @@ -246,29 +247,29 @@ type ListGroupIssuesOptions struct { NotMilestone *string `url:"not[milestone],omitempty" json:"not[milestone],omitempty"` Scope *string `url:"scope,omitempty" json:"scope,omitempty"` AuthorID *int `url:"author_id,omitempty" json:"author_id,omitempty"` - NotAuthorID *[]int `url:"not[author_id],omitempty" json:"not[author_id],omitempty"` + NotAuthorID *int `url:"not[author_id],omitempty" json:"not[author_id],omitempty"` AuthorUsername *string `url:"author_username,omitempty" json:"author_username,omitempty"` NotAuthorUsername *string `url:"not[author_username],omitempty" json:"not[author_username],omitempty"` - AssigneeID *AssigneeIDValue `url:"assignee_id,omitempty" json:"assignee_id,omitempty"` - NotAssigneeID *[]int `url:"not[assignee_id],omitempty" json:"not[assignee_id],omitempty"` - AssigneeUsername *string `url:"assignee_username,omitempty" json:"assignee_username,omitempty"` - NotAssigneeUsername *string `url:"not[assignee_username],omitempty" json:"not[assignee_username],omitempty"` - MyReactionEmoji *string `url:"my_reaction_emoji,omitempty" json:"my_reaction_emoji,omitempty"` - NotMyReactionEmoji *[]string `url:"not[my_reaction_emoji],omitempty" json:"not[my_reaction_emoji],omitempty"` - OrderBy *string `url:"order_by,omitempty" json:"order_by,omitempty"` - Sort *string `url:"sort,omitempty" json:"sort,omitempty"` - Search *string `url:"search,omitempty" json:"search,omitempty"` - NotSearch *string `url:"not[search],omitempty" json:"not[search],omitempty"` - In *string `url:"in,omitempty" json:"in,omitempty"` - NotIn *string `url:"not[in],omitempty" json:"not[in],omitempty"` - CreatedAfter *time.Time `url:"created_after,omitempty" json:"created_after,omitempty"` - CreatedBefore *time.Time `url:"created_before,omitempty" json:"created_before,omitempty"` - DueDate *string `url:"due_date,omitempty" json:"due_date,omitempty"` - UpdatedAfter *time.Time `url:"updated_after,omitempty" json:"updated_after,omitempty"` - UpdatedBefore *time.Time `url:"updated_before,omitempty" json:"updated_before,omitempty"` - IssueType *string `url:"issue_type,omitempty" json:"issue_type,omitempty"` - IterationID *int `url:"iteration_id,omitempty" json:"iteration_id,omitempty"` + AssigneeID *int `url:"assignee_id,omitempty" json:"assignee_id,omitempty"` + NotAssigneeID *int `url:"not[assignee_id],omitempty" json:"not[assignee_id],omitempty"` + AssigneeUsername *string `url:"assignee_username,omitempty" json:"assignee_username,omitempty"` + NotAssigneeUsername *string `url:"not[assignee_username],omitempty" json:"not[assignee_username],omitempty"` + MyReactionEmoji *string `url:"my_reaction_emoji,omitempty" json:"my_reaction_emoji,omitempty"` + NotMyReactionEmoji *string `url:"not[my_reaction_emoji],omitempty" json:"not[my_reaction_emoji],omitempty"` + OrderBy *string `url:"order_by,omitempty" json:"order_by,omitempty"` + Sort *string `url:"sort,omitempty" json:"sort,omitempty"` + Search *string `url:"search,omitempty" json:"search,omitempty"` + NotSearch *string `url:"not[search],omitempty" json:"not[search],omitempty"` + In *string `url:"in,omitempty" json:"in,omitempty"` + NotIn *string `url:"not[in],omitempty" json:"not[in],omitempty"` + CreatedAfter *time.Time `url:"created_after,omitempty" json:"created_after,omitempty"` + CreatedBefore *time.Time `url:"created_before,omitempty" json:"created_before,omitempty"` + DueDate *string `url:"due_date,omitempty" json:"due_date,omitempty"` + UpdatedAfter *time.Time `url:"updated_after,omitempty" json:"updated_after,omitempty"` + UpdatedBefore *time.Time `url:"updated_before,omitempty" json:"updated_before,omitempty"` + IssueType *string `url:"issue_type,omitempty" json:"issue_type,omitempty"` + IterationID *int `url:"iteration_id,omitempty" json:"iteration_id,omitempty"` } // ListGroupIssues gets a list of group issues. This function accepts @@ -301,37 +302,37 @@ func (s *IssuesService) ListGroupIssues(pid interface{}, opt *ListGroupIssuesOpt // GitLab API docs: https://docs.gitlab.com/ee/api/issues.html#list-project-issues type ListProjectIssuesOptions struct { ListOptions - IIDs *[]int `url:"iids[],omitempty" json:"iids,omitempty"` - State *string `url:"state,omitempty" json:"state,omitempty"` - Labels *LabelOptions `url:"labels,comma,omitempty" json:"labels,omitempty"` - NotLabels *LabelOptions `url:"not[labels],comma,omitempty" json:"not[labels],omitempty"` - WithLabelDetails *bool `url:"with_labels_details,omitempty" json:"with_labels_details,omitempty"` - Milestone *string `url:"milestone,omitempty" json:"milestone,omitempty"` - NotMilestone *string `url:"not[milestone],omitempty" json:"not[milestone],omitempty"` - Scope *string `url:"scope,omitempty" json:"scope,omitempty"` - AuthorID *int `url:"author_id,omitempty" json:"author_id,omitempty"` - AuthorUsername *string `url:"author_username,omitempty" json:"author_username,omitempty"` - NotAuthorUsername *string `url:"not[author_username],omitempty" json:"not[author_username],omitempty"` - NotAuthorID *[]int `url:"not[author_id],omitempty" json:"not[author_id],omitempty"` - AssigneeID *AssigneeIDValue `url:"assignee_id,omitempty" json:"assignee_id,omitempty"` - NotAssigneeID *[]int `url:"not[assignee_id],omitempty" json:"not[assignee_id],omitempty"` - AssigneeUsername *string `url:"assignee_username,omitempty" json:"assignee_username,omitempty"` - NotAssigneeUsername *string `url:"not[assignee_username],omitempty" json:"not[assignee_username],omitempty"` - MyReactionEmoji *string `url:"my_reaction_emoji,omitempty" json:"my_reaction_emoji,omitempty"` - NotMyReactionEmoji *[]string `url:"not[my_reaction_emoji],omitempty" json:"not[my_reaction_emoji],omitempty"` - OrderBy *string `url:"order_by,omitempty" json:"order_by,omitempty"` - Sort *string `url:"sort,omitempty" json:"sort,omitempty"` - Search *string `url:"search,omitempty" json:"search,omitempty"` - In *string `url:"in,omitempty" json:"in,omitempty"` - NotIn *string `url:"not[in],omitempty" json:"not[in],omitempty"` - CreatedAfter *time.Time `url:"created_after,omitempty" json:"created_after,omitempty"` - CreatedBefore *time.Time `url:"created_before,omitempty" json:"created_before,omitempty"` - DueDate *string `url:"due_date,omitempty" json:"due_date,omitempty"` - UpdatedAfter *time.Time `url:"updated_after,omitempty" json:"updated_after,omitempty"` - UpdatedBefore *time.Time `url:"updated_before,omitempty" json:"updated_before,omitempty"` - Confidential *bool `url:"confidential,omitempty" json:"confidential,omitempty"` - IssueType *string `url:"issue_type,omitempty" json:"issue_type,omitempty"` - IterationID *int `url:"iteration_id,omitempty" json:"iteration_id,omitempty"` + IIDs *[]int `url:"iids[],omitempty" json:"iids,omitempty"` + State *string `url:"state,omitempty" json:"state,omitempty"` + Labels *LabelOptions `url:"labels,comma,omitempty" json:"labels,omitempty"` + NotLabels *LabelOptions `url:"not[labels],comma,omitempty" json:"not[labels],omitempty"` + WithLabelDetails *bool `url:"with_labels_details,omitempty" json:"with_labels_details,omitempty"` + Milestone *string `url:"milestone,omitempty" json:"milestone,omitempty"` + NotMilestone *string `url:"not[milestone],omitempty" json:"not[milestone],omitempty"` + Scope *string `url:"scope,omitempty" json:"scope,omitempty"` + AuthorID *int `url:"author_id,omitempty" json:"author_id,omitempty"` + AuthorUsername *string `url:"author_username,omitempty" json:"author_username,omitempty"` + NotAuthorUsername *string `url:"not[author_username],omitempty" json:"not[author_username],omitempty"` + NotAuthorID *int `url:"not[author_id],omitempty" json:"not[author_id],omitempty"` + AssigneeID *int `url:"assignee_id,omitempty" json:"assignee_id,omitempty"` + NotAssigneeID *int `url:"not[assignee_id],omitempty" json:"not[assignee_id],omitempty"` + AssigneeUsername *string `url:"assignee_username,omitempty" json:"assignee_username,omitempty"` + NotAssigneeUsername *string `url:"not[assignee_username],omitempty" json:"not[assignee_username],omitempty"` + MyReactionEmoji *string `url:"my_reaction_emoji,omitempty" json:"my_reaction_emoji,omitempty"` + NotMyReactionEmoji *string `url:"not[my_reaction_emoji],omitempty" json:"not[my_reaction_emoji],omitempty"` + OrderBy *string `url:"order_by,omitempty" json:"order_by,omitempty"` + Sort *string `url:"sort,omitempty" json:"sort,omitempty"` + Search *string `url:"search,omitempty" json:"search,omitempty"` + In *string `url:"in,omitempty" json:"in,omitempty"` + NotIn *string `url:"not[in],omitempty" json:"not[in],omitempty"` + CreatedAfter *time.Time `url:"created_after,omitempty" json:"created_after,omitempty"` + CreatedBefore *time.Time `url:"created_before,omitempty" json:"created_before,omitempty"` + DueDate *string `url:"due_date,omitempty" json:"due_date,omitempty"` + UpdatedAfter *time.Time `url:"updated_after,omitempty" json:"updated_after,omitempty"` + UpdatedBefore *time.Time `url:"updated_before,omitempty" json:"updated_before,omitempty"` + Confidential *bool `url:"confidential,omitempty" json:"confidential,omitempty"` + IssueType *string `url:"issue_type,omitempty" json:"issue_type,omitempty"` + IterationID *int `url:"iteration_id,omitempty" json:"iteration_id,omitempty"` } // ListProjectIssues gets a list of project issues. This function accepts diff --git a/vendor/github.com/xanzy/go-gitlab/issues_statistics.go b/vendor/gitlab.com/gitlab-org/api/client-go/issues_statistics.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/issues_statistics.go rename to vendor/gitlab.com/gitlab-org/api/client-go/issues_statistics.go diff --git a/vendor/github.com/xanzy/go-gitlab/job_token_scope.go b/vendor/gitlab.com/gitlab-org/api/client-go/job_token_scope.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/job_token_scope.go rename to vendor/gitlab.com/gitlab-org/api/client-go/job_token_scope.go diff --git a/vendor/github.com/xanzy/go-gitlab/jobs.go b/vendor/gitlab.com/gitlab-org/api/client-go/jobs.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/jobs.go rename to vendor/gitlab.com/gitlab-org/api/client-go/jobs.go diff --git a/vendor/github.com/xanzy/go-gitlab/keys.go b/vendor/gitlab.com/gitlab-org/api/client-go/keys.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/keys.go rename to vendor/gitlab.com/gitlab-org/api/client-go/keys.go diff --git a/vendor/github.com/xanzy/go-gitlab/labels.go b/vendor/gitlab.com/gitlab-org/api/client-go/labels.go similarity index 90% rename from vendor/github.com/xanzy/go-gitlab/labels.go rename to vendor/gitlab.com/gitlab-org/api/client-go/labels.go index d36e85b086..bc73669eeb 100644 --- a/vendor/github.com/xanzy/go-gitlab/labels.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/labels.go @@ -108,12 +108,12 @@ func (s *LabelsService) ListLabels(pid interface{}, opt *ListLabelsOptions, opti // GetLabel get a single label for a given project. // // GitLab API docs: https://docs.gitlab.com/ee/api/labels.html#get-a-single-project-label -func (s *LabelsService) GetLabel(pid interface{}, labelID interface{}, options ...RequestOptionFunc) (*Label, *Response, error) { +func (s *LabelsService) GetLabel(pid interface{}, lid interface{}, options ...RequestOptionFunc) (*Label, *Response, error) { project, err := parseID(pid) if err != nil { return nil, nil, err } - label, err := parseID(labelID) + label, err := parseID(lid) if err != nil { return nil, nil, err } @@ -216,13 +216,21 @@ type UpdateLabelOptions struct { // one parameter is required, to update the label. // // GitLab API docs: https://docs.gitlab.com/ee/api/labels.html#edit-an-existing-label -func (s *LabelsService) UpdateLabel(pid interface{}, opt *UpdateLabelOptions, options ...RequestOptionFunc) (*Label, *Response, error) { +func (s *LabelsService) UpdateLabel(pid interface{}, lid interface{}, opt *UpdateLabelOptions, options ...RequestOptionFunc) (*Label, *Response, error) { project, err := parseID(pid) if err != nil { return nil, nil, err } u := fmt.Sprintf("projects/%s/labels", PathEscape(project)) + if lid != nil { + label, err := parseID(lid) + if err != nil { + return nil, nil, err + } + u = fmt.Sprintf("projects/%s/labels/%s", PathEscape(project), PathEscape(label)) + } + req, err := s.client.NewRequest(http.MethodPut, u, opt, options) if err != nil { return nil, nil, err @@ -243,12 +251,12 @@ func (s *LabelsService) UpdateLabel(pid interface{}, opt *UpdateLabelOptions, op // // GitLab API docs: // https://docs.gitlab.com/ee/api/labels.html#subscribe-to-a-label -func (s *LabelsService) SubscribeToLabel(pid interface{}, labelID interface{}, options ...RequestOptionFunc) (*Label, *Response, error) { +func (s *LabelsService) SubscribeToLabel(pid interface{}, lid interface{}, options ...RequestOptionFunc) (*Label, *Response, error) { project, err := parseID(pid) if err != nil { return nil, nil, err } - label, err := parseID(labelID) + label, err := parseID(lid) if err != nil { return nil, nil, err } @@ -274,12 +282,12 @@ func (s *LabelsService) SubscribeToLabel(pid interface{}, labelID interface{}, o // // GitLab API docs: // https://docs.gitlab.com/ee/api/labels.html#unsubscribe-from-a-label -func (s *LabelsService) UnsubscribeFromLabel(pid interface{}, labelID interface{}, options ...RequestOptionFunc) (*Response, error) { +func (s *LabelsService) UnsubscribeFromLabel(pid interface{}, lid interface{}, options ...RequestOptionFunc) (*Response, error) { project, err := parseID(pid) if err != nil { return nil, err } - label, err := parseID(labelID) + label, err := parseID(lid) if err != nil { return nil, err } @@ -297,12 +305,12 @@ func (s *LabelsService) UnsubscribeFromLabel(pid interface{}, labelID interface{ // // GitLab API docs: // https://docs.gitlab.com/ee/api/labels.html#promote-a-project-label-to-a-group-label -func (s *LabelsService) PromoteLabel(pid interface{}, labelID interface{}, options ...RequestOptionFunc) (*Response, error) { +func (s *LabelsService) PromoteLabel(pid interface{}, lid interface{}, options ...RequestOptionFunc) (*Response, error) { project, err := parseID(pid) if err != nil { return nil, err } - label, err := parseID(labelID) + label, err := parseID(lid) if err != nil { return nil, err } diff --git a/vendor/github.com/xanzy/go-gitlab/license.go b/vendor/gitlab.com/gitlab-org/api/client-go/license.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/license.go rename to vendor/gitlab.com/gitlab-org/api/client-go/license.go diff --git a/vendor/github.com/xanzy/go-gitlab/license_templates.go b/vendor/gitlab.com/gitlab-org/api/client-go/license_templates.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/license_templates.go rename to vendor/gitlab.com/gitlab-org/api/client-go/license_templates.go diff --git a/vendor/github.com/xanzy/go-gitlab/markdown.go b/vendor/gitlab.com/gitlab-org/api/client-go/markdown.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/markdown.go rename to vendor/gitlab.com/gitlab-org/api/client-go/markdown.go diff --git a/vendor/github.com/xanzy/go-gitlab/member_roles.go b/vendor/gitlab.com/gitlab-org/api/client-go/member_roles.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/member_roles.go rename to vendor/gitlab.com/gitlab-org/api/client-go/member_roles.go diff --git a/vendor/github.com/xanzy/go-gitlab/merge_request_approvals.go b/vendor/gitlab.com/gitlab-org/api/client-go/merge_request_approvals.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/merge_request_approvals.go rename to vendor/gitlab.com/gitlab-org/api/client-go/merge_request_approvals.go diff --git a/vendor/github.com/xanzy/go-gitlab/merge_requests.go b/vendor/gitlab.com/gitlab-org/api/client-go/merge_requests.go similarity index 84% rename from vendor/github.com/xanzy/go-gitlab/merge_requests.go rename to vendor/gitlab.com/gitlab-org/api/client-go/merge_requests.go index a9e8d2e5c6..506e3303c6 100644 --- a/vendor/github.com/xanzy/go-gitlab/merge_requests.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/merge_requests.go @@ -17,6 +17,7 @@ package gitlab import ( + "bytes" "encoding/json" "fmt" "net/http" @@ -533,6 +534,42 @@ func (s *MergeRequestsService) ListMergeRequestDiffs(pid interface{}, mergeReque return m, resp, nil } +// ShowMergeRequestRawDiffsOptions represents the available ShowMergeRequestRawDiffs() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/merge_requests.html#show-merge-request-raw-diffs +type ShowMergeRequestRawDiffsOptions struct{} + +// ShowMergeRequestRawDiffs Show raw diffs of the files changed in a merge request +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/merge_requests.html#show-merge-request-raw-diffs +func (s *MergeRequestsService) ShowMergeRequestRawDiffs(pid interface{}, mergeRequest int, opt *ShowMergeRequestRawDiffsOptions, options ...RequestOptionFunc) ([]byte, *Response, error) { + project, err := parseID(pid) + if err != nil { + return []byte{}, nil, err + } + u := fmt.Sprintf( + "projects/%s/merge_requests/%d/raw_diffs", + PathEscape(project), + mergeRequest, + ) + + req, err := s.client.NewRequest(http.MethodGet, u, opt, options) + if err != nil { + return []byte{}, nil, err + } + + var rd bytes.Buffer + resp, err := s.client.Do(req, &rd) + if err != nil { + return []byte{}, resp, err + } + + return rd.Bytes(), resp, nil +} + // GetMergeRequestParticipants gets a list of merge request participants. // // GitLab API docs: @@ -1078,3 +1115,160 @@ func (s *MergeRequestsService) ResetSpentTime(pid interface{}, mergeRequest int, func (s *MergeRequestsService) GetTimeSpent(pid interface{}, mergeRequest int, options ...RequestOptionFunc) (*TimeStats, *Response, error) { return s.timeStats.getTimeSpent(pid, "merge_requests", mergeRequest, options...) } + +// MergeRequestDependency represents a GitLab merge request dependency. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/merge_requests.html#create-a-merge-request-dependency +type MergeRequestDependency struct { + ID int `json:"id"` + BlockingMergeRequest BlockingMergeRequest `json:"blocking_merge_request"` + ProjectID int `json:"project_id"` +} + +// BlockingMergeRequest represents a GitLab merge request dependency. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/merge_requests.html#create-a-merge-request-dependency +type BlockingMergeRequest struct { + ID int `json:"id"` + Iid int `json:"iid"` + TargetBranch string `json:"target_branch"` + SourceBranch string `json:"source_branch"` + ProjectID int `json:"project_id"` + Title string `json:"title"` + State string `json:"state"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + Upvotes int `json:"upvotes"` + Downvotes int `json:"downvotes"` + Author *BasicUser `json:"author"` + Assignee *BasicUser `json:"assignee"` + Assignees []*BasicUser `json:"assignees"` + Reviewers []*BasicUser `json:"reviewers"` + SourceProjectID int `json:"source_project_id"` + TargetProjectID int `json:"target_project_id"` + Labels *LabelOptions `json:"labels"` + Description string `json:"description"` + Draft bool `json:"draft"` + WorkInProgress bool `json:"work_in_progress"` + Milestone *string `json:"milestone"` + MergeWhenPipelineSucceeds bool `json:"merge_when_pipeline_succeeds"` + DetailedMergeStatus string `json:"detailed_merge_status"` + MergedBy *BasicUser `json:"merged_by"` + MergedAt *time.Time `json:"merged_at"` + ClosedBy *BasicUser `json:"closed_by"` + ClosedAt *time.Time `json:"closed_at"` + Sha string `json:"sha"` + MergeCommitSha string `json:"merge_commit_sha"` + SquashCommitSha string `json:"squash_commit_sha"` + UserNotesCount int `json:"user_notes_count"` + ShouldRemoveSourceBranch *bool `json:"should_remove_source_branch"` + ForceRemoveSourceBranch bool `json:"force_remove_source_branch"` + WebURL string `json:"web_url"` + References *IssueReferences `json:"references"` + DiscussionLocked *bool `json:"discussion_locked"` + TimeStats *TimeStats `json:"time_stats"` + Squash bool `json:"squash"` + ApprovalsBeforeMerge *int `json:"approvals_before_merge"` + Reference string `json:"reference"` + TaskCompletionStatus *TasksCompletionStatus `json:"task_completion_status"` + HasConflicts bool `json:"has_conflicts"` + BlockingDiscussionsResolved bool `json:"blocking_discussions_resolved"` + MergeStatus string `json:"merge_status"` + MergeUser *BasicUser `json:"merge_user"` + MergeAfter time.Time `json:"merge_after"` + Imported bool `json:"imported"` + ImportedFrom string `json:"imported_from"` + PreparedAt *time.Time `json:"prepared_at"` + SquashOnMerge bool `json:"squash_on_merge"` +} + +func (m MergeRequestDependency) String() string { + return Stringify(m) +} + +// CreateMergeRequestDependencyOptions represents the available CreateMergeRequestDependency() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/merge_requests.html#create-a-merge-request-dependency +type CreateMergeRequestDependencyOptions struct { + BlockingMergeRequestID *int `url:"blocking_merge_request_id,omitempty" json:"blocking_merge_request_id,omitempty"` +} + +// CreateMergeRequestDependency creates a new merge request dependency for a given +// merge request. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/merge_requests.html#create-a-merge-request-dependency +func (s *MergeRequestsService) CreateMergeRequestDependency(pid interface{}, mergeRequest int, opts CreateMergeRequestDependencyOptions, options ...RequestOptionFunc) ([]MergeRequestDependency, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/merge_requests/%d/blocks", PathEscape(project), mergeRequest) + + req, err := s.client.NewRequest(http.MethodPost, u, opts, options) + if err != nil { + return nil, nil, err + } + + var mrd []MergeRequestDependency + resp, err := s.client.Do(req, &mrd) + if err != nil { + return nil, resp, err + } + + return mrd, resp, err +} + +// DeleteMergeRequestDependency deletes a merge request dependency for a given +// merge request. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/merge_requests.html#delete-a-merge-request-dependency +func (s *MergeRequestsService) DeleteMergeRequestDependency(pid interface{}, mergeRequest int, blockingMergeRequest int, options ...RequestOptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/merge_requests/%d/blocks/%d", PathEscape(project), mergeRequest, blockingMergeRequest) + + req, err := s.client.NewRequest(http.MethodDelete, u, nil, options) + if err != nil { + return nil, err + } + + resp, err := s.client.Do(req, nil) + if err != nil { + return resp, err + } + + return resp, err +} + +// GetMergeRequestDependencies gets a list of merge request dependencies. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/merge_requests.html#get-merge-request-dependencies +func (s *MergeRequestsService) GetMergeRequestDependencies(pid interface{}, mergeRequest int, options ...RequestOptionFunc) ([]MergeRequestDependency, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/merge_requests/%d/blocks", PathEscape(project), mergeRequest) + + req, err := s.client.NewRequest(http.MethodGet, u, nil, options) + if err != nil { + return nil, nil, err + } + + var mrd []MergeRequestDependency + resp, err := s.client.Do(req, &mrd) + if err != nil { + return nil, resp, err + } + + return mrd, resp, err +} diff --git a/vendor/github.com/xanzy/go-gitlab/merge_trains.go b/vendor/gitlab.com/gitlab-org/api/client-go/merge_trains.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/merge_trains.go rename to vendor/gitlab.com/gitlab-org/api/client-go/merge_trains.go diff --git a/vendor/github.com/xanzy/go-gitlab/metadata.go b/vendor/gitlab.com/gitlab-org/api/client-go/metadata.go similarity index 89% rename from vendor/github.com/xanzy/go-gitlab/metadata.go rename to vendor/gitlab.com/gitlab-org/api/client-go/metadata.go index db23a81e46..3550c49442 100644 --- a/vendor/github.com/xanzy/go-gitlab/metadata.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/metadata.go @@ -33,9 +33,10 @@ type Metadata struct { Version string `json:"version"` Revision string `json:"revision"` KAS struct { - Enabled bool `json:"enabled"` - ExternalURL string `json:"externalUrl"` - Version string `json:"version"` + Enabled bool `json:"enabled"` + ExternalURL string `json:"externalUrl"` + ExternalK8SProxyURL string `json:"externalK8sProxyUrl"` + Version string `json:"version"` } `json:"kas"` Enterprise bool `json:"enterprise"` } diff --git a/vendor/github.com/xanzy/go-gitlab/milestones.go b/vendor/gitlab.com/gitlab-org/api/client-go/milestones.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/milestones.go rename to vendor/gitlab.com/gitlab-org/api/client-go/milestones.go diff --git a/vendor/github.com/xanzy/go-gitlab/namespaces.go b/vendor/gitlab.com/gitlab-org/api/client-go/namespaces.go similarity index 95% rename from vendor/github.com/xanzy/go-gitlab/namespaces.go rename to vendor/gitlab.com/gitlab-org/api/client-go/namespaces.go index da82a0c588..eaf53867fd 100644 --- a/vendor/github.com/xanzy/go-gitlab/namespaces.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/namespaces.go @@ -59,8 +59,9 @@ func (n Namespace) String() string { // GitLab API docs: https://docs.gitlab.com/ee/api/namespaces.html#list-namespaces type ListNamespacesOptions struct { ListOptions - Search *string `url:"search,omitempty" json:"search,omitempty"` - OwnedOnly *bool `url:"owned_only,omitempty" json:"owned_only,omitempty"` + Search *string `url:"search,omitempty" json:"search,omitempty"` + OwnedOnly *bool `url:"owned_only,omitempty" json:"owned_only,omitempty"` + TopLevelOnly *bool `url:"top_level_only,omitempty" json:"top_level_only,omitempty"` } // ListNamespaces gets a list of projects accessible by the authenticated user. diff --git a/vendor/github.com/xanzy/go-gitlab/notes.go b/vendor/gitlab.com/gitlab-org/api/client-go/notes.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/notes.go rename to vendor/gitlab.com/gitlab-org/api/client-go/notes.go diff --git a/vendor/github.com/xanzy/go-gitlab/notifications.go b/vendor/gitlab.com/gitlab-org/api/client-go/notifications.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/notifications.go rename to vendor/gitlab.com/gitlab-org/api/client-go/notifications.go diff --git a/vendor/github.com/xanzy/go-gitlab/packages.go b/vendor/gitlab.com/gitlab-org/api/client-go/packages.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/packages.go rename to vendor/gitlab.com/gitlab-org/api/client-go/packages.go diff --git a/vendor/gitlab.com/gitlab-org/api/client-go/pages.go b/vendor/gitlab.com/gitlab-org/api/client-go/pages.go new file mode 100644 index 0000000000..7b0f503edc --- /dev/null +++ b/vendor/gitlab.com/gitlab-org/api/client-go/pages.go @@ -0,0 +1,127 @@ +// +// Copyright 2021, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "fmt" + "net/http" + "time" +) + +type PagesService struct { + client *Client +} + +// Pages represents the Pages of a project. +// +// GitLab API docs: https://docs.gitlab.com/ee/api/pages.html +type Pages struct { + URL string `json:"url"` + IsUniqueDomainEnabled bool `json:"is_unique_domain_enabled"` + ForceHTTPS bool `json:"force_https"` + Deployments []*PagesDeployment `json:"deployments"` +} + +// PagesDeployment represents a Pages deployment. +// +// GitLab API docs: https://docs.gitlab.com/ee/api/pages.html +type PagesDeployment struct { + CreatedAt time.Time `json:"created_at"` + URL string `json:"url"` + PathPrefix string `json:"path_prefix"` + RootDirectory string `json:"root_directory"` +} + +// UnpublishPages unpublished pages. The user must have admin privileges. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/pages.html#unpublish-pages +func (s *PagesService) UnpublishPages(gid interface{}, options ...RequestOptionFunc) (*Response, error) { + page, err := parseID(gid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/pages", PathEscape(page)) + + req, err := s.client.NewRequest(http.MethodDelete, u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + +// GetPages lists Pages settings for a project. The user must have at least +// maintainer privileges. +// +// GitLab API Docs: +// https://docs.gitlab.com/ee/api/pages.html#get-pages-settings-for-a-project +func (s *PagesService) GetPages(gid interface{}, options ...RequestOptionFunc) (*Pages, *Response, error) { + project, err := parseID(gid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/pages", PathEscape(project)) + + req, err := s.client.NewRequest(http.MethodGet, u, nil, options) + if err != nil { + return nil, nil, err + } + + p := new(Pages) + resp, err := s.client.Do(req, p) + if err != nil { + return nil, resp, err + } + + return p, resp, nil +} + +// UpdatePages represents the available UpdatePages() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/pages.html#update-pages-settings-for-a-project +type UpdatePagesOptions struct { + PagesUniqueDomainEnabled *bool `url:"pages_unique_domain_enabled,omitempty" json:"pages_unique_domain_enabled,omitempty"` + PagesHTTPSOnly *bool `url:"pages_https_only,omitempty" json:"pages_https_only,omitempty"` +} + +// UpdatePages updates Pages settings for a project. The user must have +// administrator privileges. +// +// GitLab API Docs: +// https://docs.gitlab.com/ee/api/pages.html#update-pages-settings-for-a-project +func (s *PagesService) UpdatePages(pid interface{}, opt UpdatePagesOptions, options ...RequestOptionFunc) (*Pages, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/pages", PathEscape(project)) + + req, err := s.client.NewRequest(http.MethodPatch, u, opt, options) + if err != nil { + return nil, nil, err + } + + p := new(Pages) + resp, err := s.client.Do(req, p) + if err != nil { + return nil, resp, err + } + + return p, resp, nil +} diff --git a/vendor/github.com/xanzy/go-gitlab/pages_domains.go b/vendor/gitlab.com/gitlab-org/api/client-go/pages_domains.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/pages_domains.go rename to vendor/gitlab.com/gitlab-org/api/client-go/pages_domains.go diff --git a/vendor/github.com/xanzy/go-gitlab/personal_access_tokens.go b/vendor/gitlab.com/gitlab-org/api/client-go/personal_access_tokens.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/personal_access_tokens.go rename to vendor/gitlab.com/gitlab-org/api/client-go/personal_access_tokens.go diff --git a/vendor/github.com/xanzy/go-gitlab/pipeline_schedules.go b/vendor/gitlab.com/gitlab-org/api/client-go/pipeline_schedules.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/pipeline_schedules.go rename to vendor/gitlab.com/gitlab-org/api/client-go/pipeline_schedules.go diff --git a/vendor/github.com/xanzy/go-gitlab/pipeline_triggers.go b/vendor/gitlab.com/gitlab-org/api/client-go/pipeline_triggers.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/pipeline_triggers.go rename to vendor/gitlab.com/gitlab-org/api/client-go/pipeline_triggers.go diff --git a/vendor/github.com/xanzy/go-gitlab/pipelines.go b/vendor/gitlab.com/gitlab-org/api/client-go/pipelines.go similarity index 85% rename from vendor/github.com/xanzy/go-gitlab/pipelines.go rename to vendor/gitlab.com/gitlab-org/api/client-go/pipelines.go index 3f2448447e..dd02acc9f3 100644 --- a/vendor/github.com/xanzy/go-gitlab/pipelines.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/pipelines.go @@ -142,6 +142,7 @@ type PipelineInfo struct { Source string `json:"source"` Ref string `json:"ref"` SHA string `json:"sha"` + Name string `json:"name"` WebURL string `json:"web_url"` UpdatedAt *time.Time `json:"updated_at"` CreatedAt *time.Time `json:"created_at"` @@ -151,9 +152,11 @@ func (p PipelineInfo) String() string { return Stringify(p) } -// ListProjectPipelinesOptions represents the available ListProjectPipelines() options. +// ListProjectPipelinesOptions represents the available ListProjectPipelines() +// options. // -// GitLab API docs: https://docs.gitlab.com/ee/api/pipelines.html#list-project-pipelines +// GitLab API docs: +// https://docs.gitlab.com/ee/api/pipelines.html#list-project-pipelines type ListProjectPipelinesOptions struct { ListOptions Scope *string `url:"scope,omitempty" json:"scope,omitempty"` @@ -172,7 +175,8 @@ type ListProjectPipelinesOptions struct { // ListProjectPipelines gets a list of project piplines. // -// GitLab API docs: https://docs.gitlab.com/ee/api/pipelines.html#list-project-pipelines +// GitLab API docs: +// https://docs.gitlab.com/ee/api/pipelines.html#list-project-pipelines func (s *PipelinesService) ListProjectPipelines(pid interface{}, opt *ListProjectPipelinesOptions, options ...RequestOptionFunc) ([]*PipelineInfo, *Response, error) { project, err := parseID(pid) if err != nil { @@ -196,7 +200,8 @@ func (s *PipelinesService) ListProjectPipelines(pid interface{}, opt *ListProjec // GetPipeline gets a single project pipeline. // -// GitLab API docs: https://docs.gitlab.com/ee/api/pipelines.html#get-a-single-pipeline +// GitLab API docs: +// https://docs.gitlab.com/ee/api/pipelines.html#get-a-single-pipeline func (s *PipelinesService) GetPipeline(pid interface{}, pipeline int, options ...RequestOptionFunc) (*Pipeline, *Response, error) { project, err := parseID(pid) if err != nil { @@ -220,7 +225,8 @@ func (s *PipelinesService) GetPipeline(pid interface{}, pipeline int, options .. // GetPipelineVariables gets the variables of a single project pipeline. // -// GitLab API docs: https://docs.gitlab.com/ee/api/pipelines.html#get-variables-of-a-pipeline +// GitLab API docs: +// https://docs.gitlab.com/ee/api/pipelines.html#get-variables-of-a-pipeline func (s *PipelinesService) GetPipelineVariables(pid interface{}, pipeline int, options ...RequestOptionFunc) ([]*PipelineVariable, *Response, error) { project, err := parseID(pid) if err != nil { @@ -244,7 +250,8 @@ func (s *PipelinesService) GetPipelineVariables(pid interface{}, pipeline int, o // GetPipelineTestReport gets the test report of a single project pipeline. // -// GitLab API docs: https://docs.gitlab.com/ee/api/pipelines.html#get-a-pipelines-test-report +// GitLab API docs: +// https://docs.gitlab.com/ee/api/pipelines.html#get-a-pipelines-test-report func (s *PipelinesService) GetPipelineTestReport(pid interface{}, pipeline int, options ...RequestOptionFunc) (*PipelineTestReport, *Response, error) { project, err := parseID(pid) if err != nil { @@ -268,14 +275,16 @@ func (s *PipelinesService) GetPipelineTestReport(pid interface{}, pipeline int, // GetLatestPipelineOptions represents the available GetLatestPipeline() options. // -// GitLab API docs: https://docs.gitlab.com/ee/api/pipelines.html#get-the-latest-pipeline +// GitLab API docs: +// https://docs.gitlab.com/ee/api/pipelines.html#get-the-latest-pipeline type GetLatestPipelineOptions struct { Ref *string `url:"ref,omitempty" json:"ref,omitempty"` } // GetLatestPipeline gets the latest pipeline for a specific ref in a project. // -// GitLab API docs: https://docs.gitlab.com/ee/api/pipelines.html#get-the-latest-pipeline +// GitLab API docs: +// https://docs.gitlab.com/ee/api/pipelines.html#get-the-latest-pipeline func (s *PipelinesService) GetLatestPipeline(pid interface{}, opt *GetLatestPipelineOptions, options ...RequestOptionFunc) (*Pipeline, *Response, error) { project, err := parseID(pid) if err != nil { @@ -299,7 +308,8 @@ func (s *PipelinesService) GetLatestPipeline(pid interface{}, opt *GetLatestPipe // CreatePipelineOptions represents the available CreatePipeline() options. // -// GitLab API docs: https://docs.gitlab.com/ee/api/pipelines.html#create-a-new-pipeline +// GitLab API docs: +// https://docs.gitlab.com/ee/api/pipelines.html#create-a-new-pipeline type CreatePipelineOptions struct { Ref *string `url:"ref" json:"ref"` Variables *[]*PipelineVariableOptions `url:"variables,omitempty" json:"variables,omitempty"` @@ -316,7 +326,8 @@ type PipelineVariableOptions struct { // CreatePipeline creates a new project pipeline. // -// GitLab API docs: https://docs.gitlab.com/ee/api/pipelines.html#create-a-new-pipeline +// GitLab API docs: +// https://docs.gitlab.com/ee/api/pipelines.html#create-a-new-pipeline func (s *PipelinesService) CreatePipeline(pid interface{}, opt *CreatePipelineOptions, options ...RequestOptionFunc) (*Pipeline, *Response, error) { project, err := parseID(pid) if err != nil { @@ -338,7 +349,7 @@ func (s *PipelinesService) CreatePipeline(pid interface{}, opt *CreatePipelineOp return p, resp, nil } -// RetryPipelineBuild retries failed builds in a pipeline +// RetryPipelineBuild retries failed builds in a pipeline. // // GitLab API docs: // https://docs.gitlab.com/ee/api/pipelines.html#retry-jobs-in-a-pipeline @@ -363,7 +374,7 @@ func (s *PipelinesService) RetryPipelineBuild(pid interface{}, pipeline int, opt return p, resp, nil } -// CancelPipelineBuild cancels a pipeline builds +// CancelPipelineBuild cancels a pipeline builds. // // GitLab API docs: // https://docs.gitlab.com/ee/api/pipelines.html#cancel-a-pipelines-jobs @@ -406,3 +417,38 @@ func (s *PipelinesService) DeletePipeline(pid interface{}, pipeline int, options return s.client.Do(req, nil) } + +// UpdatePipelineMetadataOptions represents the available UpdatePipelineMetadata() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/pipelines.html#update-pipeline-metadata +type UpdatePipelineMetadataOptions struct { + Name *string `url:"name,omitempty" json:"name,omitempty"` +} + +// UpdatePipelineMetadata You can update the metadata of a pipeline. The metadata +// contains the name of the pipeline. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/pipelines.html#update-pipeline-metadata +func (s *PipelinesService) UpdatePipelineMetadata(pid interface{}, pipeline int, opt *UpdatePipelineMetadataOptions, options ...RequestOptionFunc) (*Pipeline, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/pipelines/%d/metadata", PathEscape(project), pipeline) + + req, err := s.client.NewRequest(http.MethodPut, u, opt, options) + if err != nil { + return nil, nil, err + } + + p := new(Pipeline) + resp, err := s.client.Do(req, p) + if err != nil { + return nil, resp, err + } + + return p, resp, nil +} diff --git a/vendor/github.com/xanzy/go-gitlab/plan_limits.go b/vendor/gitlab.com/gitlab-org/api/client-go/plan_limits.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/plan_limits.go rename to vendor/gitlab.com/gitlab-org/api/client-go/plan_limits.go diff --git a/vendor/github.com/xanzy/go-gitlab/project_access_tokens.go b/vendor/gitlab.com/gitlab-org/api/client-go/project_access_tokens.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/project_access_tokens.go rename to vendor/gitlab.com/gitlab-org/api/client-go/project_access_tokens.go diff --git a/vendor/github.com/xanzy/go-gitlab/project_badges.go b/vendor/gitlab.com/gitlab-org/api/client-go/project_badges.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/project_badges.go rename to vendor/gitlab.com/gitlab-org/api/client-go/project_badges.go diff --git a/vendor/github.com/xanzy/go-gitlab/project_clusters.go b/vendor/gitlab.com/gitlab-org/api/client-go/project_clusters.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/project_clusters.go rename to vendor/gitlab.com/gitlab-org/api/client-go/project_clusters.go diff --git a/vendor/github.com/xanzy/go-gitlab/project_feature_flags.go b/vendor/gitlab.com/gitlab-org/api/client-go/project_feature_flags.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/project_feature_flags.go rename to vendor/gitlab.com/gitlab-org/api/client-go/project_feature_flags.go diff --git a/vendor/github.com/xanzy/go-gitlab/project_import_export.go b/vendor/gitlab.com/gitlab-org/api/client-go/project_import_export.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/project_import_export.go rename to vendor/gitlab.com/gitlab-org/api/client-go/project_import_export.go diff --git a/vendor/github.com/xanzy/go-gitlab/project_iterations.go b/vendor/gitlab.com/gitlab-org/api/client-go/project_iterations.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/project_iterations.go rename to vendor/gitlab.com/gitlab-org/api/client-go/project_iterations.go diff --git a/vendor/github.com/xanzy/go-gitlab/project_managed_licenses.go b/vendor/gitlab.com/gitlab-org/api/client-go/project_managed_licenses.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/project_managed_licenses.go rename to vendor/gitlab.com/gitlab-org/api/client-go/project_managed_licenses.go diff --git a/vendor/gitlab.com/gitlab-org/api/client-go/project_markdown_uploads.go b/vendor/gitlab.com/gitlab-org/api/client-go/project_markdown_uploads.go new file mode 100644 index 0000000000..3eb7ebce14 --- /dev/null +++ b/vendor/gitlab.com/gitlab-org/api/client-go/project_markdown_uploads.go @@ -0,0 +1,211 @@ +// +// Copyright 2024, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "bytes" + "fmt" + "io" + "net/http" + "time" +) + +// ProjectMarkdownUploadsService handles communication with the project markdown uploads +// related methods of the GitLab API. +// +// Gitlab API docs: https://docs.gitlab.com/ee/api/project_markdown_uploads.html +type ProjectMarkdownUploadsService struct { + client *Client +} + +// ProjectMarkdownUploadedFile represents a single project markdown uploaded file. +// +// Gitlab API docs: https://docs.gitlab.com/ee/api/project_markdown_uploads.html +type ProjectMarkdownUploadedFile struct { + ID int `json:"id"` + Alt string `json:"alt"` + URL string `json:"url"` + FullPath string `json:"full_path"` + Markdown string `json:"markdown"` +} + +// ProjectMarkdownUpload represents a single project markdown upload. +// +// Gitlab API docs: https://docs.gitlab.com/ee/api/project_markdown_uploads.html +type ProjectMarkdownUpload struct { + ID int `json:"id"` + Size int `json:"size"` + Filename string `json:"filename"` + CreatedAt *time.Time `json:"created_at"` + UploadedBy *User `json:"uploaded_by"` +} + +// Gets a string representation of a ProjectMarkdownUpload. +// +// GitLab API docs: https://docs.gitlab.com/ee/api/project_markdown_uploads.html +func (m ProjectMarkdownUpload) String() string { + return Stringify(m) +} + +// UploadProjectMarkdown uploads a markdown file to a project. +// +// GitLab docs: +// https://docs.gitlab.com/ee/api/project_markdown_uploads.html#upload-a-file +func (s *ProjectMarkdownUploadsService) UploadProjectMarkdown(pid interface{}, content io.Reader, filename string, options ...RequestOptionFunc) (*ProjectMarkdownUploadedFile, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/uploads", PathEscape(project)) + + req, err := s.client.UploadRequest( + http.MethodPost, + u, + content, + filename, + UploadFile, + nil, + options, + ) + if err != nil { + return nil, nil, err + } + + f := new(ProjectMarkdownUploadedFile) + resp, err := s.client.Do(req, f) + if err != nil { + return nil, resp, err + } + + return f, resp, nil +} + +// ListProjectMarkdownUploads gets all markdown uploads for a project. +// +// GitLab API Docs: +// https://docs.gitlab.com/ee/api/project_markdown_uploads.html#list-uploads +func (s *ProjectMarkdownUploadsService) ListProjectMarkdownUploads(pid interface{}, options ...RequestOptionFunc) ([]*ProjectMarkdownUpload, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/uploads", PathEscape(project)) + + req, err := s.client.NewRequest(http.MethodGet, u, nil, options) + if err != nil { + return nil, nil, err + } + + var uploads []*ProjectMarkdownUpload + resp, err := s.client.Do(req, &uploads) + if err != nil { + return nil, resp, err + } + + return uploads, resp, err +} + +// DownloadProjectMarkdownUploadByID downloads a specific upload by ID. +// +// GitLab API Docs: +// https://docs.gitlab.com/ee/api/project_markdown_uploads.html#download-an-uploaded-file-by-id +func (s *ProjectMarkdownUploadsService) DownloadProjectMarkdownUploadByID(pid interface{}, uploadID int, options ...RequestOptionFunc) ([]byte, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/uploads/%d", PathEscape(project), uploadID) + + req, err := s.client.NewRequest(http.MethodGet, u, nil, options) + if err != nil { + return nil, nil, err + } + + var f bytes.Buffer + resp, err := s.client.Do(req, &f) + if err != nil { + return nil, resp, err + } + + return f.Bytes(), resp, err +} + +// DownloadProjectMarkdownUploadBySecretAndFilename downloads a specific upload +// by secret and filename. +// +// GitLab API Docs: +// https://docs.gitlab.com/ee/api/project_markdown_uploads.html#download-an-uploaded-file-by-secret-and-filename +func (s *ProjectMarkdownUploadsService) DownloadProjectMarkdownUploadBySecretAndFilename(pid interface{}, secret string, filename string, options ...RequestOptionFunc) ([]byte, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/uploads/%s/%s", PathEscape(project), PathEscape(secret), PathEscape(filename)) + + req, err := s.client.NewRequest(http.MethodGet, u, nil, options) + if err != nil { + return nil, nil, err + } + + var f bytes.Buffer + resp, err := s.client.Do(req, &f) + if err != nil { + return nil, resp, err + } + + return f.Bytes(), resp, err +} + +// DeleteProjectMarkdownUploadByID deletes an upload by ID. +// +// GitLab API Docs: +// https://docs.gitlab.com/ee/api/project_markdown_uploads.html#delete-an-uploaded-file-by-id +func (s *ProjectMarkdownUploadsService) DeleteProjectMarkdownUploadByID(pid interface{}, uploadID int, options ...RequestOptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/uploads/%d", PathEscape(project), uploadID) + + req, err := s.client.NewRequest(http.MethodDelete, u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + +// DeleteProjectMarkdownUploadBySecretAndFilename deletes an upload +// by secret and filename. +// +// GitLab API Docs: +// https://docs.gitlab.com/ee/api/project_markdown_uploads.html#delete-an-uploaded-file-by-secret-and-filename +func (s *ProjectMarkdownUploadsService) DeleteProjectMarkdownUploadBySecretAndFilename(pid interface{}, secret string, filename string, options ...RequestOptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/uploads/%s/%s", + PathEscape(project), PathEscape(secret), PathEscape(filename)) + + req, err := s.client.NewRequest(http.MethodDelete, u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} diff --git a/vendor/github.com/xanzy/go-gitlab/project_members.go b/vendor/gitlab.com/gitlab-org/api/client-go/project_members.go similarity index 91% rename from vendor/github.com/xanzy/go-gitlab/project_members.go rename to vendor/gitlab.com/gitlab-org/api/client-go/project_members.go index 37d4b8a2e6..c47a77ef06 100644 --- a/vendor/github.com/xanzy/go-gitlab/project_members.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/project_members.go @@ -19,6 +19,7 @@ package gitlab import ( "fmt" "net/http" + "time" ) // ProjectMembersService handles communication with the project members @@ -29,6 +30,24 @@ type ProjectMembersService struct { client *Client } +// ProjectMember represents a project member. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/members.html +type ProjectMember struct { + ID int `json:"id"` + Username string `json:"username"` + Email string `json:"email"` + Name string `json:"name"` + State string `json:"state"` + CreatedAt *time.Time `json:"created_at"` + ExpiresAt *ISOTime `json:"expires_at"` + AccessLevel AccessLevelValue `json:"access_level"` + WebURL string `json:"web_url"` + AvatarURL string `json:"avatar_url"` + MemberRole *MemberRole `json:"member_role"` +} + // ListProjectMembersOptions represents the available ListProjectMembers() and // ListAllProjectMembers() options. // diff --git a/vendor/github.com/xanzy/go-gitlab/project_mirror.go b/vendor/gitlab.com/gitlab-org/api/client-go/project_mirror.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/project_mirror.go rename to vendor/gitlab.com/gitlab-org/api/client-go/project_mirror.go diff --git a/vendor/github.com/xanzy/go-gitlab/project_repository_storage_move.go b/vendor/gitlab.com/gitlab-org/api/client-go/project_repository_storage_move.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/project_repository_storage_move.go rename to vendor/gitlab.com/gitlab-org/api/client-go/project_repository_storage_move.go diff --git a/vendor/github.com/xanzy/go-gitlab/project_snippets.go b/vendor/gitlab.com/gitlab-org/api/client-go/project_snippets.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/project_snippets.go rename to vendor/gitlab.com/gitlab-org/api/client-go/project_snippets.go diff --git a/vendor/github.com/xanzy/go-gitlab/project_templates.go b/vendor/gitlab.com/gitlab-org/api/client-go/project_templates.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/project_templates.go rename to vendor/gitlab.com/gitlab-org/api/client-go/project_templates.go diff --git a/vendor/github.com/xanzy/go-gitlab/project_variables.go b/vendor/gitlab.com/gitlab-org/api/client-go/project_variables.go similarity index 98% rename from vendor/github.com/xanzy/go-gitlab/project_variables.go rename to vendor/gitlab.com/gitlab-org/api/client-go/project_variables.go index e75c74634a..9dea091bf0 100644 --- a/vendor/github.com/xanzy/go-gitlab/project_variables.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/project_variables.go @@ -41,6 +41,7 @@ type ProjectVariable struct { VariableType VariableTypeValue `json:"variable_type"` Protected bool `json:"protected"` Masked bool `json:"masked"` + Hidden bool `json:"hidden"` Raw bool `json:"raw"` EnvironmentScope string `json:"environment_scope"` Description string `json:"description"` @@ -132,6 +133,7 @@ type CreateProjectVariableOptions struct { Description *string `url:"description,omitempty" json:"description,omitempty"` EnvironmentScope *string `url:"environment_scope,omitempty" json:"environment_scope,omitempty"` Masked *bool `url:"masked,omitempty" json:"masked,omitempty"` + MaskedAndHidden *bool `url:"masked_and_hidden,omitempty" json:"masked_and_hidden,omitempty"` Protected *bool `url:"protected,omitempty" json:"protected,omitempty"` Raw *bool `url:"raw,omitempty" json:"raw,omitempty"` VariableType *VariableTypeValue `url:"variable_type,omitempty" json:"variable_type,omitempty"` diff --git a/vendor/github.com/xanzy/go-gitlab/project_vulnerabilities.go b/vendor/gitlab.com/gitlab-org/api/client-go/project_vulnerabilities.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/project_vulnerabilities.go rename to vendor/gitlab.com/gitlab-org/api/client-go/project_vulnerabilities.go diff --git a/vendor/github.com/xanzy/go-gitlab/projects.go b/vendor/gitlab.com/gitlab-org/api/client-go/projects.go similarity index 85% rename from vendor/github.com/xanzy/go-gitlab/projects.go rename to vendor/gitlab.com/gitlab-org/api/client-go/projects.go index cc23f265d0..ae108d9fa3 100644 --- a/vendor/github.com/xanzy/go-gitlab/projects.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/projects.go @@ -17,6 +17,7 @@ package gitlab import ( + "bytes" "encoding/json" "fmt" "io" @@ -66,6 +67,7 @@ type Project struct { ContainerRegistryAccessLevel AccessControlValue `json:"container_registry_access_level"` ContainerRegistryImagePrefix string `json:"container_registry_image_prefix,omitempty"` CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` LastActivityAt *time.Time `json:"last_activity_at,omitempty"` CreatorID int `json:"creator_id"` Namespace *ProjectNamespace `json:"namespace"` @@ -83,6 +85,7 @@ type Project struct { StarCount int `json:"star_count"` RunnersToken string `json:"runners_token"` AllowMergeOnSkippedPipeline bool `json:"allow_merge_on_skipped_pipeline"` + AllowPipelineTriggerApproveDeployment bool `json:"allow_pipeline_trigger_approve_deployment"` OnlyAllowMergeIfPipelineSucceeds bool `json:"only_allow_merge_if_pipeline_succeeds"` OnlyAllowMergeIfAllDiscussionsAreResolved bool `json:"only_allow_merge_if_all_discussions_are_resolved"` RemoveSourceBranchAfterMerge bool `json:"remove_source_branch_after_merge"` @@ -127,49 +130,50 @@ type Project struct { GroupFullPath string `json:"group_full_path"` GroupAccessLevel int `json:"group_access_level"` } `json:"shared_with_groups"` - Statistics *Statistics `json:"statistics"` - Links *Links `json:"_links,omitempty"` - ImportURL string `json:"import_url"` - ImportType string `json:"import_type"` - ImportStatus string `json:"import_status"` - ImportError string `json:"import_error"` - CIDefaultGitDepth int `json:"ci_default_git_depth"` - CIForwardDeploymentEnabled bool `json:"ci_forward_deployment_enabled"` - CIForwardDeploymentRollbackAllowed bool `json:"ci_forward_deployment_rollback_allowed"` - CISeperateCache bool `json:"ci_separated_caches"` - CIJobTokenScopeEnabled bool `json:"ci_job_token_scope_enabled"` - CIOptInJWT bool `json:"ci_opt_in_jwt"` - CIAllowForkPipelinesToRunInParentProject bool `json:"ci_allow_fork_pipelines_to_run_in_parent_project"` - CIRestrictPipelineCancellationRole AccessControlValue `json:"ci_restrict_pipeline_cancellation_role"` - PublicJobs bool `json:"public_jobs"` - BuildTimeout int `json:"build_timeout"` - AutoCancelPendingPipelines string `json:"auto_cancel_pending_pipelines"` - CIConfigPath string `json:"ci_config_path"` - CustomAttributes []*CustomAttribute `json:"custom_attributes"` - ComplianceFrameworks []string `json:"compliance_frameworks"` - BuildCoverageRegex string `json:"build_coverage_regex"` - IssuesTemplate string `json:"issues_template"` - MergeRequestsTemplate string `json:"merge_requests_template"` - IssueBranchTemplate string `json:"issue_branch_template"` - KeepLatestArtifact bool `json:"keep_latest_artifact"` - MergePipelinesEnabled bool `json:"merge_pipelines_enabled"` - MergeTrainsEnabled bool `json:"merge_trains_enabled"` - RestrictUserDefinedVariables bool `json:"restrict_user_defined_variables"` - MergeCommitTemplate string `json:"merge_commit_template"` - SquashCommitTemplate string `json:"squash_commit_template"` - AutoDevopsDeployStrategy string `json:"auto_devops_deploy_strategy"` - AutoDevopsEnabled bool `json:"auto_devops_enabled"` - BuildGitStrategy string `json:"build_git_strategy"` - EmailsEnabled bool `json:"emails_enabled"` - ExternalAuthorizationClassificationLabel string `json:"external_authorization_classification_label"` - RequirementsEnabled bool `json:"requirements_enabled"` - RequirementsAccessLevel AccessControlValue `json:"requirements_access_level"` - SecurityAndComplianceEnabled bool `json:"security_and_compliance_enabled"` - SecurityAndComplianceAccessLevel AccessControlValue `json:"security_and_compliance_access_level"` - MergeRequestDefaultTargetSelf bool `json:"mr_default_target_self"` - ModelExperimentsAccessLevel AccessControlValue `json:"model_experiments_access_level"` - ModelRegistryAccessLevel AccessControlValue `json:"model_registry_access_level"` - PreReceiveSecretDetectionEnabled bool `json:"pre_receive_secret_detection_enabled"` + Statistics *Statistics `json:"statistics"` + Links *Links `json:"_links,omitempty"` + ImportURL string `json:"import_url"` + ImportType string `json:"import_type"` + ImportStatus string `json:"import_status"` + ImportError string `json:"import_error"` + CIDefaultGitDepth int `json:"ci_default_git_depth"` + CIForwardDeploymentEnabled bool `json:"ci_forward_deployment_enabled"` + CIForwardDeploymentRollbackAllowed bool `json:"ci_forward_deployment_rollback_allowed"` + CISeperateCache bool `json:"ci_separated_caches"` + CIJobTokenScopeEnabled bool `json:"ci_job_token_scope_enabled"` + CIOptInJWT bool `json:"ci_opt_in_jwt"` + CIAllowForkPipelinesToRunInParentProject bool `json:"ci_allow_fork_pipelines_to_run_in_parent_project"` + CIRestrictPipelineCancellationRole AccessControlValue `json:"ci_restrict_pipeline_cancellation_role"` + PublicJobs bool `json:"public_jobs"` + BuildTimeout int `json:"build_timeout"` + AutoCancelPendingPipelines string `json:"auto_cancel_pending_pipelines"` + CIConfigPath string `json:"ci_config_path"` + CustomAttributes []*CustomAttribute `json:"custom_attributes"` + ComplianceFrameworks []string `json:"compliance_frameworks"` + BuildCoverageRegex string `json:"build_coverage_regex"` + IssuesTemplate string `json:"issues_template"` + MergeRequestsTemplate string `json:"merge_requests_template"` + IssueBranchTemplate string `json:"issue_branch_template"` + KeepLatestArtifact bool `json:"keep_latest_artifact"` + MergePipelinesEnabled bool `json:"merge_pipelines_enabled"` + MergeTrainsEnabled bool `json:"merge_trains_enabled"` + RestrictUserDefinedVariables bool `json:"restrict_user_defined_variables"` + CIPipelineVariablesMinimumOverrideRole CIPipelineVariablesMinimumOverrideRoleValue `json:"ci_pipeline_variables_minimum_override_role"` + MergeCommitTemplate string `json:"merge_commit_template"` + SquashCommitTemplate string `json:"squash_commit_template"` + AutoDevopsDeployStrategy string `json:"auto_devops_deploy_strategy"` + AutoDevopsEnabled bool `json:"auto_devops_enabled"` + BuildGitStrategy string `json:"build_git_strategy"` + EmailsEnabled bool `json:"emails_enabled"` + ExternalAuthorizationClassificationLabel string `json:"external_authorization_classification_label"` + RequirementsEnabled bool `json:"requirements_enabled"` + RequirementsAccessLevel AccessControlValue `json:"requirements_access_level"` + SecurityAndComplianceEnabled bool `json:"security_and_compliance_enabled"` + SecurityAndComplianceAccessLevel AccessControlValue `json:"security_and_compliance_access_level"` + MergeRequestDefaultTargetSelf bool `json:"mr_default_target_self"` + ModelExperimentsAccessLevel AccessControlValue `json:"model_experiments_access_level"` + ModelRegistryAccessLevel AccessControlValue `json:"model_registry_access_level"` + PreReceiveSecretDetectionEnabled bool `json:"pre_receive_secret_detection_enabled"` // Deprecated: Use EmailsEnabled instead EmailsDisabled bool `json:"emails_disabled"` @@ -832,89 +836,90 @@ func (s *ProjectsService) CreateProjectForUser(user int, opt *CreateProjectForUs // // GitLab API docs: https://docs.gitlab.com/ee/api/projects.html#edit-project type EditProjectOptions struct { - AllowMergeOnSkippedPipeline *bool `url:"allow_merge_on_skipped_pipeline,omitempty" json:"allow_merge_on_skipped_pipeline,omitempty"` - AllowPipelineTriggerApproveDeployment *bool `url:"allow_pipeline_trigger_approve_deployment,omitempty" json:"allow_pipeline_trigger_approve_deployment,omitempty"` - OnlyAllowMergeIfAllStatusChecksPassed *bool `url:"only_allow_merge_if_all_status_checks_passed,omitempty" json:"only_allow_merge_if_all_status_checks_passed,omitempty"` - AnalyticsAccessLevel *AccessControlValue `url:"analytics_access_level,omitempty" json:"analytics_access_level,omitempty"` - ApprovalsBeforeMerge *int `url:"approvals_before_merge,omitempty" json:"approvals_before_merge,omitempty"` - AutoCancelPendingPipelines *string `url:"auto_cancel_pending_pipelines,omitempty" json:"auto_cancel_pending_pipelines,omitempty"` - AutoDevopsDeployStrategy *string `url:"auto_devops_deploy_strategy,omitempty" json:"auto_devops_deploy_strategy,omitempty"` - AutoDevopsEnabled *bool `url:"auto_devops_enabled,omitempty" json:"auto_devops_enabled,omitempty"` - AutocloseReferencedIssues *bool `url:"autoclose_referenced_issues,omitempty" json:"autoclose_referenced_issues,omitempty"` - Avatar *ProjectAvatar `url:"-" json:"avatar,omitempty"` - BuildCoverageRegex *string `url:"build_coverage_regex,omitempty" json:"build_coverage_regex,omitempty"` - BuildGitStrategy *string `url:"build_git_strategy,omitempty" json:"build_git_strategy,omitempty"` - BuildTimeout *int `url:"build_timeout,omitempty" json:"build_timeout,omitempty"` - BuildsAccessLevel *AccessControlValue `url:"builds_access_level,omitempty" json:"builds_access_level,omitempty"` - CIConfigPath *string `url:"ci_config_path,omitempty" json:"ci_config_path,omitempty"` - CIDefaultGitDepth *int `url:"ci_default_git_depth,omitempty" json:"ci_default_git_depth,omitempty"` - CIForwardDeploymentEnabled *bool `url:"ci_forward_deployment_enabled,omitempty" json:"ci_forward_deployment_enabled,omitempty"` - CIForwardDeploymentRollbackAllowed *bool `url:"ci_forward_deployment_rollback_allowed,omitempty" json:"ci_forward_deployment_rollback_allowed,omitempty"` - CISeperateCache *bool `url:"ci_separated_caches,omitempty" json:"ci_separated_caches,omitempty"` - CIRestrictPipelineCancellationRole *AccessControlValue `url:"ci_restrict_pipeline_cancellation_role,omitempty" json:"ci_restrict_pipeline_cancellation_role,omitempty"` - ContainerExpirationPolicyAttributes *ContainerExpirationPolicyAttributes `url:"container_expiration_policy_attributes,omitempty" json:"container_expiration_policy_attributes,omitempty"` - ContainerRegistryAccessLevel *AccessControlValue `url:"container_registry_access_level,omitempty" json:"container_registry_access_level,omitempty"` - DefaultBranch *string `url:"default_branch,omitempty" json:"default_branch,omitempty"` - Description *string `url:"description,omitempty" json:"description,omitempty"` - EmailsEnabled *bool `url:"emails_enabled,omitempty" json:"emails_enabled,omitempty"` - EnforceAuthChecksOnUploads *bool `url:"enforce_auth_checks_on_uploads,omitempty" json:"enforce_auth_checks_on_uploads,omitempty"` - ExternalAuthorizationClassificationLabel *string `url:"external_authorization_classification_label,omitempty" json:"external_authorization_classification_label,omitempty"` - ForkingAccessLevel *AccessControlValue `url:"forking_access_level,omitempty" json:"forking_access_level,omitempty"` - ImportURL *string `url:"import_url,omitempty" json:"import_url,omitempty"` - IssuesAccessLevel *AccessControlValue `url:"issues_access_level,omitempty" json:"issues_access_level,omitempty"` - IssueBranchTemplate *string `url:"issue_branch_template,omitempty" json:"issue_branch_template,omitempty"` - IssuesTemplate *string `url:"issues_template,omitempty" json:"issues_template,omitempty"` - KeepLatestArtifact *bool `url:"keep_latest_artifact,omitempty" json:"keep_latest_artifact,omitempty"` - LFSEnabled *bool `url:"lfs_enabled,omitempty" json:"lfs_enabled,omitempty"` - MergeCommitTemplate *string `url:"merge_commit_template,omitempty" json:"merge_commit_template,omitempty"` - MergeRequestDefaultTargetSelf *bool `url:"mr_default_target_self,omitempty" json:"mr_default_target_self,omitempty"` - MergeMethod *MergeMethodValue `url:"merge_method,omitempty" json:"merge_method,omitempty"` - MergePipelinesEnabled *bool `url:"merge_pipelines_enabled,omitempty" json:"merge_pipelines_enabled,omitempty"` - MergeRequestsAccessLevel *AccessControlValue `url:"merge_requests_access_level,omitempty" json:"merge_requests_access_level,omitempty"` - MergeRequestsTemplate *string `url:"merge_requests_template,omitempty" json:"merge_requests_template,omitempty"` - MergeTrainsEnabled *bool `url:"merge_trains_enabled,omitempty" json:"merge_trains_enabled,omitempty"` - Mirror *bool `url:"mirror,omitempty" json:"mirror,omitempty"` - MirrorBranchRegex *string `url:"mirror_branch_regex,omitempty" json:"mirror_branch_regex,omitempty"` - MirrorOverwritesDivergedBranches *bool `url:"mirror_overwrites_diverged_branches,omitempty" json:"mirror_overwrites_diverged_branches,omitempty"` - MirrorTriggerBuilds *bool `url:"mirror_trigger_builds,omitempty" json:"mirror_trigger_builds,omitempty"` - MirrorUserID *int `url:"mirror_user_id,omitempty" json:"mirror_user_id,omitempty"` - ModelExperimentsAccessLevel *AccessControlValue `url:"model_experiments_access_level,omitempty" json:"model_experiments_access_level,omitempty"` - ModelRegistryAccessLevel *AccessControlValue `url:"model_registry_access_level,omitempty" json:"model_registry_access_level,omitempty"` - Name *string `url:"name,omitempty" json:"name,omitempty"` - OnlyAllowMergeIfAllDiscussionsAreResolved *bool `url:"only_allow_merge_if_all_discussions_are_resolved,omitempty" json:"only_allow_merge_if_all_discussions_are_resolved,omitempty"` - OnlyAllowMergeIfPipelineSucceeds *bool `url:"only_allow_merge_if_pipeline_succeeds,omitempty" json:"only_allow_merge_if_pipeline_succeeds,omitempty"` - OnlyMirrorProtectedBranches *bool `url:"only_mirror_protected_branches,omitempty" json:"only_mirror_protected_branches,omitempty"` - OperationsAccessLevel *AccessControlValue `url:"operations_access_level,omitempty" json:"operations_access_level,omitempty"` - PackagesEnabled *bool `url:"packages_enabled,omitempty" json:"packages_enabled,omitempty"` - PagesAccessLevel *AccessControlValue `url:"pages_access_level,omitempty" json:"pages_access_level,omitempty"` - Path *string `url:"path,omitempty" json:"path,omitempty"` - PublicBuilds *bool `url:"public_builds,omitempty" json:"public_builds,omitempty"` - ReleasesAccessLevel *AccessControlValue `url:"releases_access_level,omitempty" json:"releases_access_level,omitempty"` - EnvironmentsAccessLevel *AccessControlValue `url:"environments_access_level,omitempty" json:"environments_access_level,omitempty"` - FeatureFlagsAccessLevel *AccessControlValue `url:"feature_flags_access_level,omitempty" json:"feature_flags_access_level,omitempty"` - InfrastructureAccessLevel *AccessControlValue `url:"infrastructure_access_level,omitempty" json:"infrastructure_access_level,omitempty"` - MonitorAccessLevel *AccessControlValue `url:"monitor_access_level,omitempty" json:"monitor_access_level,omitempty"` - RemoveSourceBranchAfterMerge *bool `url:"remove_source_branch_after_merge,omitempty" json:"remove_source_branch_after_merge,omitempty"` - PreventMergeWithoutJiraIssue *bool `url:"prevent_merge_without_jira_issue,omitempty" json:"prevent_merge_without_jira_issue,omitempty"` - PrintingMergeRequestLinkEnabled *bool `url:"printing_merge_request_link_enabled,omitempty" json:"printing_merge_request_link_enabled,omitempty"` - RepositoryAccessLevel *AccessControlValue `url:"repository_access_level,omitempty" json:"repository_access_level,omitempty"` - RepositoryStorage *string `url:"repository_storage,omitempty" json:"repository_storage,omitempty"` - RequestAccessEnabled *bool `url:"request_access_enabled,omitempty" json:"request_access_enabled,omitempty"` - RequirementsAccessLevel *AccessControlValue `url:"requirements_access_level,omitempty" json:"requirements_access_level,omitempty"` - ResolveOutdatedDiffDiscussions *bool `url:"resolve_outdated_diff_discussions,omitempty" json:"resolve_outdated_diff_discussions,omitempty"` - RestrictUserDefinedVariables *bool `url:"restrict_user_defined_variables,omitempty" json:"restrict_user_defined_variables,omitempty"` - SecurityAndComplianceAccessLevel *AccessControlValue `url:"security_and_compliance_access_level,omitempty" json:"security_and_compliance_access_level,omitempty"` - ServiceDeskEnabled *bool `url:"service_desk_enabled,omitempty" json:"service_desk_enabled,omitempty"` - SharedRunnersEnabled *bool `url:"shared_runners_enabled,omitempty" json:"shared_runners_enabled,omitempty"` - GroupRunnersEnabled *bool `url:"group_runners_enabled,omitempty" json:"group_runners_enabled,omitempty"` - ShowDefaultAwardEmojis *bool `url:"show_default_award_emojis,omitempty" json:"show_default_award_emojis,omitempty"` - SnippetsAccessLevel *AccessControlValue `url:"snippets_access_level,omitempty" json:"snippets_access_level,omitempty"` - SquashCommitTemplate *string `url:"squash_commit_template,omitempty" json:"squash_commit_template,omitempty"` - SquashOption *SquashOptionValue `url:"squash_option,omitempty" json:"squash_option,omitempty"` - SuggestionCommitMessage *string `url:"suggestion_commit_message,omitempty" json:"suggestion_commit_message,omitempty"` - Topics *[]string `url:"topics,omitempty" json:"topics,omitempty"` - Visibility *VisibilityValue `url:"visibility,omitempty" json:"visibility,omitempty"` - WikiAccessLevel *AccessControlValue `url:"wiki_access_level,omitempty" json:"wiki_access_level,omitempty"` + AllowMergeOnSkippedPipeline *bool `url:"allow_merge_on_skipped_pipeline,omitempty" json:"allow_merge_on_skipped_pipeline,omitempty"` + AllowPipelineTriggerApproveDeployment *bool `url:"allow_pipeline_trigger_approve_deployment,omitempty" json:"allow_pipeline_trigger_approve_deployment,omitempty"` + OnlyAllowMergeIfAllStatusChecksPassed *bool `url:"only_allow_merge_if_all_status_checks_passed,omitempty" json:"only_allow_merge_if_all_status_checks_passed,omitempty"` + AnalyticsAccessLevel *AccessControlValue `url:"analytics_access_level,omitempty" json:"analytics_access_level,omitempty"` + ApprovalsBeforeMerge *int `url:"approvals_before_merge,omitempty" json:"approvals_before_merge,omitempty"` + AutoCancelPendingPipelines *string `url:"auto_cancel_pending_pipelines,omitempty" json:"auto_cancel_pending_pipelines,omitempty"` + AutoDevopsDeployStrategy *string `url:"auto_devops_deploy_strategy,omitempty" json:"auto_devops_deploy_strategy,omitempty"` + AutoDevopsEnabled *bool `url:"auto_devops_enabled,omitempty" json:"auto_devops_enabled,omitempty"` + AutocloseReferencedIssues *bool `url:"autoclose_referenced_issues,omitempty" json:"autoclose_referenced_issues,omitempty"` + Avatar *ProjectAvatar `url:"-" json:"avatar,omitempty"` + BuildCoverageRegex *string `url:"build_coverage_regex,omitempty" json:"build_coverage_regex,omitempty"` + BuildGitStrategy *string `url:"build_git_strategy,omitempty" json:"build_git_strategy,omitempty"` + BuildTimeout *int `url:"build_timeout,omitempty" json:"build_timeout,omitempty"` + BuildsAccessLevel *AccessControlValue `url:"builds_access_level,omitempty" json:"builds_access_level,omitempty"` + CIConfigPath *string `url:"ci_config_path,omitempty" json:"ci_config_path,omitempty"` + CIDefaultGitDepth *int `url:"ci_default_git_depth,omitempty" json:"ci_default_git_depth,omitempty"` + CIForwardDeploymentEnabled *bool `url:"ci_forward_deployment_enabled,omitempty" json:"ci_forward_deployment_enabled,omitempty"` + CIForwardDeploymentRollbackAllowed *bool `url:"ci_forward_deployment_rollback_allowed,omitempty" json:"ci_forward_deployment_rollback_allowed,omitempty"` + CISeperateCache *bool `url:"ci_separated_caches,omitempty" json:"ci_separated_caches,omitempty"` + CIRestrictPipelineCancellationRole *AccessControlValue `url:"ci_restrict_pipeline_cancellation_role,omitempty" json:"ci_restrict_pipeline_cancellation_role,omitempty"` + CIPipelineVariablesMinimumOverrideRole *CIPipelineVariablesMinimumOverrideRoleValue `url:"ci_pipeline_variables_minimum_override_role,omitempty" json:"ci_pipeline_variables_minimum_override_role,omitempty"` + ContainerExpirationPolicyAttributes *ContainerExpirationPolicyAttributes `url:"container_expiration_policy_attributes,omitempty" json:"container_expiration_policy_attributes,omitempty"` + ContainerRegistryAccessLevel *AccessControlValue `url:"container_registry_access_level,omitempty" json:"container_registry_access_level,omitempty"` + DefaultBranch *string `url:"default_branch,omitempty" json:"default_branch,omitempty"` + Description *string `url:"description,omitempty" json:"description,omitempty"` + EmailsEnabled *bool `url:"emails_enabled,omitempty" json:"emails_enabled,omitempty"` + EnforceAuthChecksOnUploads *bool `url:"enforce_auth_checks_on_uploads,omitempty" json:"enforce_auth_checks_on_uploads,omitempty"` + ExternalAuthorizationClassificationLabel *string `url:"external_authorization_classification_label,omitempty" json:"external_authorization_classification_label,omitempty"` + ForkingAccessLevel *AccessControlValue `url:"forking_access_level,omitempty" json:"forking_access_level,omitempty"` + ImportURL *string `url:"import_url,omitempty" json:"import_url,omitempty"` + IssuesAccessLevel *AccessControlValue `url:"issues_access_level,omitempty" json:"issues_access_level,omitempty"` + IssueBranchTemplate *string `url:"issue_branch_template,omitempty" json:"issue_branch_template,omitempty"` + IssuesTemplate *string `url:"issues_template,omitempty" json:"issues_template,omitempty"` + KeepLatestArtifact *bool `url:"keep_latest_artifact,omitempty" json:"keep_latest_artifact,omitempty"` + LFSEnabled *bool `url:"lfs_enabled,omitempty" json:"lfs_enabled,omitempty"` + MergeCommitTemplate *string `url:"merge_commit_template,omitempty" json:"merge_commit_template,omitempty"` + MergeRequestDefaultTargetSelf *bool `url:"mr_default_target_self,omitempty" json:"mr_default_target_self,omitempty"` + MergeMethod *MergeMethodValue `url:"merge_method,omitempty" json:"merge_method,omitempty"` + MergePipelinesEnabled *bool `url:"merge_pipelines_enabled,omitempty" json:"merge_pipelines_enabled,omitempty"` + MergeRequestsAccessLevel *AccessControlValue `url:"merge_requests_access_level,omitempty" json:"merge_requests_access_level,omitempty"` + MergeRequestsTemplate *string `url:"merge_requests_template,omitempty" json:"merge_requests_template,omitempty"` + MergeTrainsEnabled *bool `url:"merge_trains_enabled,omitempty" json:"merge_trains_enabled,omitempty"` + Mirror *bool `url:"mirror,omitempty" json:"mirror,omitempty"` + MirrorBranchRegex *string `url:"mirror_branch_regex,omitempty" json:"mirror_branch_regex,omitempty"` + MirrorOverwritesDivergedBranches *bool `url:"mirror_overwrites_diverged_branches,omitempty" json:"mirror_overwrites_diverged_branches,omitempty"` + MirrorTriggerBuilds *bool `url:"mirror_trigger_builds,omitempty" json:"mirror_trigger_builds,omitempty"` + MirrorUserID *int `url:"mirror_user_id,omitempty" json:"mirror_user_id,omitempty"` + ModelExperimentsAccessLevel *AccessControlValue `url:"model_experiments_access_level,omitempty" json:"model_experiments_access_level,omitempty"` + ModelRegistryAccessLevel *AccessControlValue `url:"model_registry_access_level,omitempty" json:"model_registry_access_level,omitempty"` + Name *string `url:"name,omitempty" json:"name,omitempty"` + OnlyAllowMergeIfAllDiscussionsAreResolved *bool `url:"only_allow_merge_if_all_discussions_are_resolved,omitempty" json:"only_allow_merge_if_all_discussions_are_resolved,omitempty"` + OnlyAllowMergeIfPipelineSucceeds *bool `url:"only_allow_merge_if_pipeline_succeeds,omitempty" json:"only_allow_merge_if_pipeline_succeeds,omitempty"` + OnlyMirrorProtectedBranches *bool `url:"only_mirror_protected_branches,omitempty" json:"only_mirror_protected_branches,omitempty"` + OperationsAccessLevel *AccessControlValue `url:"operations_access_level,omitempty" json:"operations_access_level,omitempty"` + PackagesEnabled *bool `url:"packages_enabled,omitempty" json:"packages_enabled,omitempty"` + PagesAccessLevel *AccessControlValue `url:"pages_access_level,omitempty" json:"pages_access_level,omitempty"` + Path *string `url:"path,omitempty" json:"path,omitempty"` + PublicBuilds *bool `url:"public_builds,omitempty" json:"public_builds,omitempty"` + ReleasesAccessLevel *AccessControlValue `url:"releases_access_level,omitempty" json:"releases_access_level,omitempty"` + EnvironmentsAccessLevel *AccessControlValue `url:"environments_access_level,omitempty" json:"environments_access_level,omitempty"` + FeatureFlagsAccessLevel *AccessControlValue `url:"feature_flags_access_level,omitempty" json:"feature_flags_access_level,omitempty"` + InfrastructureAccessLevel *AccessControlValue `url:"infrastructure_access_level,omitempty" json:"infrastructure_access_level,omitempty"` + MonitorAccessLevel *AccessControlValue `url:"monitor_access_level,omitempty" json:"monitor_access_level,omitempty"` + RemoveSourceBranchAfterMerge *bool `url:"remove_source_branch_after_merge,omitempty" json:"remove_source_branch_after_merge,omitempty"` + PreventMergeWithoutJiraIssue *bool `url:"prevent_merge_without_jira_issue,omitempty" json:"prevent_merge_without_jira_issue,omitempty"` + PrintingMergeRequestLinkEnabled *bool `url:"printing_merge_request_link_enabled,omitempty" json:"printing_merge_request_link_enabled,omitempty"` + RepositoryAccessLevel *AccessControlValue `url:"repository_access_level,omitempty" json:"repository_access_level,omitempty"` + RepositoryStorage *string `url:"repository_storage,omitempty" json:"repository_storage,omitempty"` + RequestAccessEnabled *bool `url:"request_access_enabled,omitempty" json:"request_access_enabled,omitempty"` + RequirementsAccessLevel *AccessControlValue `url:"requirements_access_level,omitempty" json:"requirements_access_level,omitempty"` + ResolveOutdatedDiffDiscussions *bool `url:"resolve_outdated_diff_discussions,omitempty" json:"resolve_outdated_diff_discussions,omitempty"` + RestrictUserDefinedVariables *bool `url:"restrict_user_defined_variables,omitempty" json:"restrict_user_defined_variables,omitempty"` + SecurityAndComplianceAccessLevel *AccessControlValue `url:"security_and_compliance_access_level,omitempty" json:"security_and_compliance_access_level,omitempty"` + ServiceDeskEnabled *bool `url:"service_desk_enabled,omitempty" json:"service_desk_enabled,omitempty"` + SharedRunnersEnabled *bool `url:"shared_runners_enabled,omitempty" json:"shared_runners_enabled,omitempty"` + GroupRunnersEnabled *bool `url:"group_runners_enabled,omitempty" json:"group_runners_enabled,omitempty"` + ShowDefaultAwardEmojis *bool `url:"show_default_award_emojis,omitempty" json:"show_default_award_emojis,omitempty"` + SnippetsAccessLevel *AccessControlValue `url:"snippets_access_level,omitempty" json:"snippets_access_level,omitempty"` + SquashCommitTemplate *string `url:"squash_commit_template,omitempty" json:"squash_commit_template,omitempty"` + SquashOption *SquashOptionValue `url:"squash_option,omitempty" json:"squash_option,omitempty"` + SuggestionCommitMessage *string `url:"suggestion_commit_message,omitempty" json:"suggestion_commit_message,omitempty"` + Topics *[]string `url:"topics,omitempty" json:"topics,omitempty"` + Visibility *VisibilityValue `url:"visibility,omitempty" json:"visibility,omitempty"` + WikiAccessLevel *AccessControlValue `url:"wiki_access_level,omitempty" json:"wiki_access_level,omitempty"` // Deprecated: Use ContainerRegistryAccessLevel instead. ContainerRegistryEnabled *bool `url:"container_registry_enabled,omitempty" json:"container_registry_enabled,omitempty"` @@ -1159,18 +1164,28 @@ func (s *ProjectsService) UnarchiveProject(pid interface{}, options ...RequestOp return p, resp, nil } +// DeleteProjectOptions represents the available DeleteProject() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/projects.html#delete-project +type DeleteProjectOptions struct { + FullPath *string `url:"full_path" json:"full_path"` + PermanentlyRemove *bool `url:"permanently_remove" json:"permanently_remove"` +} + // DeleteProject removes a project including all associated resources // (issues, merge requests etc.) // -// GitLab API docs: https://docs.gitlab.com/ee/api/projects.html#delete-project -func (s *ProjectsService) DeleteProject(pid interface{}, options ...RequestOptionFunc) (*Response, error) { +// GitLab API docs: +// https://docs.gitlab.com/ee/api/projects.html#delete-project +func (s *ProjectsService) DeleteProject(pid interface{}, opt *DeleteProjectOptions, options ...RequestOptionFunc) (*Response, error) { project, err := parseID(pid) if err != nil { return nil, err } u := fmt.Sprintf("projects/%s", PathEscape(project)) - req, err := s.client.NewRequest(http.MethodDelete, u, nil, options) + req, err := s.client.NewRequest(http.MethodDelete, u, opt, options) if err != nil { return nil, err } @@ -1178,7 +1193,7 @@ func (s *ProjectsService) DeleteProject(pid interface{}, options ...RequestOptio return s.client.Do(req, nil) } -// ShareWithGroupOptions represents options to share project with groups +// ShareWithGroupOptions represents the available SharedWithGroup() options. // // GitLab API docs: https://docs.gitlab.com/ee/api/projects.html#share-project-with-group type ShareWithGroupOptions struct { @@ -1223,23 +1238,6 @@ func (s *ProjectsService) DeleteSharedProjectFromGroup(pid interface{}, groupID return s.client.Do(req, nil) } -// ProjectMember represents a project member. -// -// GitLab API docs: -// https://docs.gitlab.com/ee/api/members.html#list-all-members-of-a-group-or-project -type ProjectMember struct { - ID int `json:"id"` - Username string `json:"username"` - Email string `json:"email"` - Name string `json:"name"` - State string `json:"state"` - CreatedAt *time.Time `json:"created_at"` - ExpiresAt *ISOTime `json:"expires_at"` - AccessLevel AccessLevelValue `json:"access_level"` - WebURL string `json:"web_url"` - AvatarURL string `json:"avatar_url"` -} - // HookCustomHeader represents a project or group hook custom header // Note: "Key" is returned from the Get operation, but "Value" is not // The List operation doesn't return any headers at all for Projects, @@ -1256,6 +1254,8 @@ type HookCustomHeader struct { type ProjectHook struct { ID int `json:"id"` URL string `json:"url"` + Name string `json:"name"` + Description string `json:"description"` ConfidentialNoteEvents bool `json:"confidential_note_events"` ProjectID int `json:"project_id"` PushEvents bool `json:"push_events"` @@ -1271,6 +1271,7 @@ type ProjectHook struct { DeploymentEvents bool `json:"deployment_events"` ReleasesEvents bool `json:"releases_events"` EnableSSLVerification bool `json:"enable_ssl_verification"` + AlertStatus string `json:"alert_status"` CreatedAt *time.Time `json:"created_at"` ResourceAccessTokenEvents bool `json:"resource_access_token_events"` CustomWebhookTemplate string `json:"custom_webhook_template"` @@ -1337,6 +1338,8 @@ func (s *ProjectsService) GetProjectHook(pid interface{}, hook int, options ...R // GitLab API docs: // https://docs.gitlab.com/ee/api/projects.html#add-project-hook type AddProjectHookOptions struct { + Name *string `url:"name,omitempty" json:"name,omitempty"` + Description *string `url:"description,omitempty" json:"description,omitempty"` ConfidentialIssuesEvents *bool `url:"confidential_issues_events,omitempty" json:"confidential_issues_events,omitempty"` ConfidentialNoteEvents *bool `url:"confidential_note_events,omitempty" json:"confidential_note_events,omitempty"` DeploymentEvents *bool `url:"deployment_events,omitempty" json:"deployment_events,omitempty"` @@ -1388,6 +1391,8 @@ func (s *ProjectsService) AddProjectHook(pid interface{}, opt *AddProjectHookOpt // GitLab API docs: // https://docs.gitlab.com/ee/api/projects.html#edit-project-hook type EditProjectHookOptions struct { + Name *string `url:"name,omitempty" json:"name,omitempty"` + Description *string `url:"description,omitempty" json:"description,omitempty"` ConfidentialIssuesEvents *bool `url:"confidential_issues_events,omitempty" json:"confidential_issues_events,omitempty"` ConfidentialNoteEvents *bool `url:"confidential_note_events,omitempty" json:"confidential_note_events,omitempty"` DeploymentEvents *bool `url:"deployment_events,omitempty" json:"deployment_events,omitempty"` @@ -1481,8 +1486,8 @@ func (s *ProjectsService) TriggerTestProjectHook(pid interface{}, hook int, even return s.client.Do(req, nil) } -// SetHookCustomHeaderOptions represents a project or group hook custom header. -// If the header isn't present, it will be created. +// SetHookCustomHeaderOptions represents the available SetProjectCustomHeader() +// options. // // GitLab API docs: // https://docs.gitlab.com/ee/api/projects.html#set-a-custom-header @@ -1597,7 +1602,11 @@ type ProjectFile struct { // UploadFile uploads a file. // -// GitLab API docs: https://docs.gitlab.com/ee/api/projects.html#upload-a-file +// Deprecated: UploadFile is deprecated and will be removed in a future release. +// Use [ProjectMarkdownUploadsService.UploadProjectMarkdown] instead for uploading +// markdown files to a project. +// +// GitLab API docs: https://docs.gitlab.com/ee/api/project_markdown_uploads.html#upload-a-file func (s *ProjectsService) UploadFile(pid interface{}, content io.Reader, filename string, options ...RequestOptionFunc) (*ProjectFile, *Response, error) { project, err := parseID(pid) if err != nil { @@ -1660,6 +1669,31 @@ func (s *ProjectsService) UploadAvatar(pid interface{}, avatar io.Reader, filena return p, resp, nil } +// DownloadAvatar downloads an avatar. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/projects.html#download-a-project-avatar +func (s *ProjectsService) DownloadAvatar(pid interface{}, options ...RequestOptionFunc) (*bytes.Reader, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/avatar", PathEscape(project)) + + req, err := s.client.NewRequest(http.MethodGet, u, nil, options) + if err != nil { + return nil, nil, err + } + + avatar := new(bytes.Buffer) + resp, err := s.client.Do(req, avatar) + if err != nil { + return nil, resp, err + } + + return bytes.NewReader(avatar.Bytes()), resp, err +} + // ListProjectForks gets a list of project forks. // // GitLab API docs: @@ -1927,9 +1961,11 @@ func (s *ProjectsService) ChangeApprovalConfiguration(pid interface{}, opt *Chan return pa, resp, nil } -// GetProjectApprovalRulesListsOptions represents the available GetProjectApprovalRules() options. +// GetProjectApprovalRulesListsOptions represents the available +// GetProjectApprovalRules() options. // -// GitLab API docs: https://docs.gitlab.com/ee/api/merge_request_approvals.html#get-project-level-rules +// GitLab API docs: +// https://docs.gitlab.com/ee/api/merge_request_approvals.html#get-project-level-rules type GetProjectApprovalRulesListsOptions ListOptions // GetProjectApprovalRules looks up the list of project level approver rules. @@ -2182,7 +2218,8 @@ func (s *ProjectsService) StartMirroringProject(pid interface{}, options ...Requ // TransferProjectOptions represents the available TransferProject() options. // -// GitLab API docs: https://docs.gitlab.com/ee/api/projects.html#transfer-a-project-to-a-new-namespace +// GitLab API docs: +// https://docs.gitlab.com/ee/api/projects.html#transfer-a-project-to-a-new-namespace type TransferProjectOptions struct { Namespace interface{} `url:"namespace,omitempty" json:"namespace,omitempty"` } diff --git a/vendor/github.com/xanzy/go-gitlab/protected_branches.go b/vendor/gitlab.com/gitlab-org/api/client-go/protected_branches.go similarity index 99% rename from vendor/github.com/xanzy/go-gitlab/protected_branches.go rename to vendor/gitlab.com/gitlab-org/api/client-go/protected_branches.go index d13f57a608..e88c7aea25 100644 --- a/vendor/github.com/xanzy/go-gitlab/protected_branches.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/protected_branches.go @@ -54,6 +54,7 @@ type BranchAccessDescription struct { ID int `json:"id"` AccessLevel AccessLevelValue `json:"access_level"` AccessLevelDescription string `json:"access_level_description"` + DeployKeyID int `json:"deploy_key_id"` UserID int `json:"user_id"` GroupID int `json:"group_id"` } diff --git a/vendor/github.com/xanzy/go-gitlab/protected_environments.go b/vendor/gitlab.com/gitlab-org/api/client-go/protected_environments.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/protected_environments.go rename to vendor/gitlab.com/gitlab-org/api/client-go/protected_environments.go diff --git a/vendor/github.com/xanzy/go-gitlab/protected_tags.go b/vendor/gitlab.com/gitlab-org/api/client-go/protected_tags.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/protected_tags.go rename to vendor/gitlab.com/gitlab-org/api/client-go/protected_tags.go diff --git a/vendor/github.com/xanzy/go-gitlab/releaselinks.go b/vendor/gitlab.com/gitlab-org/api/client-go/releaselinks.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/releaselinks.go rename to vendor/gitlab.com/gitlab-org/api/client-go/releaselinks.go diff --git a/vendor/github.com/xanzy/go-gitlab/releases.go b/vendor/gitlab.com/gitlab-org/api/client-go/releases.go similarity index 82% rename from vendor/github.com/xanzy/go-gitlab/releases.go rename to vendor/gitlab.com/gitlab-org/api/client-go/releases.go index 97cbff7bb9..26e37cb4c4 100644 --- a/vendor/github.com/xanzy/go-gitlab/releases.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/releases.go @@ -49,19 +49,22 @@ type Release struct { AvatarURL string `json:"avatar_url"` WebURL string `json:"web_url"` } `json:"author"` - Commit Commit `json:"commit"` - UpcomingRelease bool `json:"upcoming_release"` - CommitPath string `json:"commit_path"` - TagPath string `json:"tag_path"` + Commit Commit `json:"commit"` + Milestones []*ReleaseMilestone `json:"milestones"` + UpcomingRelease bool `json:"upcoming_release"` + CommitPath string `json:"commit_path"` + TagPath string `json:"tag_path"` Assets struct { Count int `json:"count"` Sources []struct { Format string `json:"format"` URL string `json:"url"` } `json:"sources"` - Links []*ReleaseLink `json:"links"` + Links []*ReleaseLink `json:"links"` + EvidenceFilePath string `json:"evidence_file_path"` } `json:"assets"` - Links struct { + Evidences []*ReleaseEvidence `json:"evidences"` + Links struct { ClosedIssueURL string `json:"closed_issues_url"` ClosedMergeRequest string `json:"closed_merge_requests_url"` EditURL string `json:"edit_url"` @@ -72,6 +75,45 @@ type Release struct { } `json:"_links"` } +// ReleaseMilestone represents a project release milestone. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/releases/index.html#list-releases +type ReleaseMilestone struct { + ID int `json:"id"` + IID int `json:"iid"` + ProjectID int `json:"project_id"` + Title string `json:"title"` + Description string `json:"description"` + State string `json:"state"` + CreatedAt *time.Time `json:"created_at"` + UpdatedAt *time.Time `json:"updated_at"` + DueDate *ISOTime `json:"due_date"` + StartDate *ISOTime `json:"start_date"` + WebURL string `json:"web_url"` + IssueStats *ReleaseMilestoneIssueStats `json:"issue_stats"` +} + +// ReleaseMilestoneIssueStats represents a project release milestone's +// related issues statistics. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/releases/index.html#list-releases +type ReleaseMilestoneIssueStats struct { + Total int `json:"total"` + Closed int `json:"closed"` +} + +// ReleaseEvidence represents a project release's evidence. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/releases/index.html#list-releases +type ReleaseEvidence struct { + SHA string `json:"sha"` + Filepath string `json:"filepath"` + CollectedAt *time.Time `json:"collected_at"` +} + // ListReleasesOptions represents ListReleases() options. // // GitLab API docs: diff --git a/vendor/github.com/xanzy/go-gitlab/repositories.go b/vendor/gitlab.com/gitlab-org/api/client-go/repositories.go similarity index 99% rename from vendor/github.com/xanzy/go-gitlab/repositories.go rename to vendor/gitlab.com/gitlab-org/api/client-go/repositories.go index dde8761749..3c59f9abc2 100644 --- a/vendor/github.com/xanzy/go-gitlab/repositories.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/repositories.go @@ -209,6 +209,7 @@ type Compare struct { Diffs []*Diff `json:"diffs"` CompareTimeout bool `json:"compare_timeout"` CompareSameRef bool `json:"compare_same_ref"` + WebURL string `json:"web_url"` } func (c Compare) String() string { diff --git a/vendor/github.com/xanzy/go-gitlab/repository_files.go b/vendor/gitlab.com/gitlab-org/api/client-go/repository_files.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/repository_files.go rename to vendor/gitlab.com/gitlab-org/api/client-go/repository_files.go diff --git a/vendor/github.com/xanzy/go-gitlab/repository_submodules.go b/vendor/gitlab.com/gitlab-org/api/client-go/repository_submodules.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/repository_submodules.go rename to vendor/gitlab.com/gitlab-org/api/client-go/repository_submodules.go diff --git a/vendor/github.com/xanzy/go-gitlab/request_options.go b/vendor/gitlab.com/gitlab-org/api/client-go/request_options.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/request_options.go rename to vendor/gitlab.com/gitlab-org/api/client-go/request_options.go diff --git a/vendor/github.com/xanzy/go-gitlab/resource_group.go b/vendor/gitlab.com/gitlab-org/api/client-go/resource_group.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/resource_group.go rename to vendor/gitlab.com/gitlab-org/api/client-go/resource_group.go diff --git a/vendor/github.com/xanzy/go-gitlab/resource_iteration_events.go b/vendor/gitlab.com/gitlab-org/api/client-go/resource_iteration_events.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/resource_iteration_events.go rename to vendor/gitlab.com/gitlab-org/api/client-go/resource_iteration_events.go diff --git a/vendor/github.com/xanzy/go-gitlab/resource_label_events.go b/vendor/gitlab.com/gitlab-org/api/client-go/resource_label_events.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/resource_label_events.go rename to vendor/gitlab.com/gitlab-org/api/client-go/resource_label_events.go diff --git a/vendor/github.com/xanzy/go-gitlab/resource_milestone_events.go b/vendor/gitlab.com/gitlab-org/api/client-go/resource_milestone_events.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/resource_milestone_events.go rename to vendor/gitlab.com/gitlab-org/api/client-go/resource_milestone_events.go diff --git a/vendor/github.com/xanzy/go-gitlab/resource_state_events.go b/vendor/gitlab.com/gitlab-org/api/client-go/resource_state_events.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/resource_state_events.go rename to vendor/gitlab.com/gitlab-org/api/client-go/resource_state_events.go diff --git a/vendor/github.com/xanzy/go-gitlab/resource_weight_events.go b/vendor/gitlab.com/gitlab-org/api/client-go/resource_weight_events.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/resource_weight_events.go rename to vendor/gitlab.com/gitlab-org/api/client-go/resource_weight_events.go diff --git a/vendor/github.com/xanzy/go-gitlab/runners.go b/vendor/gitlab.com/gitlab-org/api/client-go/runners.go similarity index 93% rename from vendor/github.com/xanzy/go-gitlab/runners.go rename to vendor/gitlab.com/gitlab-org/api/client-go/runners.go index 5224cf91b8..8c255f7927 100644 --- a/vendor/github.com/xanzy/go-gitlab/runners.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/runners.go @@ -52,19 +52,20 @@ type Runner struct { // // GitLab API docs: https://docs.gitlab.com/ee/api/runners.html type RunnerDetails struct { - Paused bool `json:"paused"` - Architecture string `json:"architecture"` - Description string `json:"description"` - ID int `json:"id"` - IPAddress string `json:"ip_address"` - IsShared bool `json:"is_shared"` - RunnerType string `json:"runner_type"` - ContactedAt *time.Time `json:"contacted_at"` - Name string `json:"name"` - Online bool `json:"online"` - Status string `json:"status"` - Platform string `json:"platform"` - Projects []struct { + Paused bool `json:"paused"` + Architecture string `json:"architecture"` + Description string `json:"description"` + ID int `json:"id"` + IPAddress string `json:"ip_address"` + IsShared bool `json:"is_shared"` + RunnerType string `json:"runner_type"` + ContactedAt *time.Time `json:"contacted_at"` + MaintenanceNote string `json:"maintenance_note"` + Name string `json:"name"` + Online bool `json:"online"` + Status string `json:"status"` + Platform string `json:"platform"` + Projects []struct { ID int `json:"id"` Name string `json:"name"` NameWithNamespace string `json:"name_with_namespace"` @@ -173,13 +174,14 @@ func (s *RunnersService) GetRunnerDetails(rid interface{}, options ...RequestOpt // GitLab API docs: // https://docs.gitlab.com/ee/api/runners.html#update-runners-details type UpdateRunnerDetailsOptions struct { - Description *string `url:"description,omitempty" json:"description,omitempty"` - Paused *bool `url:"paused,omitempty" json:"paused,omitempty"` - TagList *[]string `url:"tag_list[],omitempty" json:"tag_list,omitempty"` - RunUntagged *bool `url:"run_untagged,omitempty" json:"run_untagged,omitempty"` - Locked *bool `url:"locked,omitempty" json:"locked,omitempty"` - AccessLevel *string `url:"access_level,omitempty" json:"access_level,omitempty"` - MaximumTimeout *int `url:"maximum_timeout,omitempty" json:"maximum_timeout,omitempty"` + Description *string `url:"description,omitempty" json:"description,omitempty"` + Paused *bool `url:"paused,omitempty" json:"paused,omitempty"` + TagList *[]string `url:"tag_list[],omitempty" json:"tag_list,omitempty"` + RunUntagged *bool `url:"run_untagged,omitempty" json:"run_untagged,omitempty"` + Locked *bool `url:"locked,omitempty" json:"locked,omitempty"` + AccessLevel *string `url:"access_level,omitempty" json:"access_level,omitempty"` + MaximumTimeout *int `url:"maximum_timeout,omitempty" json:"maximum_timeout,omitempty"` + MaintenanceNote *string `url:"maintenance_note,omitempty" json:"maintenance_note,omitempty"` // Deprecated: Use Paused instead. (Deprecated in GitLab 14.8) Active *bool `url:"active,omitempty" json:"active,omitempty"` diff --git a/vendor/github.com/xanzy/go-gitlab/search.go b/vendor/gitlab.com/gitlab-org/api/client-go/search.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/search.go rename to vendor/gitlab.com/gitlab-org/api/client-go/search.go diff --git a/vendor/github.com/xanzy/go-gitlab/services.go b/vendor/gitlab.com/gitlab-org/api/client-go/services.go similarity index 81% rename from vendor/github.com/xanzy/go-gitlab/services.go rename to vendor/gitlab.com/gitlab-org/api/client-go/services.go index fcaa71ecc4..c8ae0c870b 100644 --- a/vendor/github.com/xanzy/go-gitlab/services.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/services.go @@ -36,27 +36,31 @@ type ServicesService struct { // // GitLab API docs: https://docs.gitlab.com/ee/api/integrations.html type Service struct { - ID int `json:"id"` - Title string `json:"title"` - Slug string `json:"slug"` - CreatedAt *time.Time `json:"created_at"` - UpdatedAt *time.Time `json:"updated_at"` - Active bool `json:"active"` - PushEvents bool `json:"push_events"` - IssuesEvents bool `json:"issues_events"` - AlertEvents bool `json:"alert_events"` - ConfidentialIssuesEvents bool `json:"confidential_issues_events"` - CommitEvents bool `json:"commit_events"` - MergeRequestsEvents bool `json:"merge_requests_events"` - CommentOnEventEnabled bool `json:"comment_on_event_enabled"` - TagPushEvents bool `json:"tag_push_events"` - NoteEvents bool `json:"note_events"` - ConfidentialNoteEvents bool `json:"confidential_note_events"` - PipelineEvents bool `json:"pipeline_events"` - JobEvents bool `json:"job_events"` - WikiPageEvents bool `json:"wiki_page_events"` - VulnerabilityEvents bool `json:"vulnerability_events"` - DeploymentEvents bool `json:"deployment_events"` + ID int `json:"id"` + Title string `json:"title"` + Slug string `json:"slug"` + CreatedAt *time.Time `json:"created_at"` + UpdatedAt *time.Time `json:"updated_at"` + Active bool `json:"active"` + AlertEvents bool `json:"alert_events"` + CommitEvents bool `json:"commit_events"` + ConfidentialIssuesEvents bool `json:"confidential_issues_events"` + ConfidentialNoteEvents bool `json:"confidential_note_events"` + DeploymentEvents bool `json:"deployment_events"` + GroupConfidentialMentionEvents bool `json:"group_confidential_mention_events"` + GroupMentionEvents bool `json:"group_mention_events"` + IncidentEvents bool `json:"incident_events"` + IssuesEvents bool `json:"issues_events"` + JobEvents bool `json:"job_events"` + MergeRequestsEvents bool `json:"merge_requests_events"` + NoteEvents bool `json:"note_events"` + PipelineEvents bool `json:"pipeline_events"` + PushEvents bool `json:"push_events"` + TagPushEvents bool `json:"tag_push_events"` + VulnerabilityEvents bool `json:"vulnerability_events"` + WikiPageEvents bool `json:"wiki_page_events"` + CommentOnEventEnabled bool `json:"comment_on_event_enabled"` + Inherited bool `json:"inherited"` } // ListServices gets a list of all active services. @@ -142,19 +146,25 @@ type SetCustomIssueTrackerServiceOptions struct { // // GitLab API docs: // https://docs.gitlab.com/ee/api/integrations.html#set-up-a-custom-issue-tracker -func (s *ServicesService) SetCustomIssueTrackerService(pid interface{}, opt *SetCustomIssueTrackerServiceOptions, options ...RequestOptionFunc) (*Response, error) { +func (s *ServicesService) SetCustomIssueTrackerService(pid interface{}, opt *SetCustomIssueTrackerServiceOptions, options ...RequestOptionFunc) (*CustomIssueTrackerService, *Response, error) { project, err := parseID(pid) if err != nil { - return nil, err + return nil, nil, err } u := fmt.Sprintf("projects/%s/services/custom-issue-tracker", PathEscape(project)) req, err := s.client.NewRequest(http.MethodPut, u, opt, options) if err != nil { - return nil, err + return nil, nil, err } - return s.client.Do(req, nil) + svc := new(CustomIssueTrackerService) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, nil, err + } + + return svc, resp, nil } // DeleteCustomIssueTrackerService deletes Custom Issue Tracker service settings for a project. @@ -242,19 +252,25 @@ type SetDataDogServiceOptions struct { // // GitLab API docs: // https://docs.gitlab.com/ee/api/integrations.html#set-up-datadog -func (s *ServicesService) SetDataDogService(pid interface{}, opt *SetDataDogServiceOptions, options ...RequestOptionFunc) (*Response, error) { +func (s *ServicesService) SetDataDogService(pid interface{}, opt *SetDataDogServiceOptions, options ...RequestOptionFunc) (*DataDogService, *Response, error) { project, err := parseID(pid) if err != nil { - return nil, err + return nil, nil, err } u := fmt.Sprintf("projects/%s/services/datadog", PathEscape(project)) req, err := s.client.NewRequest(http.MethodPut, u, opt, options) if err != nil { - return nil, err + return nil, nil, err } - return s.client.Do(req, nil) + svc := new(DataDogService) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, nil, err + } + + return svc, resp, nil } // DeleteDataDogService deletes the DataDog service settings for a project. @@ -358,19 +374,25 @@ type SetDiscordServiceOptions struct { // // GitLab API docs: // https://docs.gitlab.com/ee/api/integrations.html#set-up-discord-notifications -func (s *ServicesService) SetDiscordService(pid interface{}, opt *SetDiscordServiceOptions, options ...RequestOptionFunc) (*Response, error) { +func (s *ServicesService) SetDiscordService(pid interface{}, opt *SetDiscordServiceOptions, options ...RequestOptionFunc) (*DiscordService, *Response, error) { project, err := parseID(pid) if err != nil { - return nil, err + return nil, nil, err } u := fmt.Sprintf("projects/%s/services/discord", PathEscape(project)) req, err := s.client.NewRequest(http.MethodPut, u, opt, options) if err != nil { - return nil, err + return nil, nil, err } - return s.client.Do(req, nil) + svc := new(DiscordService) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, resp, err + } + + return svc, resp, nil } // DeleteDiscordService deletes Discord service settings for a project. @@ -453,19 +475,25 @@ type SetDroneCIServiceOptions struct { // // GitLab API docs: // https://docs.gitlab.com/ee/api/integrations.html#set-up-drone -func (s *ServicesService) SetDroneCIService(pid interface{}, opt *SetDroneCIServiceOptions, options ...RequestOptionFunc) (*Response, error) { +func (s *ServicesService) SetDroneCIService(pid interface{}, opt *SetDroneCIServiceOptions, options ...RequestOptionFunc) (*DroneCIService, *Response, error) { project, err := parseID(pid) if err != nil { - return nil, err + return nil, nil, err } u := fmt.Sprintf("projects/%s/services/drone-ci", PathEscape(project)) req, err := s.client.NewRequest(http.MethodPut, u, opt, options) if err != nil { - return nil, err + return nil, nil, err } - return s.client.Do(req, nil) + svc := new(DroneCIService) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, nil, err + } + + return svc, resp, nil } // DeleteDroneCIService deletes Drone CI service settings for a project. @@ -552,19 +580,25 @@ type SetEmailsOnPushServiceOptions struct { // // GitLab API docs: // https://docs.gitlab.com/ee/api/integrations.html#set-up-emails-on-push -func (s *ServicesService) SetEmailsOnPushService(pid interface{}, opt *SetEmailsOnPushServiceOptions, options ...RequestOptionFunc) (*Response, error) { +func (s *ServicesService) SetEmailsOnPushService(pid interface{}, opt *SetEmailsOnPushServiceOptions, options ...RequestOptionFunc) (*EmailsOnPushService, *Response, error) { project, err := parseID(pid) if err != nil { - return nil, err + return nil, nil, err } u := fmt.Sprintf("projects/%s/integrations/emails-on-push", PathEscape(project)) req, err := s.client.NewRequest(http.MethodPut, u, opt, options) if err != nil { - return nil, err + return nil, nil, err } - return s.client.Do(req, nil) + svc := new(EmailsOnPushService) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, nil, err + } + + return svc, resp, nil } // DeleteEmailsOnPushService deletes Emails on Push service settings for a project. @@ -641,19 +675,25 @@ type SetExternalWikiServiceOptions struct { // // GitLab API docs: // https://docs.gitlab.com/ee/api/integrations.html#set-up-an-external-wiki -func (s *ServicesService) SetExternalWikiService(pid interface{}, opt *SetExternalWikiServiceOptions, options ...RequestOptionFunc) (*Response, error) { +func (s *ServicesService) SetExternalWikiService(pid interface{}, opt *SetExternalWikiServiceOptions, options ...RequestOptionFunc) (*ExternalWikiService, *Response, error) { project, err := parseID(pid) if err != nil { - return nil, err + return nil, nil, err } u := fmt.Sprintf("projects/%s/services/external-wiki", PathEscape(project)) req, err := s.client.NewRequest(http.MethodPut, u, opt, options) if err != nil { - return nil, err + return nil, nil, err } - return s.client.Do(req, nil) + svc := new(ExternalWikiService) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, nil, err + } + + return svc, resp, nil } // DeleteExternalWikiService deletes External Wiki service for project. @@ -733,19 +773,25 @@ type SetGithubServiceOptions struct { // // GitLab API docs: // https://docs.gitlab.com/ee/api/integrations.html#set-up-github -func (s *ServicesService) SetGithubService(pid interface{}, opt *SetGithubServiceOptions, options ...RequestOptionFunc) (*Response, error) { +func (s *ServicesService) SetGithubService(pid interface{}, opt *SetGithubServiceOptions, options ...RequestOptionFunc) (*GithubService, *Response, error) { project, err := parseID(pid) if err != nil { - return nil, err + return nil, nil, err } u := fmt.Sprintf("projects/%s/services/github", PathEscape(project)) req, err := s.client.NewRequest(http.MethodPut, u, opt, options) if err != nil { - return nil, err + return nil, nil, err } - return s.client.Do(req, nil) + svc := new(GithubService) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, nil, err + } + + return svc, resp, nil } // DeleteGithubService deletes Github service for a project @@ -767,6 +813,109 @@ func (s *ServicesService) DeleteGithubService(pid interface{}, options ...Reques return s.client.Do(req, nil) } +// HarborService represents the Harbor service settings. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/integrations.html#harbor +type HarborService struct { + Service + Properties *HarborServiceProperties `json:"properties"` +} + +// HarborServiceProperties represents Harbor specific properties. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/integrations.html#harbor +type HarborServiceProperties struct { + URL string `json:"url"` + ProjectName string `json:"project_name"` + Username string `json:"username"` + Password string `json:"password"` + UseInheritedSettings bool `json:"use_inherited_settings"` +} + +// GetHarborService gets Harbor service settings for a project. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/integrations.html#get-harbor-settings +func (s *ServicesService) GetHarborService(pid interface{}, options ...RequestOptionFunc) (*HarborService, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/integrations/harbor", PathEscape(project)) + + req, err := s.client.NewRequest(http.MethodGet, u, nil, options) + if err != nil { + return nil, nil, err + } + + svc := new(HarborService) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, resp, err + } + + return svc, resp, nil +} + +// SetHarborServiceOptions represents the available SetHarborService() +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/integrations.html#set-up-harbor +type SetHarborServiceOptions struct { + URL *string `url:"url,omitempty" json:"url,omitempty"` + ProjectName *string `url:"project_name,omitempty" json:"project_name,omitempty"` + Username *string `url:"username,omitempty" json:"username,omitempty"` + Password *string `url:"password,omitempty" json:"password,omitempty"` + UseInheritedSettings *bool `url:"use_inherited_settings,omitempty" json:"use_inherited_settings,omitempty"` +} + +// SetHarborService sets Harbor service for a project. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/integrations.html#set-up-harbor +func (s *ServicesService) SetHarborService(pid interface{}, opt *SetHarborServiceOptions, options ...RequestOptionFunc) (*HarborService, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/integrations/harbor", PathEscape(project)) + + req, err := s.client.NewRequest(http.MethodPut, u, opt, options) + if err != nil { + return nil, nil, err + } + + svc := new(HarborService) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, nil, err + } + + return svc, resp, nil +} + +// DeleteHarborService deletes Harbor service for a project. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/integrations.html#disable-harbor +func (s *ServicesService) DeleteHarborService(pid interface{}, options ...RequestOptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/integrations/harbor", PathEscape(project)) + + req, err := s.client.NewRequest(http.MethodDelete, u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + // SlackApplication represents GitLab for slack application settings. // // GitLab API docs: @@ -781,22 +930,24 @@ type SlackApplication struct { // GitLab API docs: // https://docs.gitlab.com/ee/api/integrations.html#gitlab-for-slack-app type SlackApplicationProperties struct { - Channel string `json:"channel"` - NotifyOnlyBrokenPipelines bool `json:"notify_only_broken_pipelines"` - BranchesToBeNotified string `json:"branches_to_be_notified"` - AlertEvents bool `json:"alert_events"` - IssuesEvents bool `json:"issues_events"` - ConfidentialIssuesEvents bool `json:"confidential_issues_events"` - MergeRequestsEvents bool `json:"merge_requests_events"` - NoteEvents bool `json:"note_events"` - ConfidentialNoteEvents bool `json:"confidential_note_events"` - DeploymentEvents bool `json:"deployment_events"` - IncidentsEvents bool `json:"incidents_events"` - PipelineEvents bool `json:"pipeline_events"` - PushEvents bool `json:"push_events"` - TagPushEvents bool `json:"tag_push_events"` - VulnerabilityEvents bool `json:"vulnerability_events"` - WikiPageEvents bool `json:"wiki_page_events"` + Channel string `json:"channel"` + NotifyOnlyBrokenPipelines bool `json:"notify_only_broken_pipelines"` + BranchesToBeNotified string `json:"branches_to_be_notified"` + LabelsToBeNotified string `json:"labels_to_be_notified"` + LabelsToBeNotifiedBehavior string `json:"labels_to_be_notified_behavior"` + PushChannel string `json:"push_channel"` + IssueChannel string `json:"issue_channel"` + ConfidentialIssueChannel string `json:"confidential_issue_channel"` + MergeRequestChannel string `json:"merge_request_channel"` + NoteChannel string `json:"note_channel"` + ConfidentialNoteChannel string `json:"confidential_note_channel"` + TagPushChannel string `json:"tag_push_channel"` + PipelineChannel string `json:"pipeline_channel"` + WikiPageChannel string `json:"wiki_page_channel"` + DeploymentChannel string `json:"deployment_channel"` + IncidentChannel string `json:"incident_channel"` + VulnerabilityChannel string `json:"vulnerability_channel"` + AlertChannel string `json:"alert_channel"` // Deprecated: This parameter has been replaced with BranchesToBeNotified. NotifyOnlyDefaultBranch bool `json:"notify_only_default_branch"` @@ -834,22 +985,38 @@ func (s *ServicesService) GetSlackApplication(pid interface{}, options ...Reques // GitLab API docs: // https://docs.gitlab.com/ee/api/integrations.html#set-up-gitlab-for-slack-app type SetSlackApplicationOptions struct { - Channel *string `url:"channel,omitempty" json:"channel,omitempty"` - NotifyOnlyBrokenPipelines *bool `url:"notify_only_broken_pipelines,omitempty" json:"notify_only_broken_pipelines,omitempty"` - BranchesToBeNotified *string `url:"branches_to_be_notified,omitempty" json:"branches_to_be_notified,omitempty"` - AlertEvents *bool `url:"alert_events,omitempty" json:"alert_events,omitempty"` - IssuesEvents *bool `url:"issues_events,omitempty" json:"issues_events,omitempty"` - ConfidentialIssuesEvents *bool `url:"confidential_issues_events,omitempty" json:"confidential_issues_events,omitempty"` - MergeRequestsEvents *bool `url:"merge_requests_events,omitempty" json:"merge_requests_events,omitempty"` - NoteEvents *bool `url:"note_events,omitempty" json:"note_events,omitempty"` - ConfidentialNoteEvents *bool `url:"confidential_note_events,omitempty" json:"confidential_note_events,omitempty"` - DeploymentEvents *bool `url:"deployment_events,omitempty" json:"deployment_events,omitempty"` - IncidentsEvents *bool `url:"incidents_events,omitempty" json:"incidents_events,omitempty"` - PipelineEvents *bool `url:"pipeline_events,omitempty" json:"pipeline_events,omitempty"` - PushEvents *bool `url:"push_events,omitempty" json:"push_events,omitempty"` - TagPushEvents *bool `url:"tag_push_events,omitempty" json:"tag_push_events,omitempty"` - VulnerabilityEvents *bool `url:"vulnerability_events,omitempty" json:"vulnerability_events,omitempty"` - WikiPageEvents *bool `url:"wiki_page_events,omitempty" json:"wiki_page_events,omitempty"` + Channel *string `url:"channel,omitempty" json:"channel,omitempty"` + NotifyOnlyBrokenPipelines *bool `url:"notify_only_broken_pipelines,omitempty" json:"notify_only_broken_pipelines,omitempty"` + BranchesToBeNotified *string `url:"branches_to_be_notified,omitempty" json:"branches_to_be_notified,omitempty"` + AlertEvents *bool `url:"alert_events,omitempty" json:"alert_events,omitempty"` + IssuesEvents *bool `url:"issues_events,omitempty" json:"issues_events,omitempty"` + ConfidentialIssuesEvents *bool `url:"confidential_issues_events,omitempty" json:"confidential_issues_events,omitempty"` + MergeRequestsEvents *bool `url:"merge_requests_events,omitempty" json:"merge_requests_events,omitempty"` + NoteEvents *bool `url:"note_events,omitempty" json:"note_events,omitempty"` + ConfidentialNoteEvents *bool `url:"confidential_note_events,omitempty" json:"confidential_note_events,omitempty"` + DeploymentEvents *bool `url:"deployment_events,omitempty" json:"deployment_events,omitempty"` + IncidentsEvents *bool `url:"incidents_events,omitempty" json:"incidents_events,omitempty"` + PipelineEvents *bool `url:"pipeline_events,omitempty" json:"pipeline_events,omitempty"` + PushEvents *bool `url:"push_events,omitempty" json:"push_events,omitempty"` + TagPushEvents *bool `url:"tag_push_events,omitempty" json:"tag_push_events,omitempty"` + VulnerabilityEvents *bool `url:"vulnerability_events,omitempty" json:"vulnerability_events,omitempty"` + WikiPageEvents *bool `url:"wiki_page_events,omitempty" json:"wiki_page_events,omitempty"` + LabelsToBeNotified *string `url:"labels_to_be_notified,omitempty" json:"labels_to_be_notified,omitempty"` + LabelsToBeNotifiedBehavior *string `url:"labels_to_be_notified_behavior,omitempty" json:"labels_to_be_notified_behavior,omitempty"` + PushChannel *string `url:"push_channel,omitempty" json:"push_channel,omitempty"` + IssueChannel *string `url:"issue_channel,omitempty" json:"issue_channel,omitempty"` + ConfidentialIssueChannel *string `url:"confidential_issue_channel,omitempty" json:"confidential_issue_channel,omitempty"` + MergeRequestChannel *string `url:"merge_request_channel,omitempty" json:"merge_request_channel,omitempty"` + NoteChannel *string `url:"note_channel,omitempty" json:"note_channel,omitempty"` + ConfidentialNoteChannel *string `url:"confidential_note_channel,omitempty" json:"confidential_note_channel,omitempty"` + TagPushChannel *string `url:"tag_push_channel,omitempty" json:"tag_push_channel,omitempty"` + PipelineChannel *string `url:"pipeline_channel,omitempty" json:"pipeline_channel,omitempty"` + WikiPageChannel *string `url:"wiki_page_channel,omitempty" json:"wiki_page_channel,omitempty"` + DeploymentChannel *string `url:"deployment_channel,omitempty" json:"deployment_channel,omitempty"` + IncidentChannel *string `url:"incident_channel,omitempty" json:"incident_channel,omitempty"` + VulnerabilityChannel *string `url:"vulnerability_channel,omitempty" json:"vulnerability_channel,omitempty"` + AlertChannel *string `url:"alert_channel,omitempty" json:"alert_channel,omitempty"` + UseInheritedSettings *bool `url:"use_inherited_settings,omitempty" json:"use_inherited_settings,omitempty"` // Deprecated: This parameter has been replaced with BranchesToBeNotified. NotifyOnlyDefaultBranch *bool `url:"notify_only_default_branch,omitempty" json:"notify_only_default_branch,omitempty"` @@ -859,19 +1026,25 @@ type SetSlackApplicationOptions struct { // // GitLab API docs: // https://docs.gitlab.com/ee/api/integrations.html#set-up-gitlab-for-slack-app -func (s *ServicesService) SetSlackApplication(pid interface{}, opt *SetSlackApplicationOptions, options ...RequestOptionFunc) (*Response, error) { +func (s *ServicesService) SetSlackApplication(pid interface{}, opt *SetSlackApplicationOptions, options ...RequestOptionFunc) (*SlackApplication, *Response, error) { project, err := parseID(pid) if err != nil { - return nil, err + return nil, nil, err } u := fmt.Sprintf("projects/%s/integrations/gitlab-slack-application", PathEscape(project)) req, err := s.client.NewRequest(http.MethodPut, u, opt, options) if err != nil { - return nil, err + return nil, nil, err } - return s.client.Do(req, nil) + svc := new(SlackApplication) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, nil, err + } + + return svc, resp, nil } // DisableSlackApplication disable the GitLab for Slack app integration for a project. @@ -1054,19 +1227,25 @@ type SetJenkinsCIServiceOptions struct { // // GitLab API docs: // https://docs.gitlab.com/ee/api/integrations.html#set-up-jenkins -func (s *ServicesService) SetJenkinsCIService(pid interface{}, opt *SetJenkinsCIServiceOptions, options ...RequestOptionFunc) (*Response, error) { +func (s *ServicesService) SetJenkinsCIService(pid interface{}, opt *SetJenkinsCIServiceOptions, options ...RequestOptionFunc) (*JenkinsCIService, *Response, error) { project, err := parseID(pid) if err != nil { - return nil, err + return nil, nil, err } u := fmt.Sprintf("projects/%s/services/jenkins", PathEscape(project)) req, err := s.client.NewRequest(http.MethodPut, u, opt, options) if err != nil { - return nil, err + return nil, nil, err } - return s.client.Do(req, nil) + svc := new(JenkinsCIService) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, nil, err + } + + return svc, resp, nil } // DeleteJenkinsCIService deletes Jenkins CI service for project. @@ -1209,19 +1388,25 @@ type SetJiraServiceOptions struct { // // GitLab API docs: // https://docs.gitlab.com/ee/api/integrations.html#edit-jira-service -func (s *ServicesService) SetJiraService(pid interface{}, opt *SetJiraServiceOptions, options ...RequestOptionFunc) (*Response, error) { +func (s *ServicesService) SetJiraService(pid interface{}, opt *SetJiraServiceOptions, options ...RequestOptionFunc) (*JiraService, *Response, error) { project, err := parseID(pid) if err != nil { - return nil, err + return nil, nil, err } u := fmt.Sprintf("projects/%s/integrations/jira", PathEscape(project)) req, err := s.client.NewRequest(http.MethodPut, u, opt, options) if err != nil { - return nil, err + return nil, nil, err } - return s.client.Do(req, nil) + svc := new(JiraService) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, nil, err + } + + return svc, resp, nil } // DeleteJiraService deletes Jira service for project. @@ -1330,6 +1515,50 @@ type SetMattermostServiceOptions struct { WikiPageChannel *string `url:"wiki_page_channel,omitempty" json:"wiki_page_channel,omitempty"` } +// SetMattermostService sets Mattermost service for a project. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/integrations.html#createedit-mattermost-notifications-service +func (s *ServicesService) SetMattermostService(pid interface{}, opt *SetMattermostServiceOptions, options ...RequestOptionFunc) (*MattermostService, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/services/mattermost", PathEscape(project)) + + req, err := s.client.NewRequest(http.MethodPut, u, opt, options) + if err != nil { + return nil, nil, err + } + + svc := new(MattermostService) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, nil, err + } + + return svc, resp, nil +} + +// DeleteMattermostService deletes Mattermost service for project. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/integrations.html#delete-mattermost-notifications-service +func (s *ServicesService) DeleteMattermostService(pid interface{}, options ...RequestOptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/services/mattermost", PathEscape(project)) + + req, err := s.client.NewRequest(http.MethodDelete, u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + // MattermostSlashCommandsService represents Mattermost slash commands settings. // // GitLab API docs: @@ -1387,19 +1616,25 @@ type SetMattermostSlashCommandsServiceOptions struct { // // GitLab API docs: // https://docs.gitlab.com/ee/api/integrations.html#createedit-mattermost-slash-command-integration -func (s *ServicesService) SetMattermostSlashCommandsService(pid interface{}, opt *SetMattermostSlashCommandsServiceOptions, options ...RequestOptionFunc) (*Response, error) { +func (s *ServicesService) SetMattermostSlashCommandsService(pid interface{}, opt *SetMattermostSlashCommandsServiceOptions, options ...RequestOptionFunc) (*MattermostSlashCommandsService, *Response, error) { project, err := parseID(pid) if err != nil { - return nil, err + return nil, nil, err } u := fmt.Sprintf("projects/%s/services/mattermost-slash-commands", PathEscape(project)) req, err := s.client.NewRequest(http.MethodPut, u, opt, options) if err != nil { - return nil, err + return nil, nil, err } - return s.client.Do(req, nil) + svc := new(MattermostSlashCommandsService) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, nil, err + } + + return svc, resp, nil } // DeleteMattermostSlashCommandsService deletes Mattermost slash commands service for project. @@ -1421,44 +1656,6 @@ func (s *ServicesService) DeleteMattermostSlashCommandsService(pid interface{}, return s.client.Do(req, nil) } -// SetMattermostService sets Mattermost service for a project. -// -// GitLab API docs: -// https://docs.gitlab.com/ee/api/integrations.html#createedit-mattermost-notifications-service -func (s *ServicesService) SetMattermostService(pid interface{}, opt *SetMattermostServiceOptions, options ...RequestOptionFunc) (*Response, error) { - project, err := parseID(pid) - if err != nil { - return nil, err - } - u := fmt.Sprintf("projects/%s/services/mattermost", PathEscape(project)) - - req, err := s.client.NewRequest(http.MethodPut, u, opt, options) - if err != nil { - return nil, err - } - - return s.client.Do(req, nil) -} - -// DeleteMattermostService deletes Mattermost service for project. -// -// GitLab API docs: -// https://docs.gitlab.com/ee/api/integrations.html#delete-mattermost-notifications-service -func (s *ServicesService) DeleteMattermostService(pid interface{}, options ...RequestOptionFunc) (*Response, error) { - project, err := parseID(pid) - if err != nil { - return nil, err - } - u := fmt.Sprintf("projects/%s/services/mattermost", PathEscape(project)) - - req, err := s.client.NewRequest(http.MethodDelete, u, nil, options) - if err != nil { - return nil, err - } - - return s.client.Do(req, nil) -} - // MicrosoftTeamsService represents Microsoft Teams service settings. // // GitLab API docs: @@ -1535,18 +1732,25 @@ type SetMicrosoftTeamsServiceOptions struct { // // GitLab API docs: // https://docs.gitlab.com/ee/api/integrations.html#create-edit-microsoft-teams-service -func (s *ServicesService) SetMicrosoftTeamsService(pid interface{}, opt *SetMicrosoftTeamsServiceOptions, options ...RequestOptionFunc) (*Response, error) { +func (s *ServicesService) SetMicrosoftTeamsService(pid interface{}, opt *SetMicrosoftTeamsServiceOptions, options ...RequestOptionFunc) (*MicrosoftTeamsService, *Response, error) { project, err := parseID(pid) if err != nil { - return nil, err + return nil, nil, err } u := fmt.Sprintf("projects/%s/services/microsoft-teams", PathEscape(project)) req, err := s.client.NewRequest(http.MethodPut, u, opt, options) if err != nil { - return nil, err + return nil, nil, err } - return s.client.Do(req, nil) + + svc := new(MicrosoftTeamsService) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, nil, err + } + + return svc, resp, nil } // DeleteMicrosoftTeamsService deletes Microsoft Teams service for project. @@ -1631,19 +1835,25 @@ type SetPipelinesEmailServiceOptions struct { // // GitLab API docs: // https://docs.gitlab.com/ee/api/integrations.html#pipeline-emails -func (s *ServicesService) SetPipelinesEmailService(pid interface{}, opt *SetPipelinesEmailServiceOptions, options ...RequestOptionFunc) (*Response, error) { +func (s *ServicesService) SetPipelinesEmailService(pid interface{}, opt *SetPipelinesEmailServiceOptions, options ...RequestOptionFunc) (*PipelinesEmailService, *Response, error) { project, err := parseID(pid) if err != nil { - return nil, err + return nil, nil, err } u := fmt.Sprintf("projects/%s/services/pipelines-email", PathEscape(project)) req, err := s.client.NewRequest(http.MethodPut, u, opt, options) if err != nil { - return nil, err + return nil, nil, err } - return s.client.Do(req, nil) + svc := new(PipelinesEmailService) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, nil, err + } + + return svc, resp, nil } // DeletePipelinesEmailService deletes Pipelines Email service settings for a project. @@ -1724,19 +1934,25 @@ type SetPrometheusServiceOptions struct { // // GitLab API docs: // https://docs.gitlab.com/ee/api/integrations.html#createedit-prometheus-service -func (s *ServicesService) SetPrometheusService(pid interface{}, opt *SetPrometheusServiceOptions, options ...RequestOptionFunc) (*Response, error) { +func (s *ServicesService) SetPrometheusService(pid interface{}, opt *SetPrometheusServiceOptions, options ...RequestOptionFunc) (*PrometheusService, *Response, error) { project, err := parseID(pid) if err != nil { - return nil, err + return nil, nil, err } u := fmt.Sprintf("projects/%s/services/prometheus", PathEscape(project)) req, err := s.client.NewRequest(http.MethodPut, u, opt, options) if err != nil { - return nil, err + return nil, nil, err } - return s.client.Do(req, nil) + svc := new(PrometheusService) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, nil, err + } + + return svc, resp, nil } // DeletePrometheusService deletes Prometheus service settings for a project. @@ -1758,6 +1974,107 @@ func (s *ServicesService) DeletePrometheusService(pid interface{}, options ...Re return s.client.Do(req, nil) } +// RedmineService represents the Redmine service settings. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/integrations.html#redmine +type RedmineService struct { + Service + Properties *RedmineServiceProperties `json:"properties"` +} + +// RedmineServiceProperties represents Redmine specific properties. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/integrations.html#redmine +type RedmineServiceProperties struct { + NewIssueURL string `json:"new_issue_url"` + ProjectURL string `json:"project_url"` + IssuesURL string `json:"issues_url"` + UseInheritedSettings BoolValue `json:"use_inherited_settings"` +} + +// GetRedmineService gets Redmine service settings for a project. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/integrations.html#get-redmine-settings +func (s *ServicesService) GetRedmineService(pid interface{}, options ...RequestOptionFunc) (*RedmineService, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/integrations/redmine", PathEscape(project)) + + req, err := s.client.NewRequest(http.MethodGet, u, nil, options) + if err != nil { + return nil, nil, err + } + + svc := new(RedmineService) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, resp, err + } + + return svc, resp, nil +} + +// SetRedmineServiceOptions represents the available SetRedmineService(). +// options. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/integrations.html#set-up-redmine +type SetRedmineServiceOptions struct { + NewIssueURL *string `url:"new_issue_url,omitempty" json:"new_issue_url,omitempty"` + ProjectURL *string `url:"project_url,omitempty" json:"project_url,omitempty"` + IssuesURL *string `url:"issues_url,omitempty" json:"issues_url,omitempty"` + UseInheritedSettings *bool `url:"use_inherited_settings,omitempty" json:"use_inherited_settings,omitempty"` +} + +// SetRedmineService sets Redmine service for a project. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/integrations.html#set-up-redmine +func (s *ServicesService) SetRedmineService(pid interface{}, opt *SetRedmineServiceOptions, options ...RequestOptionFunc) (*RedmineService, *Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, nil, err + } + u := fmt.Sprintf("projects/%s/integrations/redmine", PathEscape(project)) + + req, err := s.client.NewRequest(http.MethodPut, u, opt, options) + if err != nil { + return nil, nil, err + } + + svc := new(RedmineService) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, nil, err + } + + return svc, resp, nil +} + +// DeleteRedmineService deletes Redmine service for project. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/integrations.html#disable-redmine +func (s *ServicesService) DeleteRedmineService(pid interface{}, options ...RequestOptionFunc) (*Response, error) { + project, err := parseID(pid) + if err != nil { + return nil, err + } + u := fmt.Sprintf("projects/%s/integrations/redmine", PathEscape(project)) + + req, err := s.client.NewRequest(http.MethodDelete, u, nil, options) + if err != nil { + return nil, err + } + + return s.client.Do(req, nil) +} + // SlackService represents Slack service settings. // // GitLab API docs: @@ -1857,19 +2174,25 @@ type SetSlackServiceOptions struct { // // GitLab API docs: // https://docs.gitlab.com/ee/api/integrations.html#edit-slack-service -func (s *ServicesService) SetSlackService(pid interface{}, opt *SetSlackServiceOptions, options ...RequestOptionFunc) (*Response, error) { +func (s *ServicesService) SetSlackService(pid interface{}, opt *SetSlackServiceOptions, options ...RequestOptionFunc) (*SlackService, *Response, error) { project, err := parseID(pid) if err != nil { - return nil, err + return nil, nil, err } u := fmt.Sprintf("projects/%s/services/slack", PathEscape(project)) req, err := s.client.NewRequest(http.MethodPut, u, opt, options) if err != nil { - return nil, err + return nil, nil, err } - return s.client.Do(req, nil) + svc := new(SlackService) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, nil, err + } + + return svc, resp, nil } // DeleteSlackService deletes Slack service for project. @@ -1946,19 +2269,25 @@ type SetSlackSlashCommandsServiceOptions struct { // // GitLab API docs: // https://docs.gitlab.com/13.12/ee/api/integrations.html#createedit-slack-slash-command-service -func (s *ServicesService) SetSlackSlashCommandsService(pid interface{}, opt *SetSlackSlashCommandsServiceOptions, options ...RequestOptionFunc) (*Response, error) { +func (s *ServicesService) SetSlackSlashCommandsService(pid interface{}, opt *SetSlackSlashCommandsServiceOptions, options ...RequestOptionFunc) (*SlackSlashCommandsService, *Response, error) { project, err := parseID(pid) if err != nil { - return nil, err + return nil, nil, err } u := fmt.Sprintf("projects/%s/services/slack-slash-commands", PathEscape(project)) req, err := s.client.NewRequest(http.MethodPut, u, opt, options) if err != nil { - return nil, err + return nil, nil, err } - return s.client.Do(req, nil) + svc := new(SlackSlashCommandsService) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, nil, err + } + + return svc, resp, nil } // DeleteSlackSlashCommandsService deletes Slack slash commands service for project. @@ -2049,19 +2378,25 @@ type SetTelegramServiceOptions struct { // // GitLab API docs: // https://docs.gitlab.com/ee/api/integrations.html#set-up-telegram -func (s *ServicesService) SetTelegramService(pid interface{}, opt *SetTelegramServiceOptions, options ...RequestOptionFunc) (*Response, error) { +func (s *ServicesService) SetTelegramService(pid interface{}, opt *SetTelegramServiceOptions, options ...RequestOptionFunc) (*TelegramService, *Response, error) { project, err := parseID(pid) if err != nil { - return nil, err + return nil, nil, err } u := fmt.Sprintf("projects/%s/services/telegram", PathEscape(project)) req, err := s.client.NewRequest(http.MethodPut, u, opt, options) if err != nil { - return nil, err + return nil, nil, err } - return s.client.Do(req, nil) + svc := new(TelegramService) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, nil, err + } + + return svc, resp, nil } // DeleteTelegramService deletes Telegram service for project. @@ -2144,19 +2479,25 @@ type SetYouTrackServiceOptions struct { // // GitLab API docs: // https://docs.gitlab.com/ee/api/integrations.html#createedit-youtrack-service -func (s *ServicesService) SetYouTrackService(pid interface{}, opt *SetYouTrackServiceOptions, options ...RequestOptionFunc) (*Response, error) { +func (s *ServicesService) SetYouTrackService(pid interface{}, opt *SetYouTrackServiceOptions, options ...RequestOptionFunc) (*YouTrackService, *Response, error) { project, err := parseID(pid) if err != nil { - return nil, err + return nil, nil, err } u := fmt.Sprintf("projects/%s/services/youtrack", PathEscape(project)) + svc := new(YouTrackService) req, err := s.client.NewRequest(http.MethodPut, u, opt, options) if err != nil { - return nil, err + return nil, nil, err } - return s.client.Do(req, nil) + resp, err := s.client.Do(req, svc) + if err != nil { + return nil, nil, err + } + + return svc, resp, nil } // DeleteYouTrackService deletes YouTrack service settings for a project. diff --git a/vendor/gitlab.com/gitlab-org/api/client-go/settings.go b/vendor/gitlab.com/gitlab-org/api/client-go/settings.go new file mode 100644 index 0000000000..0b8c08378b --- /dev/null +++ b/vendor/gitlab.com/gitlab-org/api/client-go/settings.go @@ -0,0 +1,954 @@ +// +// Copyright 2021, Sander van Harmelen +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package gitlab + +import ( + "encoding/json" + "net/http" + "time" +) + +// SettingsService handles communication with the application SettingsService +// related methods of the GitLab API. +// +// GitLab API docs: https://docs.gitlab.com/ee/api/settings.html +type SettingsService struct { + client *Client +} + +// Settings represents the GitLab application settings. +// +// GitLab API docs: https://docs.gitlab.com/ee/api/settings.html +// +// The available parameters have been modeled directly after the code, as the +// documentation seems to be inaccurate. +// +// https://gitlab.com/gitlab-org/gitlab/-/blob/v14.9.3-ee/lib/api/settings.rb +// https://gitlab.com/gitlab-org/gitlab/-/blob/v14.9.3-ee/lib/api/entities/application_setting.rb#L5 +// https://gitlab.com/gitlab-org/gitlab/-/blob/v14.9.3-ee/app/helpers/application_settings_helper.rb#L192 +// https://gitlab.com/gitlab-org/gitlab/-/blob/v14.9.3-ee/ee/lib/ee/api/helpers/settings_helpers.rb#L10 +// https://gitlab.com/gitlab-org/gitlab/-/blob/v14.9.3-ee/ee/app/helpers/ee/application_settings_helper.rb#L20 +type Settings struct { + ID int `json:"id"` + AbuseNotificationEmail string `json:"abuse_notification_email"` + AdminMode bool `json:"admin_mode"` + AfterSignOutPath string `json:"after_sign_out_path"` + AfterSignUpText string `json:"after_sign_up_text"` + AkismetAPIKey string `json:"akismet_api_key"` + AkismetEnabled bool `json:"akismet_enabled"` + AllowAccountDeletion bool `json:"allow_account_deletion"` + AllowGroupOwnersToManageLDAP bool `json:"allow_group_owners_to_manage_ldap"` + AllowLocalRequestsFromSystemHooks bool `json:"allow_local_requests_from_system_hooks"` + AllowLocalRequestsFromWebHooksAndServices bool `json:"allow_local_requests_from_web_hooks_and_services"` + AllowProjectCreationForGuestAndBelow bool `json:"allow_project_creation_for_guest_and_below"` + AllowRunnerRegistrationToken bool `json:"allow_runner_registration_token"` + ArchiveBuildsInHumanReadable string `json:"archive_builds_in_human_readable"` + ASCIIDocMaxIncludes int `json:"asciidoc_max_includes"` + AssetProxyAllowlist []string `json:"asset_proxy_allowlist"` + AssetProxyEnabled bool `json:"asset_proxy_enabled"` + AssetProxyURL string `json:"asset_proxy_url"` + AssetProxySecretKey string `json:"asset_proxy_secret_key"` + AuthorizedKeysEnabled bool `json:"authorized_keys_enabled"` + AutoBanUserOnExcessiveProjectsDownload bool `json:"auto_ban_user_on_excessive_projects_download"` + AutoDevOpsDomain string `json:"auto_devops_domain"` + AutoDevOpsEnabled bool `json:"auto_devops_enabled"` + AutomaticPurchasedStorageAllocation bool `json:"automatic_purchased_storage_allocation"` + BulkImportConcurrentPipelineBatchLimit int `json:"bulk_import_concurrent_pipeline_batch_limit"` + BulkImportEnabled bool `json:"bulk_import_enabled"` + BulkImportMaxDownloadFileSize int `json:"bulk_import_max_download_file_size"` + CanCreateGroup bool `json:"can_create_group"` + CheckNamespacePlan bool `json:"check_namespace_plan"` + CIMaxIncludes int `json:"ci_max_includes"` + CIMaxTotalYAMLSizeBytes int `json:"ci_max_total_yaml_size_bytes"` + CommitEmailHostname string `json:"commit_email_hostname"` + ConcurrentBitbucketImportJobsLimit int `json:"concurrent_bitbucket_import_jobs_limit"` + ConcurrentBitbucketServerImportJobsLimit int `json:"concurrent_bitbucket_server_import_jobs_limit"` + ConcurrentGitHubImportJobsLimit int `json:"concurrent_github_import_jobs_limit"` + ContainerExpirationPoliciesEnableHistoricEntries bool `json:"container_expiration_policies_enable_historic_entries"` + ContainerRegistryCleanupTagsServiceMaxListSize int `json:"container_registry_cleanup_tags_service_max_list_size"` + ContainerRegistryDeleteTagsServiceTimeout int `json:"container_registry_delete_tags_service_timeout"` + ContainerRegistryExpirationPoliciesCaching bool `json:"container_registry_expiration_policies_caching"` + ContainerRegistryExpirationPoliciesWorkerCapacity int `json:"container_registry_expiration_policies_worker_capacity"` + ContainerRegistryImportCreatedBefore *time.Time `json:"container_registry_import_created_before"` + ContainerRegistryImportMaxRetries int `json:"container_registry_import_max_retries"` + ContainerRegistryImportMaxStepDuration int `json:"container_registry_import_max_step_duration"` + ContainerRegistryImportMaxTagsCount int `json:"container_registry_import_max_tags_count"` + ContainerRegistryImportStartMaxRetries int `json:"container_registry_import_start_max_retries"` + ContainerRegistryImportTargetPlan string `json:"container_registry_import_target_plan"` + ContainerRegistryTokenExpireDelay int `json:"container_registry_token_expire_delay"` + CreatedAt *time.Time `json:"created_at"` + CustomHTTPCloneURLRoot string `json:"custom_http_clone_url_root"` + DNSRebindingProtectionEnabled bool `json:"dns_rebinding_protection_enabled"` + DSAKeyRestriction int `json:"dsa_key_restriction"` + DeactivateDormantUsers bool `json:"deactivate_dormant_users"` + DeactivateDormantUsersPeriod int `json:"deactivate_dormant_users_period"` + DecompressArchiveFileTimeout int `json:"decompress_archive_file_timeout"` + DefaultArtifactsExpireIn string `json:"default_artifacts_expire_in"` + DefaultBranchName string `json:"default_branch_name"` + DefaultBranchProtection int `json:"default_branch_protection"` + DefaultBranchProtectionDefaults *BranchProtectionDefaults `json:"default_branch_protection_defaults,omitempty"` + DefaultCiConfigPath string `json:"default_ci_config_path"` + DefaultGroupVisibility VisibilityValue `json:"default_group_visibility"` + DefaultPreferredLanguage string `json:"default_preferred_language"` + DefaultProjectCreation int `json:"default_project_creation"` + DefaultProjectDeletionProtection bool `json:"default_project_deletion_protection"` + DefaultProjectVisibility VisibilityValue `json:"default_project_visibility"` + DefaultProjectsLimit int `json:"default_projects_limit"` + DefaultSnippetVisibility VisibilityValue `json:"default_snippet_visibility"` + DefaultSyntaxHighlightingTheme int `json:"default_syntax_highlighting_theme"` + DelayedGroupDeletion bool `json:"delayed_group_deletion"` + DelayedProjectDeletion bool `json:"delayed_project_deletion"` + DeleteInactiveProjects bool `json:"delete_inactive_projects"` + DeleteUnconfirmedUsers bool `json:"delete_unconfirmed_users"` + DeletionAdjournedPeriod int `json:"deletion_adjourned_period"` + DiagramsnetEnabled bool `json:"diagramsnet_enabled"` + DiagramsnetURL string `json:"diagramsnet_url"` + DiffMaxFiles int `json:"diff_max_files"` + DiffMaxLines int `json:"diff_max_lines"` + DiffMaxPatchBytes int `json:"diff_max_patch_bytes"` + DisableAdminOAuthScopes bool `json:"disable_admin_oauth_scopes"` + DisableFeedToken bool `json:"disable_feed_token"` + DisableOverridingApproversPerMergeRequest bool `json:"disable_overriding_approvers_per_merge_request"` + DisablePersonalAccessTokens bool `json:"disable_personal_access_tokens"` + DisabledOauthSignInSources []string `json:"disabled_oauth_sign_in_sources"` + DomainAllowlist []string `json:"domain_allowlist"` + DomainDenylist []string `json:"domain_denylist"` + DomainDenylistEnabled bool `json:"domain_denylist_enabled"` + DownstreamPipelineTriggerLimitPerProjectUserSHA int `json:"downstream_pipeline_trigger_limit_per_project_user_sha"` + DuoFeaturesEnabled bool `json:"duo_features_enabled"` + ECDSAKeyRestriction int `json:"ecdsa_key_restriction"` + ECDSASKKeyRestriction int `json:"ecdsa_sk_key_restriction"` + EKSAccessKeyID string `json:"eks_access_key_id"` + EKSAccountID string `json:"eks_account_id"` + EKSIntegrationEnabled bool `json:"eks_integration_enabled"` + EKSSecretAccessKey string `json:"eks_secret_access_key"` + Ed25519KeyRestriction int `json:"ed25519_key_restriction"` + Ed25519SKKeyRestriction int `json:"ed25519_sk_key_restriction"` + ElasticsearchAWS bool `json:"elasticsearch_aws"` + ElasticsearchAWSAccessKey string `json:"elasticsearch_aws_access_key"` + ElasticsearchAWSRegion string `json:"elasticsearch_aws_region"` + ElasticsearchAWSSecretAccessKey string `json:"elasticsearch_aws_secret_access_key"` + ElasticsearchAnalyzersKuromojiEnabled bool `json:"elasticsearch_analyzers_kuromoji_enabled"` + ElasticsearchAnalyzersKuromojiSearch bool `json:"elasticsearch_analyzers_kuromoji_search"` + ElasticsearchAnalyzersSmartCNEnabled bool `json:"elasticsearch_analyzers_smartcn_enabled"` + ElasticsearchAnalyzersSmartCNSearch bool `json:"elasticsearch_analyzers_smartcn_search"` + ElasticsearchClientRequestTimeout int `json:"elasticsearch_client_request_timeout"` + ElasticsearchIndexedFieldLengthLimit int `json:"elasticsearch_indexed_field_length_limit"` + ElasticsearchIndexedFileSizeLimitKB int `json:"elasticsearch_indexed_file_size_limit_kb"` + ElasticsearchIndexing bool `json:"elasticsearch_indexing"` + ElasticsearchLimitIndexing bool `json:"elasticsearch_limit_indexing"` + ElasticsearchMaxBulkConcurrency int `json:"elasticsearch_max_bulk_concurrency"` + ElasticsearchMaxBulkSizeMB int `json:"elasticsearch_max_bulk_size_mb"` + ElasticsearchMaxCodeIndexingConcurrency int `json:"elasticsearch_max_code_indexing_concurrency"` + ElasticsearchNamespaceIDs []int `json:"elasticsearch_namespace_ids"` + ElasticsearchPassword string `json:"elasticsearch_password"` + ElasticsearchPauseIndexing bool `json:"elasticsearch_pause_indexing"` + ElasticsearchProjectIDs []int `json:"elasticsearch_project_ids"` + ElasticsearchReplicas int `json:"elasticsearch_replicas"` + ElasticsearchRequeueWorkers bool `json:"elasticsearch_requeue_workers"` + ElasticsearchSearch bool `json:"elasticsearch_search"` + ElasticsearchShards int `json:"elasticsearch_shards"` + ElasticsearchURL []string `json:"elasticsearch_url"` + ElasticsearchUsername string `json:"elasticsearch_username"` + ElasticsearchWorkerNumberOfShards int `json:"elasticsearch_worker_number_of_shards"` + EmailAdditionalText string `json:"email_additional_text"` + EmailAuthorInBody bool `json:"email_author_in_body"` + EmailConfirmationSetting string `json:"email_confirmation_setting"` + EmailRestrictions string `json:"email_restrictions"` + EmailRestrictionsEnabled bool `json:"email_restrictions_enabled"` + EnableArtifactExternalRedirectWarningPage bool `json:"enable_artifact_external_redirect_warning_page"` + EnabledGitAccessProtocol string `json:"enabled_git_access_protocol"` + EnforceNamespaceStorageLimit bool `json:"enforce_namespace_storage_limit"` + EnforcePATExpiration bool `json:"enforce_pat_expiration"` + EnforceSSHKeyExpiration bool `json:"enforce_ssh_key_expiration"` + EnforceTerms bool `json:"enforce_terms"` + ExternalAuthClientCert string `json:"external_auth_client_cert"` + ExternalAuthClientKey string `json:"external_auth_client_key"` + ExternalAuthClientKeyPass string `json:"external_auth_client_key_pass"` + ExternalAuthorizationServiceDefaultLabel string `json:"external_authorization_service_default_label"` + ExternalAuthorizationServiceEnabled bool `json:"external_authorization_service_enabled"` + ExternalAuthorizationServiceTimeout float64 `json:"external_authorization_service_timeout"` + ExternalAuthorizationServiceURL string `json:"external_authorization_service_url"` + ExternalPipelineValidationServiceTimeout int `json:"external_pipeline_validation_service_timeout"` + ExternalPipelineValidationServiceToken string `json:"external_pipeline_validation_service_token"` + ExternalPipelineValidationServiceURL string `json:"external_pipeline_validation_service_url"` + FailedLoginAttemptsUnlockPeriodInMinutes int `json:"failed_login_attempts_unlock_period_in_minutes"` + FileTemplateProjectID int `json:"file_template_project_id"` + FirstDayOfWeek int `json:"first_day_of_week"` + FlocEnabled bool `json:"floc_enabled"` + GeoNodeAllowedIPs string `json:"geo_node_allowed_ips"` + GeoStatusTimeout int `json:"geo_status_timeout"` + GitRateLimitUsersAlertlist []string `json:"git_rate_limit_users_alertlist"` + GitTwoFactorSessionExpiry int `json:"git_two_factor_session_expiry"` + GitalyTimeoutDefault int `json:"gitaly_timeout_default"` + GitalyTimeoutFast int `json:"gitaly_timeout_fast"` + GitalyTimeoutMedium int `json:"gitaly_timeout_medium"` + GitlabDedicatedInstance bool `json:"gitlab_dedicated_instance"` + GitlabEnvironmentToolkitInstance bool `json:"gitlab_environment_toolkit_instance"` + GitlabShellOperationLimit int `json:"gitlab_shell_operation_limit"` + GitpodEnabled bool `json:"gitpod_enabled"` + GitpodURL string `json:"gitpod_url"` + GitRateLimitUsersAllowlist []string `json:"git_rate_limit_users_allowlist"` + GloballyAllowedIPs string `json:"globally_allowed_ips"` + GrafanaEnabled bool `json:"grafana_enabled"` + GrafanaURL string `json:"grafana_url"` + GravatarEnabled bool `json:"gravatar_enabled"` + GroupDownloadExportLimit int `json:"group_download_export_limit"` + GroupExportLimit int `json:"group_export_limit"` + GroupImportLimit int `json:"group_import_limit"` + GroupOwnersCanManageDefaultBranchProtection bool `json:"group_owners_can_manage_default_branch_protection"` + GroupRunnerTokenExpirationInterval int `json:"group_runner_token_expiration_interval"` + HTMLEmailsEnabled bool `json:"html_emails_enabled"` + HashedStorageEnabled bool `json:"hashed_storage_enabled"` + HelpPageDocumentationBaseURL string `json:"help_page_documentation_base_url"` + HelpPageHideCommercialContent bool `json:"help_page_hide_commercial_content"` + HelpPageSupportURL string `json:"help_page_support_url"` + HelpPageText string `json:"help_page_text"` + HelpText string `json:"help_text"` + HideThirdPartyOffers bool `json:"hide_third_party_offers"` + HomePageURL string `json:"home_page_url"` + HousekeepingBitmapsEnabled bool `json:"housekeeping_bitmaps_enabled"` + HousekeepingEnabled bool `json:"housekeeping_enabled"` + HousekeepingFullRepackPeriod int `json:"housekeeping_full_repack_period"` + HousekeepingGcPeriod int `json:"housekeeping_gc_period"` + HousekeepingIncrementalRepackPeriod int `json:"housekeeping_incremental_repack_period"` + HousekeepingOptimizeRepositoryPeriod int `json:"housekeeping_optimize_repository_period"` + ImportSources []string `json:"import_sources"` + InactiveProjectsDeleteAfterMonths int `json:"inactive_projects_delete_after_months"` + InactiveProjectsMinSizeMB int `json:"inactive_projects_min_size_mb"` + InactiveProjectsSendWarningEmailAfterMonths int `json:"inactive_projects_send_warning_email_after_months"` + IncludeOptionalMetricsInServicePing bool `json:"include_optional_metrics_in_service_ping"` + InProductMarketingEmailsEnabled bool `json:"in_product_marketing_emails_enabled"` + InvisibleCaptchaEnabled bool `json:"invisible_captcha_enabled"` + IssuesCreateLimit int `json:"issues_create_limit"` + JiraConnectApplicationKey string `json:"jira_connect_application_key"` + JiraConnectPublicKeyStorageEnabled bool `json:"jira_connect_public_key_storage_enabled"` + JiraConnectProxyURL string `json:"jira_connect_proxy_url"` + KeepLatestArtifact bool `json:"keep_latest_artifact"` + KrokiEnabled bool `json:"kroki_enabled"` + KrokiFormats map[string]bool `json:"kroki_formats"` + KrokiURL string `json:"kroki_url"` + LocalMarkdownVersion int `json:"local_markdown_version"` + LockDuoFeaturesEnabled bool `json:"lock_duo_features_enabled"` + LockMembershipsToLDAP bool `json:"lock_memberships_to_ldap"` + LoginRecaptchaProtectionEnabled bool `json:"login_recaptcha_protection_enabled"` + MailgunEventsEnabled bool `json:"mailgun_events_enabled"` + MailgunSigningKey string `json:"mailgun_signing_key"` + MaintenanceMode bool `json:"maintenance_mode"` + MaintenanceModeMessage string `json:"maintenance_mode_message"` + MavenPackageRequestsForwarding bool `json:"maven_package_requests_forwarding"` + MaxArtifactsSize int `json:"max_artifacts_size"` + MaxAttachmentSize int `json:"max_attachment_size"` + MaxDecompressedArchiveSize int `json:"max_decompressed_archive_size"` + MaxExportSize int `json:"max_export_size"` + MaxImportRemoteFileSize int `json:"max_import_remote_file_size"` + MaxImportSize int `json:"max_import_size"` + MaxLoginAttempts int `json:"max_login_attempts"` + MaxNumberOfRepositoryDownloads int `json:"max_number_of_repository_downloads"` + MaxNumberOfRepositoryDownloadsWithinTimePeriod int `json:"max_number_of_repository_downloads_within_time_period"` + MaxPagesSize int `json:"max_pages_size"` + MaxPersonalAccessTokenLifetime int `json:"max_personal_access_token_lifetime"` + MaxSSHKeyLifetime int `json:"max_ssh_key_lifetime"` + MaxTerraformStateSizeBytes int `json:"max_terraform_state_size_bytes"` + MaxYAMLDepth int `json:"max_yaml_depth"` + MaxYAMLSizeBytes int `json:"max_yaml_size_bytes"` + MetricsMethodCallThreshold int `json:"metrics_method_call_threshold"` + MinimumPasswordLength int `json:"minimum_password_length"` + MirrorAvailable bool `json:"mirror_available"` + MirrorCapacityThreshold int `json:"mirror_capacity_threshold"` + MirrorMaxCapacity int `json:"mirror_max_capacity"` + MirrorMaxDelay int `json:"mirror_max_delay"` + NPMPackageRequestsForwarding bool `json:"npm_package_requests_forwarding"` + NotesCreateLimit int `json:"notes_create_limit"` + NotifyOnUnknownSignIn bool `json:"notify_on_unknown_sign_in"` + NugetSkipMetadataURLValidation bool `json:"nuget_skip_metadata_url_validation"` + OutboundLocalRequestsAllowlistRaw string `json:"outbound_local_requests_allowlist_raw"` + OutboundLocalRequestsWhitelist []string `json:"outbound_local_requests_whitelist"` + PackageMetadataPURLTypes []int `json:"package_metadata_purl_types"` + PackageRegistryAllowAnyoneToPullOption bool `json:"package_registry_allow_anyone_to_pull_option"` + PackageRegistryCleanupPoliciesWorkerCapacity int `json:"package_registry_cleanup_policies_worker_capacity"` + PagesDomainVerificationEnabled bool `json:"pages_domain_verification_enabled"` + PasswordAuthenticationEnabledForGit bool `json:"password_authentication_enabled_for_git"` + PasswordAuthenticationEnabledForWeb bool `json:"password_authentication_enabled_for_web"` + PasswordNumberRequired bool `json:"password_number_required"` + PasswordSymbolRequired bool `json:"password_symbol_required"` + PasswordUppercaseRequired bool `json:"password_uppercase_required"` + PasswordLowercaseRequired bool `json:"password_lowercase_required"` + PerformanceBarAllowedGroupID int `json:"performance_bar_allowed_group_id"` + PerformanceBarAllowedGroupPath string `json:"performance_bar_allowed_group_path"` + PerformanceBarEnabled bool `json:"performance_bar_enabled"` + PersonalAccessTokenPrefix string `json:"personal_access_token_prefix"` + PipelineLimitPerProjectUserSha int `json:"pipeline_limit_per_project_user_sha"` + PlantumlEnabled bool `json:"plantuml_enabled"` + PlantumlURL string `json:"plantuml_url"` + PollingIntervalMultiplier float64 `json:"polling_interval_multiplier,string"` + PreventMergeRequestsAuthorApproval bool `json:"prevent_merge_request_author_approval"` + PreventMergeRequestsCommittersApproval bool `json:"prevent_merge_request_committers_approval"` + ProjectDownloadExportLimit int `json:"project_download_export_limit"` + ProjectExportEnabled bool `json:"project_export_enabled"` + ProjectExportLimit int `json:"project_export_limit"` + ProjectImportLimit int `json:"project_import_limit"` + ProjectJobsAPIRateLimit int `json:"project_jobs_api_rate_limit"` + ProjectRunnerTokenExpirationInterval int `json:"project_runner_token_expiration_interval"` + ProjectsAPIRateLimitUnauthenticated int `json:"projects_api_rate_limit_unauthenticated"` + PrometheusMetricsEnabled bool `json:"prometheus_metrics_enabled"` + ProtectedCIVariables bool `json:"protected_ci_variables"` + PseudonymizerEnabled bool `json:"pseudonymizer_enabled"` + PushEventActivitiesLimit int `json:"push_event_activities_limit"` + PushEventHooksLimit int `json:"push_event_hooks_limit"` + PyPIPackageRequestsForwarding bool `json:"pypi_package_requests_forwarding"` + RSAKeyRestriction int `json:"rsa_key_restriction"` + RateLimitingResponseText string `json:"rate_limiting_response_text"` + RawBlobRequestLimit int `json:"raw_blob_request_limit"` + RecaptchaEnabled bool `json:"recaptcha_enabled"` + RecaptchaPrivateKey string `json:"recaptcha_private_key"` + RecaptchaSiteKey string `json:"recaptcha_site_key"` + ReceiveMaxInputSize int `json:"receive_max_input_size"` + ReceptiveClusterAgentsEnabled bool `json:"receptive_cluster_agents_enabled"` + RememberMeEnabled bool `json:"remember_me_enabled"` + RepositoryChecksEnabled bool `json:"repository_checks_enabled"` + RepositorySizeLimit int `json:"repository_size_limit"` + RepositoryStorages []string `json:"repository_storages"` + RepositoryStoragesWeighted map[string]int `json:"repository_storages_weighted"` + RequireAdminApprovalAfterUserSignup bool `json:"require_admin_approval_after_user_signup"` + RequireAdminTwoFactorAuthentication bool `json:"require_admin_two_factor_authentication"` + RequirePersonalAccessTokenExpiry bool `json:"require_personal_access_token_expiry"` + RequireTwoFactorAuthentication bool `json:"require_two_factor_authentication"` + RestrictedVisibilityLevels []VisibilityValue `json:"restricted_visibility_levels"` + RunnerTokenExpirationInterval int `json:"runner_token_expiration_interval"` + SearchRateLimit int `json:"search_rate_limit"` + SearchRateLimitUnauthenticated int `json:"search_rate_limit_unauthenticated"` + SecretDetectionRevocationTokenTypesURL string `json:"secret_detection_revocation_token_types_url"` + SecretDetectionTokenRevocationEnabled bool `json:"secret_detection_token_revocation_enabled"` + SecretDetectionTokenRevocationToken string `json:"secret_detection_token_revocation_token"` + SecretDetectionTokenRevocationURL string `json:"secret_detection_token_revocation_url"` + SecurityApprovalPoliciesLimit int `json:"security_approval_policies_limit"` + SecurityPolicyGlobalGroupApproversEnabled bool `json:"security_policy_global_group_approvers_enabled"` + SecurityTXTContent string `json:"security_txt_content"` + SendUserConfirmationEmail bool `json:"send_user_confirmation_email"` + SentryClientsideDSN string `json:"sentry_clientside_dsn"` + SentryDSN string `json:"sentry_dsn"` + SentryEnabled bool `json:"sentry_enabled"` + SentryEnvironment string `json:"sentry_environment"` + ServiceAccessTokensExpirationEnforced bool `json:"service_access_tokens_expiration_enforced"` + SessionExpireDelay int `json:"session_expire_delay"` + SharedRunnersEnabled bool `json:"shared_runners_enabled"` + SharedRunnersMinutes int `json:"shared_runners_minutes"` + SharedRunnersText string `json:"shared_runners_text"` + SidekiqJobLimiterCompressionThresholdBytes int `json:"sidekiq_job_limiter_compression_threshold_bytes"` + SidekiqJobLimiterLimitBytes int `json:"sidekiq_job_limiter_limit_bytes"` + SidekiqJobLimiterMode string `json:"sidekiq_job_limiter_mode"` + SignInText string `json:"sign_in_text"` + SignupEnabled bool `json:"signup_enabled"` + SilentAdminExportsEnabled bool `json:"silent_admin_exports_enabled"` + SilentModeEnabled bool `json:"silent_mode_enabled"` + SlackAppEnabled bool `json:"slack_app_enabled"` + SlackAppID string `json:"slack_app_id"` + SlackAppSecret string `json:"slack_app_secret"` + SlackAppSigningSecret string `json:"slack_app_signing_secret"` + SlackAppVerificationToken string `json:"slack_app_verification_token"` + SnippetSizeLimit int `json:"snippet_size_limit"` + SnowplowAppID string `json:"snowplow_app_id"` + SnowplowCollectorHostname string `json:"snowplow_collector_hostname"` + SnowplowCookieDomain string `json:"snowplow_cookie_domain"` + SnowplowDatabaseCollectorHostname string `json:"snowplow_database_collector_hostname"` + SnowplowEnabled bool `json:"snowplow_enabled"` + SourcegraphEnabled bool `json:"sourcegraph_enabled"` + SourcegraphPublicOnly bool `json:"sourcegraph_public_only"` + SourcegraphURL string `json:"sourcegraph_url"` + SpamCheckAPIKey string `json:"spam_check_api_key"` + SpamCheckEndpointEnabled bool `json:"spam_check_endpoint_enabled"` + SpamCheckEndpointURL string `json:"spam_check_endpoint_url"` + StaticObjectsExternalStorageAuthToken string `json:"static_objects_external_storage_auth_token"` + StaticObjectsExternalStorageURL string `json:"static_objects_external_storage_url"` + SuggestPipelineEnabled bool `json:"suggest_pipeline_enabled"` + TerminalMaxSessionTime int `json:"terminal_max_session_time"` + Terms string `json:"terms"` + ThrottleAuthenticatedAPIEnabled bool `json:"throttle_authenticated_api_enabled"` + ThrottleAuthenticatedAPIPeriodInSeconds int `json:"throttle_authenticated_api_period_in_seconds"` + ThrottleAuthenticatedAPIRequestsPerPeriod int `json:"throttle_authenticated_api_requests_per_period"` + ThrottleAuthenticatedDeprecatedAPIEnabled bool `json:"throttle_authenticated_deprecated_api_enabled"` + ThrottleAuthenticatedDeprecatedAPIPeriodInSeconds int `json:"throttle_authenticated_deprecated_api_period_in_seconds"` + ThrottleAuthenticatedDeprecatedAPIRequestsPerPeriod int `json:"throttle_authenticated_deprecated_api_requests_per_period"` + ThrottleAuthenticatedFilesAPIEnabled bool `json:"throttle_authenticated_files_api_enabled"` + ThrottleAuthenticatedFilesAPIPeriodInSeconds int `json:"throttle_authenticated_files_api_period_in_seconds"` + ThrottleAuthenticatedFilesAPIRequestsPerPeriod int `json:"throttle_authenticated_files_api_requests_per_period"` + ThrottleAuthenticatedGitLFSEnabled bool `json:"throttle_authenticated_git_lfs_enabled"` + ThrottleAuthenticatedGitLFSPeriodInSeconds int `json:"throttle_authenticated_git_lfs_period_in_seconds"` + ThrottleAuthenticatedGitLFSRequestsPerPeriod int `json:"throttle_authenticated_git_lfs_requests_per_period"` + ThrottleAuthenticatedPackagesAPIEnabled bool `json:"throttle_authenticated_packages_api_enabled"` + ThrottleAuthenticatedPackagesAPIPeriodInSeconds int `json:"throttle_authenticated_packages_api_period_in_seconds"` + ThrottleAuthenticatedPackagesAPIRequestsPerPeriod int `json:"throttle_authenticated_packages_api_requests_per_period"` + ThrottleAuthenticatedWebEnabled bool `json:"throttle_authenticated_web_enabled"` + ThrottleAuthenticatedWebPeriodInSeconds int `json:"throttle_authenticated_web_period_in_seconds"` + ThrottleAuthenticatedWebRequestsPerPeriod int `json:"throttle_authenticated_web_requests_per_period"` + ThrottleIncidentManagementNotificationEnabled bool `json:"throttle_incident_management_notification_enabled"` + ThrottleIncidentManagementNotificationPerPeriod int `json:"throttle_incident_management_notification_per_period"` + ThrottleIncidentManagementNotificationPeriodInSeconds int `json:"throttle_incident_management_notification_period_in_seconds"` + ThrottleProtectedPathsEnabled bool `json:"throttle_protected_paths_enabled"` + ThrottleProtectedPathsPeriodInSeconds int `json:"throttle_protected_paths_period_in_seconds"` + ThrottleProtectedPathsRequestsPerPeriod int `json:"throttle_protected_paths_requests_per_period"` + ThrottleUnauthenticatedAPIEnabled bool `json:"throttle_unauthenticated_api_enabled"` + ThrottleUnauthenticatedAPIPeriodInSeconds int `json:"throttle_unauthenticated_api_period_in_seconds"` + ThrottleUnauthenticatedAPIRequestsPerPeriod int `json:"throttle_unauthenticated_api_requests_per_period"` + ThrottleUnauthenticatedDeprecatedAPIEnabled bool `json:"throttle_unauthenticated_deprecated_api_enabled"` + ThrottleUnauthenticatedDeprecatedAPIPeriodInSeconds int `json:"throttle_unauthenticated_deprecated_api_period_in_seconds"` + ThrottleUnauthenticatedDeprecatedAPIRequestsPerPeriod int `json:"throttle_unauthenticated_deprecated_api_requests_per_period"` + ThrottleUnauthenticatedFilesAPIEnabled bool `json:"throttle_unauthenticated_files_api_enabled"` + ThrottleUnauthenticatedFilesAPIPeriodInSeconds int `json:"throttle_unauthenticated_files_api_period_in_seconds"` + ThrottleUnauthenticatedFilesAPIRequestsPerPeriod int `json:"throttle_unauthenticated_files_api_requests_per_period"` + ThrottleUnauthenticatedGitLFSEnabled bool `json:"throttle_unauthenticated_git_lfs_enabled"` + ThrottleUnauthenticatedGitLFSPeriodInSeconds int `json:"throttle_unauthenticated_git_lfs_period_in_seconds"` + ThrottleUnauthenticatedGitLFSRequestsPerPeriod int `json:"throttle_unauthenticated_git_lfs_requests_per_period"` + ThrottleUnauthenticatedPackagesAPIEnabled bool `json:"throttle_unauthenticated_packages_api_enabled"` + ThrottleUnauthenticatedPackagesAPIPeriodInSeconds int `json:"throttle_unauthenticated_packages_api_period_in_seconds"` + ThrottleUnauthenticatedPackagesAPIRequestsPerPeriod int `json:"throttle_unauthenticated_packages_api_requests_per_period"` + ThrottleUnauthenticatedWebEnabled bool `json:"throttle_unauthenticated_web_enabled"` + ThrottleUnauthenticatedWebPeriodInSeconds int `json:"throttle_unauthenticated_web_period_in_seconds"` + ThrottleUnauthenticatedWebRequestsPerPeriod int `json:"throttle_unauthenticated_web_requests_per_period"` + TimeTrackingLimitToHours bool `json:"time_tracking_limit_to_hours"` + TwoFactorGracePeriod int `json:"two_factor_grace_period"` + UnconfirmedUsersDeleteAfterDays int `json:"unconfirmed_users_delete_after_days"` + UniqueIPsLimitEnabled bool `json:"unique_ips_limit_enabled"` + UniqueIPsLimitPerUser int `json:"unique_ips_limit_per_user"` + UniqueIPsLimitTimeWindow int `json:"unique_ips_limit_time_window"` + UpdateRunnerVersionsEnabled bool `json:"update_runner_versions_enabled"` + UpdatedAt *time.Time `json:"updated_at"` + UpdatingNameDisabledForUsers bool `json:"updating_name_disabled_for_users"` + UsagePingEnabled bool `json:"usage_ping_enabled"` + UsagePingFeaturesEnabled bool `json:"usage_ping_features_enabled"` + UseClickhouseForAnalytics bool `json:"use_clickhouse_for_analytics"` + UserDeactivationEmailsEnabled bool `json:"user_deactivation_emails_enabled"` + UserDefaultExternal bool `json:"user_default_external"` + UserDefaultInternalRegex string `json:"user_default_internal_regex"` + UserDefaultsToPrivateProfile bool `json:"user_defaults_to_private_profile"` + UserOauthApplications bool `json:"user_oauth_applications"` + UserShowAddSSHKeyMessage bool `json:"user_show_add_ssh_key_message"` + UsersGetByIDLimit int `json:"users_get_by_id_limit"` + UsersGetByIDLimitAllowlistRaw string `json:"users_get_by_id_limit_allowlist_raw"` + ValidRunnerRegistrars []string `json:"valid_runner_registrars"` + VersionCheckEnabled bool `json:"version_check_enabled"` + WebIDEClientsidePreviewEnabled bool `json:"web_ide_clientside_preview_enabled"` + WhatsNewVariant string `json:"whats_new_variant"` + WikiPageMaxContentBytes int `json:"wiki_page_max_content_bytes"` + + // Deprecated: Use AbuseNotificationEmail instead. + AdminNotificationEmail string `json:"admin_notification_email"` + // Deprecated: Use AllowLocalRequestsFromWebHooksAndServices instead. + AllowLocalRequestsFromHooksAndServices bool `json:"allow_local_requests_from_hooks_and_services"` + // Deprecated: Use AssetProxyAllowlist instead. + AssetProxyWhitelist []string `json:"asset_proxy_whitelist"` + // Deprecated: Use ThrottleUnauthenticatedWebEnabled or ThrottleUnauthenticatedAPIEnabled instead. (Deprecated in GitLab 14.3) + ThrottleUnauthenticatedEnabled bool `json:"throttle_unauthenticated_enabled"` + // Deprecated: Use ThrottleUnauthenticatedWebPeriodInSeconds or ThrottleUnauthenticatedAPIPeriodInSeconds instead. (Deprecated in GitLab 14.3) + ThrottleUnauthenticatedPeriodInSeconds int `json:"throttle_unauthenticated_period_in_seconds"` + // Deprecated: Use ThrottleUnauthenticatedWebRequestsPerPeriod or ThrottleUnauthenticatedAPIRequestsPerPeriod instead. (Deprecated in GitLab 14.3) + ThrottleUnauthenticatedRequestsPerPeriod int `json:"throttle_unauthenticated_requests_per_period"` + // Deprecated: Replaced by SearchRateLimit in GitLab 14.9 (removed in 15.0). + UserEmailLookupLimit int `json:"user_email_lookup_limit"` +} + +// Settings requires a custom unmarshaller in order to properly unmarshal +// `container_registry_import_created_before` which is either a time.Time or +// an empty string if no value is set. +func (s *Settings) UnmarshalJSON(data []byte) error { + type Alias Settings + + raw := make(map[string]interface{}) + err := json.Unmarshal(data, &raw) + if err != nil { + return err + } + + // If empty string, remove the value to leave it nil in the response. + if v, ok := raw["container_registry_import_created_before"]; ok && v == "" { + delete(raw, "container_registry_import_created_before") + + data, err = json.Marshal(raw) + if err != nil { + return err + } + } + + return json.Unmarshal(data, (*Alias)(s)) +} + +func (s Settings) String() string { + return Stringify(s) +} + +// GetSettings gets the current application settings. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/settings.html#get-current-application-settings +func (s *SettingsService) GetSettings(options ...RequestOptionFunc) (*Settings, *Response, error) { + req, err := s.client.NewRequest(http.MethodGet, "application/settings", nil, options) + if err != nil { + return nil, nil, err + } + + as := new(Settings) + resp, err := s.client.Do(req, as) + if err != nil { + return nil, resp, err + } + + return as, resp, nil +} + +// UpdateSettingsOptions represents the available UpdateSettings() options. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/settings.html#change-application-settings +type UpdateSettingsOptions struct { + AbuseNotificationEmail *string `url:"abuse_notification_email,omitempty" json:"abuse_notification_email,omitempty"` + AdminMode *bool `url:"admin_mode,omitempty" json:"admin_mode,omitempty"` + AdminNotificationEmail *string `url:"admin_notification_email,omitempty" json:"admin_notification_email,omitempty"` + AfterSignOutPath *string `url:"after_sign_out_path,omitempty" json:"after_sign_out_path,omitempty"` + AfterSignUpText *string `url:"after_sign_up_text,omitempty" json:"after_sign_up_text,omitempty"` + AkismetAPIKey *string `url:"akismet_api_key,omitempty" json:"akismet_api_key,omitempty"` + AkismetEnabled *bool `url:"akismet_enabled,omitempty" json:"akismet_enabled,omitempty"` + AllowAccountDeletion *bool `url:"allow_account_deletion,omitempty" json:"allow_account_deletion,omitempty"` + AllowGroupOwnersToManageLDAP *bool `url:"allow_group_owners_to_manage_ldap,omitempty" json:"allow_group_owners_to_manage_ldap,omitempty"` + AllowLocalRequestsFromHooksAndServices *bool `url:"allow_local_requests_from_hooks_and_services,omitempty" json:"allow_local_requests_from_hooks_and_services,omitempty"` + AllowLocalRequestsFromSystemHooks *bool `url:"allow_local_requests_from_system_hooks,omitempty" json:"allow_local_requests_from_system_hooks,omitempty"` + AllowLocalRequestsFromWebHooksAndServices *bool `url:"allow_local_requests_from_web_hooks_and_services,omitempty" json:"allow_local_requests_from_web_hooks_and_services,omitempty"` + AllowProjectCreationForGuestAndBelow *bool `url:"allow_project_creation_for_guest_and_below,omitempty" json:"allow_project_creation_for_guest_and_below,omitempty"` + AllowRunnerRegistrationToken *bool `url:"allow_runner_registration_token,omitempty" json:"allow_runner_registration_token,omitempty"` + ArchiveBuildsInHumanReadable *string `url:"archive_builds_in_human_readable,omitempty" json:"archive_builds_in_human_readable,omitempty"` + ASCIIDocMaxIncludes *int `url:"asciidoc_max_includes,omitempty" json:"asciidoc_max_includes,omitempty"` + AssetProxyAllowlist *[]string `url:"asset_proxy_allowlist,omitempty" json:"asset_proxy_allowlist,omitempty"` + AssetProxyEnabled *bool `url:"asset_proxy_enabled,omitempty" json:"asset_proxy_enabled,omitempty"` + AssetProxySecretKey *string `url:"asset_proxy_secret_key,omitempty" json:"asset_proxy_secret_key,omitempty"` + AssetProxyURL *string `url:"asset_proxy_url,omitempty" json:"asset_proxy_url,omitempty"` + AssetProxyWhitelist *[]string `url:"asset_proxy_whitelist,omitempty" json:"asset_proxy_whitelist,omitempty"` + AuthorizedKeysEnabled *bool `url:"authorized_keys_enabled,omitempty" json:"authorized_keys_enabled,omitempty"` + AutoBanUserOnExcessiveProjectsDownload *bool `url:"auto_ban_user_on_excessive_projects_download,omitempty" json:"auto_ban_user_on_excessive_projects_download,omitempty"` + AutoDevOpsDomain *string `url:"auto_devops_domain,omitempty" json:"auto_devops_domain,omitempty"` + AutoDevOpsEnabled *bool `url:"auto_devops_enabled,omitempty" json:"auto_devops_enabled,omitempty"` + AutomaticPurchasedStorageAllocation *bool `url:"automatic_purchased_storage_allocation,omitempty" json:"automatic_purchased_storage_allocation,omitempty"` + BulkImportConcurrentPipelineBatchLimit *int `url:"bulk_import_concurrent_pipeline_batch_limit,omitempty" json:"bulk_import_concurrent_pipeline_batch_limit,omitempty"` + BulkImportEnabled *bool `url:"bulk_import_enabled,omitempty" json:"bulk_import_enabled,omitempty"` + BulkImportMaxDownloadFileSize *int `url:"bulk_import_max_download_file_size,omitempty" json:"bulk_import_max_download_file_size,omitempty"` + CanCreateGroup *bool `url:"can_create_group,omitempty" json:"can_create_group,omitempty"` + CheckNamespacePlan *bool `url:"check_namespace_plan,omitempty" json:"check_namespace_plan,omitempty"` + CIMaxIncludes *int `url:"ci_max_includes,omitempty" json:"ci_max_includes,omitempty"` + CIMaxTotalYAMLSizeBytes *int `url:"ci_max_total_yaml_size_bytes,omitempty" json:"ci_max_total_yaml_size_bytes,omitempty"` + CommitEmailHostname *string `url:"commit_email_hostname,omitempty" json:"commit_email_hostname,omitempty"` + ConcurrentBitbucketImportJobsLimit *int `url:"concurrent_bitbucket_import_jobs_limit,omitempty" json:"concurrent_bitbucket_import_jobs_limit,omitempty"` + ConcurrentBitbucketServerImportJobsLimit *int `url:"concurrent_bitbucket_server_import_jobs_limit,omitempty" json:"concurrent_bitbucket_server_import_jobs_limit,omitempty"` + ConcurrentGitHubImportJobsLimit *int `url:"concurrent_github_import_jobs_limit,omitempty" json:"concurrent_github_import_jobs_limit,omitempty"` + ContainerExpirationPoliciesEnableHistoricEntries *bool `url:"container_expiration_policies_enable_historic_entries,omitempty" json:"container_expiration_policies_enable_historic_entries,omitempty"` + ContainerRegistryCleanupTagsServiceMaxListSize *int `url:"container_registry_cleanup_tags_service_max_list_size,omitempty" json:"container_registry_cleanup_tags_service_max_list_size,omitempty"` + ContainerRegistryDeleteTagsServiceTimeout *int `url:"container_registry_delete_tags_service_timeout,omitempty" json:"container_registry_delete_tags_service_timeout,omitempty"` + ContainerRegistryExpirationPoliciesCaching *bool `url:"container_registry_expiration_policies_caching,omitempty" json:"container_registry_expiration_policies_caching,omitempty"` + ContainerRegistryExpirationPoliciesWorkerCapacity *int `url:"container_registry_expiration_policies_worker_capacity,omitempty" json:"container_registry_expiration_policies_worker_capacity,omitempty"` + ContainerRegistryImportCreatedBefore *time.Time `url:"container_registry_import_created_before,omitempty" json:"container_registry_import_created_before,omitempty"` + ContainerRegistryImportMaxRetries *int `url:"container_registry_import_max_retries,omitempty" json:"container_registry_import_max_retries,omitempty"` + ContainerRegistryImportMaxStepDuration *int `url:"container_registry_import_max_step_duration,omitempty" json:"container_registry_import_max_step_duration,omitempty"` + ContainerRegistryImportMaxTagsCount *int `url:"container_registry_import_max_tags_count,omitempty" json:"container_registry_import_max_tags_count,omitempty"` + ContainerRegistryImportStartMaxRetries *int `url:"container_registry_import_start_max_retries,omitempty" json:"container_registry_import_start_max_retries,omitempty"` + ContainerRegistryImportTargetPlan *string `url:"container_registry_import_target_plan,omitempty" json:"container_registry_import_target_plan,omitempty"` + ContainerRegistryTokenExpireDelay *int `url:"container_registry_token_expire_delay,omitempty" json:"container_registry_token_expire_delay,omitempty"` + CustomHTTPCloneURLRoot *string `url:"custom_http_clone_url_root,omitempty" json:"custom_http_clone_url_root,omitempty"` + DNSRebindingProtectionEnabled *bool `url:"dns_rebinding_protection_enabled,omitempty" json:"dns_rebinding_protection_enabled,omitempty"` + DSAKeyRestriction *int `url:"dsa_key_restriction,omitempty" json:"dsa_key_restriction,omitempty"` + DeactivateDormantUsers *bool `url:"deactivate_dormant_users,omitempty" json:"deactivate_dormant_users,omitempty"` + DeactivateDormantUsersPeriod *int `url:"deactivate_dormant_users_period,omitempty" json:"deactivate_dormant_users_period,omitempty"` + DecompressArchiveFileTimeout *int `url:"decompress_archive_file_timeout,omitempty" json:"decompress_archive_file_timeout,omitempty"` + DefaultArtifactsExpireIn *string `url:"default_artifacts_expire_in,omitempty" json:"default_artifacts_expire_in,omitempty"` + DefaultBranchName *string `url:"default_branch_name,omitempty" json:"default_branch_name,omitempty"` + DefaultBranchProtection *int `url:"default_branch_protection,omitempty" json:"default_branch_protection,omitempty"` + DefaultBranchProtectionDefaults *DefaultBranchProtectionDefaultsOptions `url:"default_branch_protection_defaults,omitempty" json:"default_branch_protection_defaults,omitempty"` + DefaultCiConfigPath *string `url:"default_ci_config_path,omitempty" json:"default_ci_config_path,omitempty"` + DefaultGroupVisibility *VisibilityValue `url:"default_group_visibility,omitempty" json:"default_group_visibility,omitempty"` + DefaultPreferredLanguage *string `url:"default_preferred_language,omitempty" json:"default_preferred_language,omitempty"` + DefaultProjectCreation *int `url:"default_project_creation,omitempty" json:"default_project_creation,omitempty"` + DefaultProjectDeletionProtection *bool `url:"default_project_deletion_protection,omitempty" json:"default_project_deletion_protection,omitempty"` + DefaultProjectVisibility *VisibilityValue `url:"default_project_visibility,omitempty" json:"default_project_visibility,omitempty"` + DefaultProjectsLimit *int `url:"default_projects_limit,omitempty" json:"default_projects_limit,omitempty"` + DefaultSnippetVisibility *VisibilityValue `url:"default_snippet_visibility,omitempty" json:"default_snippet_visibility,omitempty"` + DefaultSyntaxHighlightingTheme *int `url:"default_syntax_highlighting_theme,omitempty" json:"default_syntax_highlighting_theme,omitempty"` + DelayedGroupDeletion *bool `url:"delayed_group_deletion,omitempty" json:"delayed_group_deletion,omitempty"` + DelayedProjectDeletion *bool `url:"delayed_project_deletion,omitempty" json:"delayed_project_deletion,omitempty"` + DeleteInactiveProjects *bool `url:"delete_inactive_projects,omitempty" json:"delete_inactive_projects,omitempty"` + DeleteUnconfirmedUsers *bool `url:"delete_unconfirmed_users,omitempty" json:"delete_unconfirmed_users,omitempty"` + DeletionAdjournedPeriod *int `url:"deletion_adjourned_period,omitempty" json:"deletion_adjourned_period,omitempty"` + DiagramsnetEnabled *bool `url:"diagramsnet_enabled,omitempty" json:"diagramsnet_enabled,omitempty"` + DiagramsnetURL *string `url:"diagramsnet_url,omitempty" json:"diagramsnet_url,omitempty"` + DiffMaxFiles *int `url:"diff_max_files,omitempty" json:"diff_max_files,omitempty"` + DiffMaxLines *int `url:"diff_max_lines,omitempty" json:"diff_max_lines,omitempty"` + DiffMaxPatchBytes *int `url:"diff_max_patch_bytes,omitempty" json:"diff_max_patch_bytes,omitempty"` + DisableFeedToken *bool `url:"disable_feed_token,omitempty" json:"disable_feed_token,omitempty"` + DisableAdminOAuthScopes *bool `url:"disable_admin_oauth_scopes,omitempty" json:"disable_admin_oauth_scopes,omitempty"` + DisableOverridingApproversPerMergeRequest *bool `url:"disable_overriding_approvers_per_merge_request,omitempty" json:"disable_overriding_approvers_per_merge_request,omitempty"` + DisablePersonalAccessTokens *bool `url:"disable_personal_access_tokens,omitempty" json:"disable_personal_access_tokens,omitempty"` + DisabledOauthSignInSources *[]string `url:"disabled_oauth_sign_in_sources,omitempty" json:"disabled_oauth_sign_in_sources,omitempty"` + DomainAllowlist *[]string `url:"domain_allowlist,omitempty" json:"domain_allowlist,omitempty"` + DomainDenylist *[]string `url:"domain_denylist,omitempty" json:"domain_denylist,omitempty"` + DomainDenylistEnabled *bool `url:"domain_denylist_enabled,omitempty" json:"domain_denylist_enabled,omitempty"` + DownstreamPipelineTriggerLimitPerProjectUserSHA *int `url:"downstream_pipeline_trigger_limit_per_project_user_sha,omitempty" json:"downstream_pipeline_trigger_limit_per_project_user_sha,omitempty"` + DuoFeaturesEnabled *bool `url:"duo_features_enabled,omitempty" json:"duo_features_enabled,omitempty"` + ECDSAKeyRestriction *int `url:"ecdsa_key_restriction,omitempty" json:"ecdsa_key_restriction,omitempty"` + ECDSASKKeyRestriction *int `url:"ecdsa_sk_key_restriction,omitempty" json:"ecdsa_sk_key_restriction,omitempty"` + EKSAccessKeyID *string `url:"eks_access_key_id,omitempty" json:"eks_access_key_id,omitempty"` + EKSAccountID *string `url:"eks_account_id,omitempty" json:"eks_account_id,omitempty"` + EKSIntegrationEnabled *bool `url:"eks_integration_enabled,omitempty" json:"eks_integration_enabled,omitempty"` + EKSSecretAccessKey *string `url:"eks_secret_access_key,omitempty" json:"eks_secret_access_key,omitempty"` + Ed25519KeyRestriction *int `url:"ed25519_key_restriction,omitempty" json:"ed25519_key_restriction,omitempty"` + Ed25519SKKeyRestriction *int `url:"ed25519_sk_key_restriction,omitempty" json:"ed25519_sk_key_restriction,omitempty"` + ElasticsearchAWS *bool `url:"elasticsearch_aws,omitempty" json:"elasticsearch_aws,omitempty"` + ElasticsearchAWSAccessKey *string `url:"elasticsearch_aws_access_key,omitempty" json:"elasticsearch_aws_access_key,omitempty"` + ElasticsearchAWSRegion *string `url:"elasticsearch_aws_region,omitempty" json:"elasticsearch_aws_region,omitempty"` + ElasticsearchAWSSecretAccessKey *string `url:"elasticsearch_aws_secret_access_key,omitempty" json:"elasticsearch_aws_secret_access_key,omitempty"` + ElasticsearchAnalyzersKuromojiEnabled *bool `url:"elasticsearch_analyzers_kuromoji_enabled,omitempty" json:"elasticsearch_analyzers_kuromoji_enabled,omitempty"` + ElasticsearchAnalyzersKuromojiSearch *int `url:"elasticsearch_analyzers_kuromoji_search,omitempty" json:"elasticsearch_analyzers_kuromoji_search,omitempty"` + ElasticsearchAnalyzersSmartCNEnabled *bool `url:"elasticsearch_analyzers_smartcn_enabled,omitempty" json:"elasticsearch_analyzers_smartcn_enabled,omitempty"` + ElasticsearchAnalyzersSmartCNSearch *int `url:"elasticsearch_analyzers_smartcn_search,omitempty" json:"elasticsearch_analyzers_smartcn_search,omitempty"` + ElasticsearchClientRequestTimeout *int `url:"elasticsearch_client_request_timeout,omitempty" json:"elasticsearch_client_request_timeout,omitempty"` + ElasticsearchIndexedFieldLengthLimit *int `url:"elasticsearch_indexed_field_length_limit,omitempty" json:"elasticsearch_indexed_field_length_limit,omitempty"` + ElasticsearchIndexedFileSizeLimitKB *int `url:"elasticsearch_indexed_file_size_limit_kb,omitempty" json:"elasticsearch_indexed_file_size_limit_kb,omitempty"` + ElasticsearchIndexing *bool `url:"elasticsearch_indexing,omitempty" json:"elasticsearch_indexing,omitempty"` + ElasticsearchLimitIndexing *bool `url:"elasticsearch_limit_indexing,omitempty" json:"elasticsearch_limit_indexing,omitempty"` + ElasticsearchMaxBulkConcurrency *int `url:"elasticsearch_max_bulk_concurrency,omitempty" json:"elasticsearch_max_bulk_concurrency,omitempty"` + ElasticsearchMaxBulkSizeMB *int `url:"elasticsearch_max_bulk_size_mb,omitempty" json:"elasticsearch_max_bulk_size_mb,omitempty"` + ElasticsearchMaxCodeIndexingConcurrency *int `url:"elasticsearch_max_code_indexing_concurrency,omitempty" json:"elasticsearch_max_code_indexing_concurrency,omitempty"` + ElasticsearchNamespaceIDs *[]int `url:"elasticsearch_namespace_ids,omitempty" json:"elasticsearch_namespace_ids,omitempty"` + ElasticsearchPassword *string `url:"elasticsearch_password,omitempty" json:"elasticsearch_password,omitempty"` + ElasticsearchPauseIndexing *bool `url:"elasticsearch_pause_indexing,omitempty" json:"elasticsearch_pause_indexing,omitempty"` + ElasticsearchProjectIDs *[]int `url:"elasticsearch_project_ids,omitempty" json:"elasticsearch_project_ids,omitempty"` + ElasticsearchReplicas *int `url:"elasticsearch_replicas,omitempty" json:"elasticsearch_replicas,omitempty"` + ElasticsearchRequeueWorkers *bool `url:"elasticsearch_requeue_workers,omitempty" json:"elasticsearch_requeue_workers,omitempty"` + ElasticsearchSearch *bool `url:"elasticsearch_search,omitempty" json:"elasticsearch_search,omitempty"` + ElasticsearchShards *int `url:"elasticsearch_shards,omitempty" json:"elasticsearch_shards,omitempty"` + ElasticsearchURL *string `url:"elasticsearch_url,omitempty" json:"elasticsearch_url,omitempty"` + ElasticsearchUsername *string `url:"elasticsearch_username,omitempty" json:"elasticsearch_username,omitempty"` + ElasticsearchWorkerNumberOfShards *int `url:"elasticsearch_worker_number_of_shards,omitempty" json:"elasticsearch_worker_number_of_shards,omitempty"` + EmailAdditionalText *string `url:"email_additional_text,omitempty" json:"email_additional_text,omitempty"` + EmailAuthorInBody *bool `url:"email_author_in_body,omitempty" json:"email_author_in_body,omitempty"` + EmailConfirmationSetting *string `url:"email_confirmation_setting,omitempty" json:"email_confirmation_setting,omitempty"` + EmailRestrictions *string `url:"email_restrictions,omitempty" json:"email_restrictions,omitempty"` + EmailRestrictionsEnabled *bool `url:"email_restrictions_enabled,omitempty" json:"email_restrictions_enabled,omitempty"` + EnableArtifactExternalRedirectWarningPage *bool `url:"enable_artifact_external_redirect_warning_page,omitempty" json:"enable_artifact_external_redirect_warning_page,omitempty"` + EnabledGitAccessProtocol *string `url:"enabled_git_access_protocol,omitempty" json:"enabled_git_access_protocol,omitempty"` + EnforceNamespaceStorageLimit *bool `url:"enforce_namespace_storage_limit,omitempty" json:"enforce_namespace_storage_limit,omitempty"` + EnforcePATExpiration *bool `url:"enforce_pat_expiration,omitempty" json:"enforce_pat_expiration,omitempty"` + EnforceSSHKeyExpiration *bool `url:"enforce_ssh_key_expiration,omitempty" json:"enforce_ssh_key_expiration,omitempty"` + EnforceTerms *bool `url:"enforce_terms,omitempty" json:"enforce_terms,omitempty"` + ExternalAuthClientCert *string `url:"external_auth_client_cert,omitempty" json:"external_auth_client_cert,omitempty"` + ExternalAuthClientKey *string `url:"external_auth_client_key,omitempty" json:"external_auth_client_key,omitempty"` + ExternalAuthClientKeyPass *string `url:"external_auth_client_key_pass,omitempty" json:"external_auth_client_key_pass,omitempty"` + ExternalAuthorizationServiceDefaultLabel *string `url:"external_authorization_service_default_label,omitempty" json:"external_authorization_service_default_label,omitempty"` + ExternalAuthorizationServiceEnabled *bool `url:"external_authorization_service_enabled,omitempty" json:"external_authorization_service_enabled,omitempty"` + ExternalAuthorizationServiceTimeout *float64 `url:"external_authorization_service_timeout,omitempty" json:"external_authorization_service_timeout,omitempty"` + ExternalAuthorizationServiceURL *string `url:"external_authorization_service_url,omitempty" json:"external_authorization_service_url,omitempty"` + ExternalPipelineValidationServiceTimeout *int `url:"external_pipeline_validation_service_timeout,omitempty" json:"external_pipeline_validation_service_timeout,omitempty"` + ExternalPipelineValidationServiceToken *string `url:"external_pipeline_validation_service_token,omitempty" json:"external_pipeline_validation_service_token,omitempty"` + ExternalPipelineValidationServiceURL *string `url:"external_pipeline_validation_service_url,omitempty" json:"external_pipeline_validation_service_url,omitempty"` + FailedLoginAttemptsUnlockPeriodInMinutes *int `url:"failed_login_attempts_unlock_period_in_minutes,omitempty" json:"failed_login_attempts_unlock_period_in_minutes,omitempty"` + FileTemplateProjectID *int `url:"file_template_project_id,omitempty" json:"file_template_project_id,omitempty"` + FirstDayOfWeek *int `url:"first_day_of_week,omitempty" json:"first_day_of_week,omitempty"` + FlocEnabled *bool `url:"floc_enabled,omitempty" json:"floc_enabled,omitempty"` + GeoNodeAllowedIPs *string `url:"geo_node_allowed_ips,omitempty" json:"geo_node_allowed_ips,omitempty"` + GeoStatusTimeout *int `url:"geo_status_timeout,omitempty" json:"geo_status_timeout,omitempty"` + GitRateLimitUsersAlertlist *[]string `url:"git_rate_limit_users_alertlist,omitempty" json:"git_rate_limit_users_alertlist,omitempty"` + GitTwoFactorSessionExpiry *int `url:"git_two_factor_session_expiry,omitempty" json:"git_two_factor_session_expiry,omitempty"` + GitalyTimeoutDefault *int `url:"gitaly_timeout_default,omitempty" json:"gitaly_timeout_default,omitempty"` + GitalyTimeoutFast *int `url:"gitaly_timeout_fast,omitempty" json:"gitaly_timeout_fast,omitempty"` + GitalyTimeoutMedium *int `url:"gitaly_timeout_medium,omitempty" json:"gitaly_timeout_medium,omitempty"` + GitlabDedicatedInstance *bool `url:"gitlab_dedicated_instance,omitempty" json:"gitlab_dedicated_instance,omitempty"` + GitlabEnvironmentToolkitInstance *bool `url:"gitlab_environment_toolkit_instance,omitempty" json:"gitlab_environment_toolkit_instance,omitempty"` + GitlabShellOperationLimit *int `url:"gitlab_shell_operation_limit,omitempty" json:"gitlab_shell_operation_limit,omitempty"` + GitpodEnabled *bool `url:"gitpod_enabled,omitempty" json:"gitpod_enabled,omitempty"` + GitpodURL *string `url:"gitpod_url,omitempty" json:"gitpod_url,omitempty"` + GitRateLimitUsersAllowlist *[]string `url:"git_rate_limit_users_allowlist,omitempty" json:"git_rate_limit_users_allowlist,omitempty"` + GloballyAllowedIPs *string `url:"globally_allowed_ips,omitempty" json:"globally_allowed_ips,omitempty"` + GrafanaEnabled *bool `url:"grafana_enabled,omitempty" json:"grafana_enabled,omitempty"` + GrafanaURL *string `url:"grafana_url,omitempty" json:"grafana_url,omitempty"` + GravatarEnabled *bool `url:"gravatar_enabled,omitempty" json:"gravatar_enabled,omitempty"` + GroupDownloadExportLimit *int `url:"group_download_export_limit,omitempty" json:"group_download_export_limit,omitempty"` + GroupExportLimit *int `url:"group_export_limit,omitempty" json:"group_export_limit,omitempty"` + GroupImportLimit *int `url:"group_import_limit,omitempty" json:"group_import_limit,omitempty"` + GroupOwnersCanManageDefaultBranchProtection *bool `url:"group_owners_can_manage_default_branch_protection,omitempty" json:"group_owners_can_manage_default_branch_protection,omitempty"` + GroupRunnerTokenExpirationInterval *int `url:"group_runner_token_expiration_interval,omitempty" json:"group_runner_token_expiration_interval,omitempty"` + HTMLEmailsEnabled *bool `url:"html_emails_enabled,omitempty" json:"html_emails_enabled,omitempty"` + HashedStorageEnabled *bool `url:"hashed_storage_enabled,omitempty" json:"hashed_storage_enabled,omitempty"` + HelpPageDocumentationBaseURL *string `url:"help_page_documentation_base_url,omitempty" json:"help_page_documentation_base_url,omitempty"` + HelpPageHideCommercialContent *bool `url:"help_page_hide_commercial_content,omitempty" json:"help_page_hide_commercial_content,omitempty"` + HelpPageSupportURL *string `url:"help_page_support_url,omitempty" json:"help_page_support_url,omitempty"` + HelpPageText *string `url:"help_page_text,omitempty" json:"help_page_text,omitempty"` + HelpText *string `url:"help_text,omitempty" json:"help_text,omitempty"` + HideThirdPartyOffers *bool `url:"hide_third_party_offers,omitempty" json:"hide_third_party_offers,omitempty"` + HomePageURL *string `url:"home_page_url,omitempty" json:"home_page_url,omitempty"` + HousekeepingBitmapsEnabled *bool `url:"housekeeping_bitmaps_enabled,omitempty" json:"housekeeping_bitmaps_enabled,omitempty"` + HousekeepingEnabled *bool `url:"housekeeping_enabled,omitempty" json:"housekeeping_enabled,omitempty"` + HousekeepingFullRepackPeriod *int `url:"housekeeping_full_repack_period,omitempty" json:"housekeeping_full_repack_period,omitempty"` + HousekeepingGcPeriod *int `url:"housekeeping_gc_period,omitempty" json:"housekeeping_gc_period,omitempty"` + HousekeepingIncrementalRepackPeriod *int `url:"housekeeping_incremental_repack_period,omitempty" json:"housekeeping_incremental_repack_period,omitempty"` + HousekeepingOptimizeRepositoryPeriod *int `url:"housekeeping_optimize_repository_period,omitempty" json:"housekeeping_optimize_repository_period,omitempty"` + ImportSources *[]string `url:"import_sources,omitempty" json:"import_sources,omitempty"` + InactiveProjectsDeleteAfterMonths *int `url:"inactive_projects_delete_after_months,omitempty" json:"inactive_projects_delete_after_months,omitempty"` + InactiveProjectsMinSizeMB *int `url:"inactive_projects_min_size_mb,omitempty" json:"inactive_projects_min_size_mb,omitempty"` + InactiveProjectsSendWarningEmailAfterMonths *int `url:"inactive_projects_send_warning_email_after_months,omitempty" json:"inactive_projects_send_warning_email_after_months,omitempty"` + IncludeOptionalMetricsInServicePing *bool `url:"include_optional_metrics_in_service_ping,omitempty" json:"include_optional_metrics_in_service_ping,omitempty"` + InProductMarketingEmailsEnabled *bool `url:"in_product_marketing_emails_enabled,omitempty" json:"in_product_marketing_emails_enabled,omitempty"` + InvisibleCaptchaEnabled *bool `url:"invisible_captcha_enabled,omitempty" json:"invisible_captcha_enabled,omitempty"` + IssuesCreateLimit *int `url:"issues_create_limit,omitempty" json:"issues_create_limit,omitempty"` + JiraConnectApplicationKey *string `url:"jira_connect_application_key,omitempty" json:"jira_connect_application_key,omitempty"` + JiraConnectPublicKeyStorageEnabled *bool `url:"jira_connect_public_key_storage_enabled,omitempty" json:"jira_connect_public_key_storage_enabled,omitempty"` + JiraConnectProxyURL *string `url:"jira_connect_proxy_url,omitempty" json:"jira_connect_proxy_url,omitempty"` + KeepLatestArtifact *bool `url:"keep_latest_artifact,omitempty" json:"keep_latest_artifact,omitempty"` + KrokiEnabled *bool `url:"kroki_enabled,omitempty" json:"kroki_enabled,omitempty"` + KrokiFormats *map[string]bool `url:"kroki_formats,omitempty" json:"kroki_formats,omitempty"` + KrokiURL *string `url:"kroki_url,omitempty" json:"kroki_url,omitempty"` + LocalMarkdownVersion *int `url:"local_markdown_version,omitempty" json:"local_markdown_version,omitempty"` + LockDuoFeaturesEnabled *bool `url:"lock_duo_features_enabled,omitempty" json:"lock_duo_features_enabled,omitempty"` + LockMembershipsToLDAP *bool `url:"lock_memberships_to_ldap,omitempty" json:"lock_memberships_to_ldap,omitempty"` + LoginRecaptchaProtectionEnabled *bool `url:"login_recaptcha_protection_enabled,omitempty" json:"login_recaptcha_protection_enabled,omitempty"` + MailgunEventsEnabled *bool `url:"mailgun_events_enabled,omitempty" json:"mailgun_events_enabled,omitempty"` + MailgunSigningKey *string `url:"mailgun_signing_key,omitempty" json:"mailgun_signing_key,omitempty"` + MaintenanceMode *bool `url:"maintenance_mode,omitempty" json:"maintenance_mode,omitempty"` + MaintenanceModeMessage *string `url:"maintenance_mode_message,omitempty" json:"maintenance_mode_message,omitempty"` + MavenPackageRequestsForwarding *bool `url:"maven_package_requests_forwarding,omitempty" json:"maven_package_requests_forwarding,omitempty"` + MaxArtifactsSize *int `url:"max_artifacts_size,omitempty" json:"max_artifacts_size,omitempty"` + MaxAttachmentSize *int `url:"max_attachment_size,omitempty" json:"max_attachment_size,omitempty"` + MaxDecompressedArchiveSize *int `url:"max_decompressed_archive_size,omitempty" json:"max_decompressed_archive_size,omitempty"` + MaxExportSize *int `url:"max_export_size,omitempty" json:"max_export_size,omitempty"` + MaxImportRemoteFileSize *int `url:"max_import_remote_file_size,omitempty" json:"max_import_remote_file_size,omitempty"` + MaxImportSize *int `url:"max_import_size,omitempty" json:"max_import_size,omitempty"` + MaxLoginAttempts *int `url:"max_login_attempts,omitempty" json:"max_login_attempts,omitempty"` + MaxNumberOfRepositoryDownloads *int `url:"max_number_of_repository_downloads,omitempty" json:"max_number_of_repository_downloads,omitempty"` + MaxNumberOfRepositoryDownloadsWithinTimePeriod *int `url:"max_number_of_repository_downloads_within_time_period,omitempty" json:"max_number_of_repository_downloads_within_time_period,omitempty"` + MaxPagesSize *int `url:"max_pages_size,omitempty" json:"max_pages_size,omitempty"` + MaxPersonalAccessTokenLifetime *int `url:"max_personal_access_token_lifetime,omitempty" json:"max_personal_access_token_lifetime,omitempty"` + MaxSSHKeyLifetime *int `url:"max_ssh_key_lifetime,omitempty" json:"max_ssh_key_lifetime,omitempty"` + MaxTerraformStateSizeBytes *int `url:"max_terraform_state_size_bytes,omitempty" json:"max_terraform_state_size_bytes,omitempty"` + MaxYAMLDepth *int `url:"max_yaml_depth,omitempty" json:"max_yaml_depth,omitempty"` + MaxYAMLSizeBytes *int `url:"max_yaml_size_bytes,omitempty" json:"max_yaml_size_bytes,omitempty"` + MetricsMethodCallThreshold *int `url:"metrics_method_call_threshold,omitempty" json:"metrics_method_call_threshold,omitempty"` + MinimumPasswordLength *int `url:"minimum_password_length,omitempty" json:"minimum_password_length,omitempty"` + MirrorAvailable *bool `url:"mirror_available,omitempty" json:"mirror_available,omitempty"` + MirrorCapacityThreshold *int `url:"mirror_capacity_threshold,omitempty" json:"mirror_capacity_threshold,omitempty"` + MirrorMaxCapacity *int `url:"mirror_max_capacity,omitempty" json:"mirror_max_capacity,omitempty"` + MirrorMaxDelay *int `url:"mirror_max_delay,omitempty" json:"mirror_max_delay,omitempty"` + NPMPackageRequestsForwarding *bool `url:"npm_package_requests_forwarding,omitempty" json:"npm_package_requests_forwarding,omitempty"` + NotesCreateLimit *int `url:"notes_create_limit,omitempty" json:"notes_create_limit,omitempty"` + NotifyOnUnknownSignIn *bool `url:"notify_on_unknown_sign_in,omitempty" json:"notify_on_unknown_sign_in,omitempty"` + NugetSkipMetadataURLValidation *bool `url:"nuget_skip_metadata_url_validation,omitempty" json:"nuget_skip_metadata_url_validation,omitempty"` + OutboundLocalRequestsAllowlistRaw *string `url:"outbound_local_requests_allowlist_raw,omitempty" json:"outbound_local_requests_allowlist_raw,omitempty"` + OutboundLocalRequestsWhitelist *[]string `url:"outbound_local_requests_whitelist,omitempty" json:"outbound_local_requests_whitelist,omitempty"` + PackageMetadataPURLTypes *[]int `url:"package_metadata_purl_types,omitempty" json:"package_metadata_purl_types,omitempty"` + PackageRegistryAllowAnyoneToPullOption *bool `url:"package_registry_allow_anyone_to_pull_option,omitempty" json:"package_registry_allow_anyone_to_pull_option,omitempty"` + PackageRegistryCleanupPoliciesWorkerCapacity *int `url:"package_registry_cleanup_policies_worker_capacity,omitempty" json:"package_registry_cleanup_policies_worker_capacity,omitempty"` + PagesDomainVerificationEnabled *bool `url:"pages_domain_verification_enabled,omitempty" json:"pages_domain_verification_enabled,omitempty"` + PasswordAuthenticationEnabledForGit *bool `url:"password_authentication_enabled_for_git,omitempty" json:"password_authentication_enabled_for_git,omitempty"` + PasswordAuthenticationEnabledForWeb *bool `url:"password_authentication_enabled_for_web,omitempty" json:"password_authentication_enabled_for_web,omitempty"` + PasswordNumberRequired *bool `url:"password_number_required,omitempty" json:"password_number_required,omitempty"` + PasswordSymbolRequired *bool `url:"password_symbol_required,omitempty" json:"password_symbol_required,omitempty"` + PasswordUppercaseRequired *bool `url:"password_uppercase_required,omitempty" json:"password_uppercase_required,omitempty"` + PasswordLowercaseRequired *bool `url:"password_lowercase_required,omitempty" json:"password_lowercase_required,omitempty"` + PerformanceBarAllowedGroupID *int `url:"performance_bar_allowed_group_id,omitempty" json:"performance_bar_allowed_group_id,omitempty"` + PerformanceBarAllowedGroupPath *string `url:"performance_bar_allowed_group_path,omitempty" json:"performance_bar_allowed_group_path,omitempty"` + PerformanceBarEnabled *bool `url:"performance_bar_enabled,omitempty" json:"performance_bar_enabled,omitempty"` + PersonalAccessTokenPrefix *string `url:"personal_access_token_prefix,omitempty" json:"personal_access_token_prefix,omitempty"` + PlantumlEnabled *bool `url:"plantuml_enabled,omitempty" json:"plantuml_enabled,omitempty"` + PlantumlURL *string `url:"plantuml_url,omitempty" json:"plantuml_url,omitempty"` + PipelineLimitPerProjectUserSha *int `url:"pipeline_limit_per_project_user_sha,omitempty" json:"pipeline_limit_per_project_user_sha,omitempty"` + PollingIntervalMultiplier *float64 `url:"polling_interval_multiplier,omitempty" json:"polling_interval_multiplier,omitempty"` + PreventMergeRequestsAuthorApproval *bool `url:"prevent_merge_requests_author_approval,omitempty" json:"prevent_merge_requests_author_approval,omitempty"` + PreventMergeRequestsCommittersApproval *bool `url:"prevent_merge_requests_committers_approval,omitempty" json:"prevent_merge_requests_committers_approval,omitempty"` + ProjectDownloadExportLimit *int `url:"project_download_export_limit,omitempty" json:"project_download_export_limit,omitempty"` + ProjectExportEnabled *bool `url:"project_export_enabled,omitempty" json:"project_export_enabled,omitempty"` + ProjectExportLimit *int `url:"project_export_limit,omitempty" json:"project_export_limit,omitempty"` + ProjectImportLimit *int `url:"project_import_limit,omitempty" json:"project_import_limit,omitempty"` + ProjectJobsAPIRateLimit *int `url:"project_jobs_api_rate_limit,omitempty" json:"project_jobs_api_rate_limit,omitempty"` + ProjectRunnerTokenExpirationInterval *int `url:"project_runner_token_expiration_interval,omitempty" json:"project_runner_token_expiration_interval,omitempty"` + ProjectsAPIRateLimitUnauthenticated *int `url:"projects_api_rate_limit_unauthenticated,omitempty" json:"projects_api_rate_limit_unauthenticated,omitempty"` + PrometheusMetricsEnabled *bool `url:"prometheus_metrics_enabled,omitempty" json:"prometheus_metrics_enabled,omitempty"` + ProtectedCIVariables *bool `url:"protected_ci_variables,omitempty" json:"protected_ci_variables,omitempty"` + PseudonymizerEnabled *bool `url:"pseudonymizer_enabled,omitempty" json:"pseudonymizer_enabled,omitempty"` + PushEventActivitiesLimit *int `url:"push_event_activities_limit,omitempty" json:"push_event_activities_limit,omitempty"` + PushEventHooksLimit *int `url:"push_event_hooks_limit,omitempty" json:"push_event_hooks_limit,omitempty"` + PyPIPackageRequestsForwarding *bool `url:"pypi_package_requests_forwarding,omitempty" json:"pypi_package_requests_forwarding,omitempty"` + RSAKeyRestriction *int `url:"rsa_key_restriction,omitempty" json:"rsa_key_restriction,omitempty"` + RateLimitingResponseText *string `url:"rate_limiting_response_text,omitempty" json:"rate_limiting_response_text,omitempty"` + RawBlobRequestLimit *int `url:"raw_blob_request_limit,omitempty" json:"raw_blob_request_limit,omitempty"` + RecaptchaEnabled *bool `url:"recaptcha_enabled,omitempty" json:"recaptcha_enabled,omitempty"` + RecaptchaPrivateKey *string `url:"recaptcha_private_key,omitempty" json:"recaptcha_private_key,omitempty"` + RecaptchaSiteKey *string `url:"recaptcha_site_key,omitempty" json:"recaptcha_site_key,omitempty"` + ReceiveMaxInputSize *int `url:"receive_max_input_size,omitempty" json:"receive_max_input_size,omitempty"` + ReceptiveClusterAgentsEnabled *bool `url:"receptive_cluster_agents_enabled,omitempty" json:"receptive_cluster_agents_enabled,omitempty"` + RememberMeEnabled *bool `url:"remember_me_enabled,omitempty" json:"remember_me_enabled,omitempty"` + RepositoryChecksEnabled *bool `url:"repository_checks_enabled,omitempty" json:"repository_checks_enabled,omitempty"` + RepositorySizeLimit *int `url:"repository_size_limit,omitempty" json:"repository_size_limit,omitempty"` + RepositoryStorages *[]string `url:"repository_storages,omitempty" json:"repository_storages,omitempty"` + RepositoryStoragesWeighted *map[string]int `url:"repository_storages_weighted,omitempty" json:"repository_storages_weighted,omitempty"` + RequireAdminApprovalAfterUserSignup *bool `url:"require_admin_approval_after_user_signup,omitempty" json:"require_admin_approval_after_user_signup,omitempty"` + RequireAdminTwoFactorAuthentication *bool `url:"require_admin_two_factor_authentication,omitempty" json:"require_admin_two_factor_authentication,omitempty"` + RequirePersonalAccessTokenExpiry *bool `url:"require_personal_access_token_expiry,omitempty" json:"require_personal_access_token_expiry,omitempty"` + RequireTwoFactorAuthentication *bool `url:"require_two_factor_authentication,omitempty" json:"require_two_factor_authentication,omitempty"` + RestrictedVisibilityLevels *[]VisibilityValue `url:"restricted_visibility_levels,omitempty" json:"restricted_visibility_levels,omitempty"` + RunnerTokenExpirationInterval *int `url:"runner_token_expiration_interval,omitempty" json:"runner_token_expiration_interval,omitempty"` + SearchRateLimit *int `url:"search_rate_limit,omitempty" json:"search_rate_limit,omitempty"` + SearchRateLimitUnauthenticated *int `url:"search_rate_limit_unauthenticated,omitempty" json:"search_rate_limit_unauthenticated,omitempty"` + SecretDetectionRevocationTokenTypesURL *string `url:"secret_detection_revocation_token_types_url,omitempty" json:"secret_detection_revocation_token_types_url,omitempty"` + SecretDetectionTokenRevocationEnabled *bool `url:"secret_detection_token_revocation_enabled,omitempty" json:"secret_detection_token_revocation_enabled,omitempty"` + SecretDetectionTokenRevocationToken *string `url:"secret_detection_token_revocation_token,omitempty" json:"secret_detection_token_revocation_token,omitempty"` + SecretDetectionTokenRevocationURL *string `url:"secret_detection_token_revocation_url,omitempty" json:"secret_detection_token_revocation_url,omitempty"` + SecurityApprovalPoliciesLimit *int `url:"security_approval_policies_limit,omitempty" json:"security_approval_policies_limit,omitempty"` + SecurityPolicyGlobalGroupApproversEnabled *bool `url:"security_policy_global_group_approvers_enabled,omitempty" json:"security_policy_global_group_approvers_enabled,omitempty"` + SecurityTXTContent *string `url:"security_txt_content,omitempty" json:"security_txt_content,omitempty"` + SendUserConfirmationEmail *bool `url:"send_user_confirmation_email,omitempty" json:"send_user_confirmation_email,omitempty"` + SentryClientsideDSN *string `url:"sentry_clientside_dsn,omitempty" json:"sentry_clientside_dsn,omitempty"` + SentryDSN *string `url:"sentry_dsn,omitempty" json:"sentry_dsn,omitempty"` + SentryEnabled *string `url:"sentry_enabled,omitempty" json:"sentry_enabled,omitempty"` + SentryEnvironment *string `url:"sentry_environment,omitempty" json:"sentry_environment,omitempty"` + ServiceAccessTokensExpirationEnforced *bool `url:"service_access_tokens_expiration_enforced,omitempty" json:"service_access_tokens_expiration_enforced,omitempty"` + SessionExpireDelay *int `url:"session_expire_delay,omitempty" json:"session_expire_delay,omitempty"` + SharedRunnersEnabled *bool `url:"shared_runners_enabled,omitempty" json:"shared_runners_enabled,omitempty"` + SharedRunnersMinutes *int `url:"shared_runners_minutes,omitempty" json:"shared_runners_minutes,omitempty"` + SharedRunnersText *string `url:"shared_runners_text,omitempty" json:"shared_runners_text,omitempty"` + SidekiqJobLimiterCompressionThresholdBytes *int `url:"sidekiq_job_limiter_compression_threshold_bytes,omitempty" json:"sidekiq_job_limiter_compression_threshold_bytes,omitempty"` + SidekiqJobLimiterLimitBytes *int `url:"sidekiq_job_limiter_limit_bytes,omitempty" json:"sidekiq_job_limiter_limit_bytes,omitempty"` + SidekiqJobLimiterMode *string `url:"sidekiq_job_limiter_mode,omitempty" json:"sidekiq_job_limiter_mode,omitempty"` + SignInText *string `url:"sign_in_text,omitempty" json:"sign_in_text,omitempty"` + SignupEnabled *bool `url:"signup_enabled,omitempty" json:"signup_enabled,omitempty"` + SilentAdminExportsEnabled *bool `url:"silent_admin_exports_enabled,omitempty" json:"silent_admin_exports_enabled,omitempty"` + SilentModeEnabled *bool `url:"silent_mode_enabled,omitempty" json:"silent_mode_enabled,omitempty"` + SlackAppEnabled *bool `url:"slack_app_enabled,omitempty" json:"slack_app_enabled,omitempty"` + SlackAppID *string `url:"slack_app_id,omitempty" json:"slack_app_id,omitempty"` + SlackAppSecret *string `url:"slack_app_secret,omitempty" json:"slack_app_secret,omitempty"` + SlackAppSigningSecret *string `url:"slack_app_signing_secret,omitempty" json:"slack_app_signing_secret,omitempty"` + SlackAppVerificationToken *string `url:"slack_app_verification_token,omitempty" json:"slack_app_verification_token,omitempty"` + SnippetSizeLimit *int `url:"snippet_size_limit,omitempty" json:"snippet_size_limit,omitempty"` + SnowplowAppID *string `url:"snowplow_app_id,omitempty" json:"snowplow_app_id,omitempty"` + SnowplowCollectorHostname *string `url:"snowplow_collector_hostname,omitempty" json:"snowplow_collector_hostname,omitempty"` + SnowplowCookieDomain *string `url:"snowplow_cookie_domain,omitempty" json:"snowplow_cookie_domain,omitempty"` + SnowplowDatabaseCollectorHostname *string `url:"snowplow_database_collector_hostname,omitempty" json:"snowplow_database_collector_hostname,omitempty"` + SnowplowEnabled *bool `url:"snowplow_enabled,omitempty" json:"snowplow_enabled,omitempty"` + SourcegraphEnabled *bool `url:"sourcegraph_enabled,omitempty" json:"sourcegraph_enabled,omitempty"` + SourcegraphPublicOnly *bool `url:"sourcegraph_public_only,omitempty" json:"sourcegraph_public_only,omitempty"` + SourcegraphURL *string `url:"sourcegraph_url,omitempty" json:"sourcegraph_url,omitempty"` + SpamCheckAPIKey *string `url:"spam_check_api_key,omitempty" json:"spam_check_api_key,omitempty"` + SpamCheckEndpointEnabled *bool `url:"spam_check_endpoint_enabled,omitempty" json:"spam_check_endpoint_enabled,omitempty"` + SpamCheckEndpointURL *string `url:"spam_check_endpoint_url,omitempty" json:"spam_check_endpoint_url,omitempty"` + StaticObjectsExternalStorageAuthToken *string `url:"static_objects_external_storage_auth_token,omitempty" json:"static_objects_external_storage_auth_token,omitempty"` + StaticObjectsExternalStorageURL *string `url:"static_objects_external_storage_url,omitempty" json:"static_objects_external_storage_url,omitempty"` + SuggestPipelineEnabled *bool `url:"suggest_pipeline_enabled,omitempty" json:"suggest_pipeline_enabled,omitempty"` + TerminalMaxSessionTime *int `url:"terminal_max_session_time,omitempty" json:"terminal_max_session_time,omitempty"` + Terms *string `url:"terms,omitempty" json:"terms,omitempty"` + ThrottleAuthenticatedAPIEnabled *bool `url:"throttle_authenticated_api_enabled,omitempty" json:"throttle_authenticated_api_enabled,omitempty"` + ThrottleAuthenticatedAPIPeriodInSeconds *int `url:"throttle_authenticated_api_period_in_seconds,omitempty" json:"throttle_authenticated_api_period_in_seconds,omitempty"` + ThrottleAuthenticatedAPIRequestsPerPeriod *int `url:"throttle_authenticated_api_requests_per_period,omitempty" json:"throttle_authenticated_api_requests_per_period,omitempty"` + ThrottleAuthenticatedDeprecatedAPIEnabled *bool `url:"throttle_authenticated_deprecated_api_enabled,omitempty" json:"throttle_authenticated_deprecated_api_enabled,omitempty"` + ThrottleAuthenticatedDeprecatedAPIPeriodInSeconds *int `url:"throttle_authenticated_deprecated_api_period_in_seconds,omitempty" json:"throttle_authenticated_deprecated_api_period_in_seconds,omitempty"` + ThrottleAuthenticatedDeprecatedAPIRequestsPerPeriod *int `url:"throttle_authenticated_deprecated_api_requests_per_period,omitempty" json:"throttle_authenticated_deprecated_api_requests_per_period,omitempty"` + ThrottleAuthenticatedFilesAPIEnabled *bool `url:"throttle_authenticated_files_api_enabled,omitempty" json:"throttle_authenticated_files_api_enabled,omitempty"` + ThrottleAuthenticatedFilesAPIPeriodInSeconds *int `url:"throttle_authenticated_files_api_period_in_seconds,omitempty" json:"throttle_authenticated_files_api_period_in_seconds,omitempty"` + ThrottleAuthenticatedFilesAPIRequestsPerPeriod *int `url:"throttle_authenticated_files_api_requests_per_period,omitempty" json:"throttle_authenticated_files_api_requests_per_period,omitempty"` + ThrottleAuthenticatedGitLFSEnabled *bool `url:"throttle_authenticated_git_lfs_enabled,omitempty" json:"throttle_authenticated_git_lfs_enabled,omitempty"` + ThrottleAuthenticatedGitLFSPeriodInSeconds *int `url:"throttle_authenticated_git_lfs_period_in_seconds,omitempty" json:"throttle_authenticated_git_lfs_period_in_seconds,omitempty"` + ThrottleAuthenticatedGitLFSRequestsPerPeriod *int `url:"throttle_authenticated_git_lfs_requests_per_period,omitempty" json:"throttle_authenticated_git_lfs_requests_per_period,omitempty"` + ThrottleAuthenticatedPackagesAPIEnabled *bool `url:"throttle_authenticated_packages_api_enabled,omitempty" json:"throttle_authenticated_packages_api_enabled,omitempty"` + ThrottleAuthenticatedPackagesAPIPeriodInSeconds *int `url:"throttle_authenticated_packages_api_period_in_seconds,omitempty" json:"throttle_authenticated_packages_api_period_in_seconds,omitempty"` + ThrottleAuthenticatedPackagesAPIRequestsPerPeriod *int `url:"throttle_authenticated_packages_api_requests_per_period,omitempty" json:"throttle_authenticated_packages_api_requests_per_period,omitempty"` + ThrottleAuthenticatedWebEnabled *bool `url:"throttle_authenticated_web_enabled,omitempty" json:"throttle_authenticated_web_enabled,omitempty"` + ThrottleAuthenticatedWebPeriodInSeconds *int `url:"throttle_authenticated_web_period_in_seconds,omitempty" json:"throttle_authenticated_web_period_in_seconds,omitempty"` + ThrottleAuthenticatedWebRequestsPerPeriod *int `url:"throttle_authenticated_web_requests_per_period,omitempty" json:"throttle_authenticated_web_requests_per_period,omitempty"` + ThrottleIncidentManagementNotificationEnabled *bool `url:"throttle_incident_management_notification_enabled,omitempty" json:"throttle_incident_management_notification_enabled,omitempty"` + ThrottleIncidentManagementNotificationPerPeriod *int `url:"throttle_incident_management_notification_per_period,omitempty" json:"throttle_incident_management_notification_per_period,omitempty"` + ThrottleIncidentManagementNotificationPeriodInSeconds *int `url:"throttle_incident_management_notification_period_in_seconds,omitempty" json:"throttle_incident_management_notification_period_in_seconds,omitempty"` + ThrottleProtectedPathsEnabled *bool `url:"throttle_protected_paths_enabled_enabled,omitempty" json:"throttle_protected_paths_enabled,omitempty"` + ThrottleProtectedPathsPeriodInSeconds *int `url:"throttle_protected_paths_enabled_period_in_seconds,omitempty" json:"throttle_protected_paths_period_in_seconds,omitempty"` + ThrottleProtectedPathsRequestsPerPeriod *int `url:"throttle_protected_paths_enabled_requests_per_period,omitempty" json:"throttle_protected_paths_per_period,omitempty"` + ThrottleUnauthenticatedAPIEnabled *bool `url:"throttle_unauthenticated_api_enabled,omitempty" json:"throttle_unauthenticated_api_enabled,omitempty"` + ThrottleUnauthenticatedAPIPeriodInSeconds *int `url:"throttle_unauthenticated_api_period_in_seconds,omitempty" json:"throttle_unauthenticated_api_period_in_seconds,omitempty"` + ThrottleUnauthenticatedAPIRequestsPerPeriod *int `url:"throttle_unauthenticated_api_requests_per_period,omitempty" json:"throttle_unauthenticated_api_requests_per_period,omitempty"` + ThrottleUnauthenticatedDeprecatedAPIEnabled *bool `url:"throttle_unauthenticated_deprecated_api_enabled,omitempty" json:"throttle_unauthenticated_deprecated_api_enabled,omitempty"` + ThrottleUnauthenticatedDeprecatedAPIPeriodInSeconds *int `url:"throttle_unauthenticated_deprecated_api_period_in_seconds,omitempty" json:"throttle_unauthenticated_deprecated_api_period_in_seconds,omitempty"` + ThrottleUnauthenticatedDeprecatedAPIRequestsPerPeriod *int `url:"throttle_unauthenticated_deprecated_api_requests_per_period,omitempty" json:"throttle_unauthenticated_deprecated_api_requests_per_period,omitempty"` + ThrottleUnauthenticatedEnabled *bool `url:"throttle_unauthenticated_enabled,omitempty" json:"throttle_unauthenticated_enabled,omitempty"` + ThrottleUnauthenticatedFilesAPIEnabled *bool `url:"throttle_unauthenticated_files_api_enabled,omitempty" json:"throttle_unauthenticated_files_api_enabled,omitempty"` + ThrottleUnauthenticatedFilesAPIPeriodInSeconds *int `url:"throttle_unauthenticated_files_api_period_in_seconds,omitempty" json:"throttle_unauthenticated_files_api_period_in_seconds,omitempty"` + ThrottleUnauthenticatedFilesAPIRequestsPerPeriod *int `url:"throttle_unauthenticated_files_api_requests_per_period,omitempty" json:"throttle_unauthenticated_files_api_requests_per_period,omitempty"` + ThrottleUnauthenticatedGitLFSEnabled *bool `url:"throttle_unauthenticated_git_lfs_enabled,omitempty" json:"throttle_unauthenticated_git_lfs_enabled,omitempty"` + ThrottleUnauthenticatedGitLFSPeriodInSeconds *int `url:"throttle_unauthenticated_git_lfs_period_in_seconds,omitempty" json:"throttle_unauthenticated_git_lfs_period_in_seconds,omitempty"` + ThrottleUnauthenticatedGitLFSRequestsPerPeriod *int `url:"throttle_unauthenticated_git_lfs_requests_per_period,omitempty" json:"throttle_unauthenticated_git_lfs_requests_per_period,omitempty"` + ThrottleUnauthenticatedPackagesAPIEnabled *bool `url:"throttle_unauthenticated_packages_api_enabled,omitempty" json:"throttle_unauthenticated_packages_api_enabled,omitempty"` + ThrottleUnauthenticatedPackagesAPIPeriodInSeconds *int `url:"throttle_unauthenticated_packages_api_period_in_seconds,omitempty" json:"throttle_unauthenticated_packages_api_period_in_seconds,omitempty"` + ThrottleUnauthenticatedPackagesAPIRequestsPerPeriod *int `url:"throttle_unauthenticated_packages_api_requests_per_period,omitempty" json:"throttle_unauthenticated_packages_api_requests_per_period,omitempty"` + ThrottleUnauthenticatedPeriodInSeconds *int `url:"throttle_unauthenticated_period_in_seconds,omitempty" json:"throttle_unauthenticated_period_in_seconds,omitempty"` + ThrottleUnauthenticatedRequestsPerPeriod *int `url:"throttle_unauthenticated_requests_per_period,omitempty" json:"throttle_unauthenticated_requests_per_period,omitempty"` + ThrottleUnauthenticatedWebEnabled *bool `url:"throttle_unauthenticated_web_enabled,omitempty" json:"throttle_unauthenticated_web_enabled,omitempty"` + ThrottleUnauthenticatedWebPeriodInSeconds *int `url:"throttle_unauthenticated_web_period_in_seconds,omitempty" json:"throttle_unauthenticated_web_period_in_seconds,omitempty"` + ThrottleUnauthenticatedWebRequestsPerPeriod *int `url:"throttle_unauthenticated_web_requests_per_period,omitempty" json:"throttle_unauthenticated_web_requests_per_period,omitempty"` + TimeTrackingLimitToHours *bool `url:"time_tracking_limit_to_hours,omitempty" json:"time_tracking_limit_to_hours,omitempty"` + TwoFactorGracePeriod *int `url:"two_factor_grace_period,omitempty" json:"two_factor_grace_period,omitempty"` + UnconfirmedUsersDeleteAfterDays *int `url:"unconfirmed_users_delete_after_days,omitempty" json:"unconfirmed_users_delete_after_days,omitempty"` + UniqueIPsLimitEnabled *bool `url:"unique_ips_limit_enabled,omitempty" json:"unique_ips_limit_enabled,omitempty"` + UniqueIPsLimitPerUser *int `url:"unique_ips_limit_per_user,omitempty" json:"unique_ips_limit_per_user,omitempty"` + UniqueIPsLimitTimeWindow *int `url:"unique_ips_limit_time_window,omitempty" json:"unique_ips_limit_time_window,omitempty"` + UpdateRunnerVersionsEnabled *bool `url:"update_runner_versions_enabled,omitempty" json:"update_runner_versions_enabled,omitempty"` + UpdatingNameDisabledForUsers *bool `url:"updating_name_disabled_for_users,omitempty" json:"updating_name_disabled_for_users,omitempty"` + UsagePingEnabled *bool `url:"usage_ping_enabled,omitempty" json:"usage_ping_enabled,omitempty"` + UsagePingFeaturesEnabled *bool `url:"usage_ping_features_enabled,omitempty" json:"usage_ping_features_enabled,omitempty"` + UseClickhouseForAnalytics *bool `url:"use_clickhouse_for_analytics,omitempty" json:"use_clickhouse_for_analytics,omitempty"` + UserDeactivationEmailsEnabled *bool `url:"user_deactivation_emails_enabled,omitempty" json:"user_deactivation_emails_enabled,omitempty"` + UserDefaultExternal *bool `url:"user_default_external,omitempty" json:"user_default_external,omitempty"` + UserDefaultInternalRegex *string `url:"user_default_internal_regex,omitempty" json:"user_default_internal_regex,omitempty"` + UserDefaultsToPrivateProfile *bool `url:"user_defaults_to_private_profile,omitempty" json:"user_defaults_to_private_profile,omitempty"` + UserEmailLookupLimit *int `url:"user_email_lookup_limit,omitempty" json:"user_email_lookup_limit,omitempty"` + UserOauthApplications *bool `url:"user_oauth_applications,omitempty" json:"user_oauth_applications,omitempty"` + UserShowAddSSHKeyMessage *bool `url:"user_show_add_ssh_key_message,omitempty" json:"user_show_add_ssh_key_message,omitempty"` + UsersGetByIDLimit *int `url:"users_get_by_id_limit,omitempty" json:"users_get_by_id_limit,omitempty"` + UsersGetByIDLimitAllowlistRaw *string `url:"users_get_by_id_limit_allowlist_raw,omitempty" json:"users_get_by_id_limit_allowlist_raw,omitempty"` + ValidRunnerRegistrars *[]string `url:"valid_runner_registrars,omitempty" json:"valid_runner_registrars,omitempty"` + VersionCheckEnabled *bool `url:"version_check_enabled,omitempty" json:"version_check_enabled,omitempty"` + WebIDEClientsidePreviewEnabled *bool `url:"web_ide_clientside_preview_enabled,omitempty" json:"web_ide_clientside_preview_enabled,omitempty"` + WhatsNewVariant *string `url:"whats_new_variant,omitempty" json:"whats_new_variant,omitempty"` + WikiPageMaxContentBytes *int `url:"wiki_page_max_content_bytes,omitempty" json:"wiki_page_max_content_bytes,omitempty"` +} + +// BranchProtectionDefaultsOptions represents default Git protected branch permissions options. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/groups.html#options-for-default_branch_protection_defaults +type BranchProtectionDefaultsOptions struct { + AllowedToPush *[]int `url:"allowed_to_push,omitempty" json:"allowed_to_push,omitempty"` + AllowForcePush *bool `url:"allow_force_push,omitempty" json:"allow_force_push,omitempty"` + AllowedToMerge *[]int `url:"allowed_to_merge,omitempty" json:"allowed_to_merge,omitempty"` + DeveloperCanInitialPush *bool `url:"developer_can_initial_push,omitempty" json:"developer_can_initial_push,omitempty"` +} + +// UpdateSettings updates the application settings. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/settings.html#change-application-settings +func (s *SettingsService) UpdateSettings(opt *UpdateSettingsOptions, options ...RequestOptionFunc) (*Settings, *Response, error) { + req, err := s.client.NewRequest(http.MethodPut, "application/settings", opt, options) + if err != nil { + return nil, nil, err + } + + as := new(Settings) + resp, err := s.client.Do(req, as) + if err != nil { + return nil, resp, err + } + + return as, resp, nil +} diff --git a/vendor/github.com/xanzy/go-gitlab/sidekiq_metrics.go b/vendor/gitlab.com/gitlab-org/api/client-go/sidekiq_metrics.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/sidekiq_metrics.go rename to vendor/gitlab.com/gitlab-org/api/client-go/sidekiq_metrics.go diff --git a/vendor/github.com/xanzy/go-gitlab/snippet_repository_storage_move.go b/vendor/gitlab.com/gitlab-org/api/client-go/snippet_repository_storage_move.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/snippet_repository_storage_move.go rename to vendor/gitlab.com/gitlab-org/api/client-go/snippet_repository_storage_move.go diff --git a/vendor/github.com/xanzy/go-gitlab/snippets.go b/vendor/gitlab.com/gitlab-org/api/client-go/snippets.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/snippets.go rename to vendor/gitlab.com/gitlab-org/api/client-go/snippets.go diff --git a/vendor/github.com/xanzy/go-gitlab/strings.go b/vendor/gitlab.com/gitlab-org/api/client-go/strings.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/strings.go rename to vendor/gitlab.com/gitlab-org/api/client-go/strings.go diff --git a/vendor/github.com/xanzy/go-gitlab/system_hooks.go b/vendor/gitlab.com/gitlab-org/api/client-go/system_hooks.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/system_hooks.go rename to vendor/gitlab.com/gitlab-org/api/client-go/system_hooks.go diff --git a/vendor/github.com/xanzy/go-gitlab/tags.go b/vendor/gitlab.com/gitlab-org/api/client-go/tags.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/tags.go rename to vendor/gitlab.com/gitlab-org/api/client-go/tags.go diff --git a/vendor/github.com/xanzy/go-gitlab/time_stats.go b/vendor/gitlab.com/gitlab-org/api/client-go/time_stats.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/time_stats.go rename to vendor/gitlab.com/gitlab-org/api/client-go/time_stats.go diff --git a/vendor/github.com/xanzy/go-gitlab/todos.go b/vendor/gitlab.com/gitlab-org/api/client-go/todos.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/todos.go rename to vendor/gitlab.com/gitlab-org/api/client-go/todos.go diff --git a/vendor/github.com/xanzy/go-gitlab/topics.go b/vendor/gitlab.com/gitlab-org/api/client-go/topics.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/topics.go rename to vendor/gitlab.com/gitlab-org/api/client-go/topics.go diff --git a/vendor/github.com/xanzy/go-gitlab/types.go b/vendor/gitlab.com/gitlab-org/api/client-go/types.go similarity index 93% rename from vendor/github.com/xanzy/go-gitlab/types.go rename to vendor/gitlab.com/gitlab-org/api/client-go/types.go index 9ce13d735c..df1231db3c 100644 --- a/vendor/github.com/xanzy/go-gitlab/types.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/types.go @@ -89,6 +89,11 @@ func AccessLevel(v AccessLevelValue) *AccessLevelValue { return Ptr(v) } +type AccessLevelDetails struct { + IntegerValue AccessLevelValue `json:"integer_value"` + StringValue string `json:"string_value"` +} + // UserIDValue represents a user ID value within GitLab. type UserIDValue string @@ -435,6 +440,26 @@ func GenericPackageStatus(v GenericPackageStatusValue) *GenericPackageStatusValu return Ptr(v) } +// GroupHookTrigger represents the type of event to trigger for a group +// hook test. +type GroupHookTrigger string + +// List of available group hook trigger types. +const ( + GroupHookTriggerPush GroupHookTrigger = "push_events" + GroupHookTriggerTagPush GroupHookTrigger = "tag_push_events" + GroupHookTriggerIssue GroupHookTrigger = "issues_events" + GroupHookTriggerConfidentialIssue GroupHookTrigger = "confidential_issues_events" + GroupHookTriggerNote GroupHookTrigger = "note_events" + GroupHookTriggerMergeRequest GroupHookTrigger = "merge_requests_events" + GroupHookTriggerJob GroupHookTrigger = "job_events" + GroupHookTriggerPipeline GroupHookTrigger = "pipeline_events" + GroupHookTriggerWikiPage GroupHookTrigger = "wiki_page_events" + GroupHookTriggerRelease GroupHookTrigger = "releases_events" + GroupHookTriggerEmoji GroupHookTrigger = "emoji_events" + GroupHookTriggerResourceAccessToken GroupHookTrigger = "resource_access_token_events" +) + // ISOTime represents an ISO 8601 formatted date. type ISOTime time.Time @@ -688,6 +713,7 @@ const ( NoOneProjectCreation ProjectCreationLevelValue = "noone" MaintainerProjectCreation ProjectCreationLevelValue = "maintainer" DeveloperProjectCreation ProjectCreationLevelValue = "developer" + OwnerProjectCreation ProjectCreationLevelValue = "owner" ) // ProjectCreationLevel is a helper routine that allocates a new ProjectCreationLevelValue @@ -977,3 +1003,19 @@ func (t *BoolValue) UnmarshalJSON(b []byte) error { return err } } + +// CIPipelineVariablesMinimumOverrideRoleValue represents an access control +// value used for managing access to the CI Pipeline Variable Override feature. +// +// GitLab API docs: https://docs.gitlab.com/ee/api/projects.html +type CIPipelineVariablesMinimumOverrideRoleValue = string + +// List of available CIPipelineVariablesMinimumOverrideRoleValue values. +// +// GitLab API docs: https://docs.gitlab.com/ee/api/projects.html +const ( + CIPipelineVariablesNoOneAllowedRole CIPipelineVariablesMinimumOverrideRoleValue = "no_one_allowed" + CiPipelineVariablesOwnerRole CIPipelineVariablesMinimumOverrideRoleValue = "owner" + CiPipelineVariablesMaintainerRole CIPipelineVariablesMinimumOverrideRoleValue = "maintainer" + CIPipelineVariablesDeveloperRole CIPipelineVariablesMinimumOverrideRoleValue = "developer" +) diff --git a/vendor/github.com/xanzy/go-gitlab/users.go b/vendor/gitlab.com/gitlab-org/api/client-go/users.go similarity index 96% rename from vendor/github.com/xanzy/go-gitlab/users.go rename to vendor/gitlab.com/gitlab-org/api/client-go/users.go index f463952ac8..9f65c48a52 100644 --- a/vendor/github.com/xanzy/go-gitlab/users.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/users.go @@ -56,11 +56,22 @@ type BasicUser struct { Username string `json:"username"` Name string `json:"name"` State string `json:"state"` + Locked bool `json:"locked"` CreatedAt *time.Time `json:"created_at"` AvatarURL string `json:"avatar_url"` WebURL string `json:"web_url"` } +// ServiceAccount represents a GitLab service account. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/user_service_accounts.html +type ServiceAccount struct { + ID int `json:"id"` + Username string `json:"username"` + Name string `json:"name"` +} + // User represents a GitLab user. // // GitLab API docs: https://docs.gitlab.com/ee/api/users.html @@ -109,6 +120,7 @@ type User struct { CustomAttributes []*CustomAttribute `json:"custom_attributes"` NamespaceID int `json:"namespace_id"` Locked bool `json:"locked"` + CreatedBy *BasicUser `json:"created_by"` } // UserIdentity represents a user identity. @@ -484,23 +496,24 @@ func (s *UsersService) GetUserAssociationsCount(user int, options ...RequestOpti // SSHKey represents a SSH key. // -// GitLab API docs: https://docs.gitlab.com/ee/api/users.html#list-ssh-keys +// GitLab API docs: https://docs.gitlab.com/ee/api/user_keys.html#list-all-ssh-keys type SSHKey struct { ID int `json:"id"` Title string `json:"title"` Key string `json:"key"` CreatedAt *time.Time `json:"created_at"` ExpiresAt *time.Time `json:"expires_at"` + UsageType string `json:"usage_type"` } // ListSSHKeysOptions represents the available ListSSHKeys options. // -// GitLab API docs: https://docs.gitlab.com/ee/api/users.html#list-ssh-keys +// GitLab API docs: https://docs.gitlab.com/ee/api/user_keys.html#list-all-ssh-keys type ListSSHKeysOptions ListOptions // ListSSHKeys gets a list of currently authenticated user's SSH keys. // -// GitLab API docs: https://docs.gitlab.com/ee/api/users.html#list-ssh-keys +// GitLab API docs: https://docs.gitlab.com/ee/api/user_keys.html#list-all-ssh-keys func (s *UsersService) ListSSHKeys(opt *ListSSHKeysOptions, options ...RequestOptionFunc) ([]*SSHKey, *Response, error) { req, err := s.client.NewRequest(http.MethodGet, "user/keys", opt, options) if err != nil { @@ -1543,11 +1556,20 @@ func (s *UsersService) CreateUserRunner(opts *CreateUserRunnerOptions, options . return r, resp, nil } -// CreateServiceAccountUser creates a new service account user. Note only administrators can create new service account users. +// CreateServiceAccountUserOptions represents the available CreateServiceAccountUser() options. +// +// GitLab API docs: https://docs.gitlab.com/ee/api/user_service_accounts.html#create-a-service-account-user +type CreateServiceAccountUserOptions struct { + Name *string `url:"name,omitempty" json:"name,omitempty"` + Username *string `url:"username,omitempty" json:"username,omitempty"` +} + +// CreateServiceAccountUser creates a new service account user. // -// GitLab API docs: https://docs.gitlab.com/ee/api/users.html#create-service-account-user -func (s *UsersService) CreateServiceAccountUser(options ...RequestOptionFunc) (*User, *Response, error) { - req, err := s.client.NewRequest(http.MethodPost, "service_accounts", nil, options) +// GitLab API docs: +// https://docs.gitlab.com/ee/api/users.html#create-service-account-user +func (s *UsersService) CreateServiceAccountUser(opts *CreateServiceAccountUserOptions, options ...RequestOptionFunc) (*User, *Response, error) { + req, err := s.client.NewRequest(http.MethodPost, "service_accounts", opts, options) if err != nil { return nil, nil, err } @@ -1561,6 +1583,25 @@ func (s *UsersService) CreateServiceAccountUser(options ...RequestOptionFunc) (* return usr, resp, nil } +// ListServiceAccounts lists all service accounts. +// +// GitLab API docs: +// https://docs.gitlab.com/ee/api/users.html#create-service-account-user +func (s *UsersService) ListServiceAccounts(opt *ListServiceAccountsOptions, options ...RequestOptionFunc) ([]*ServiceAccount, *Response, error) { + req, err := s.client.NewRequest(http.MethodGet, "service_accounts", opt, options) + if err != nil { + return nil, nil, err + } + + var sas []*ServiceAccount + resp, err := s.client.Do(req, &sas) + if err != nil { + return nil, resp, err + } + + return sas, resp, nil +} + // UploadAvatar uploads an avatar to the current user. // // GitLab API docs: diff --git a/vendor/github.com/xanzy/go-gitlab/validate.go b/vendor/gitlab.com/gitlab-org/api/client-go/validate.go similarity index 84% rename from vendor/github.com/xanzy/go-gitlab/validate.go rename to vendor/gitlab.com/gitlab-org/api/client-go/validate.go index cb79ac8380..f4aa11f470 100644 --- a/vendor/github.com/xanzy/go-gitlab/validate.go +++ b/vendor/gitlab.com/gitlab-org/api/client-go/validate.go @@ -44,10 +44,26 @@ type LintResult struct { // GitLab API docs: // https://docs.gitlab.com/ee/api/lint.html#validate-a-projects-ci-configuration type ProjectLintResult struct { - Valid bool `json:"valid"` - Errors []string `json:"errors"` - Warnings []string `json:"warnings"` - MergedYaml string `json:"merged_yaml"` + Valid bool `json:"valid"` + Errors []string `json:"errors"` + Warnings []string `json:"warnings"` + MergedYaml string `json:"merged_yaml"` + Includes []Include `json:"includes"` +} + +// Include contains the details about an include block in the .gitlab-ci.yml file. +// It is used in ProjectLintResult. +// +// Reference can be found at the lint API endpoint in the openapi yaml: +// https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/api/openapi/openapi_v2.yaml +type Include struct { + Type string `json:"type"` + Location string `json:"location"` + Blob string `json:"blob"` + Raw string `json:"raw"` + Extra map[string]interface{} `json:"extra"` + ContextProject string `json:"context_project"` + ContextSHA string `json:"context_sha"` } // LintOptions represents the available Lint() options. diff --git a/vendor/github.com/xanzy/go-gitlab/version.go b/vendor/gitlab.com/gitlab-org/api/client-go/version.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/version.go rename to vendor/gitlab.com/gitlab-org/api/client-go/version.go diff --git a/vendor/github.com/xanzy/go-gitlab/wikis.go b/vendor/gitlab.com/gitlab-org/api/client-go/wikis.go similarity index 100% rename from vendor/github.com/xanzy/go-gitlab/wikis.go rename to vendor/gitlab.com/gitlab-org/api/client-go/wikis.go diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go index e555a475f1..3ea05d0199 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go @@ -12,6 +12,7 @@ import ( "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request" "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv" "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/trace" ) @@ -21,15 +22,16 @@ type middleware struct { operation string server string - tracer trace.Tracer - propagators propagation.TextMapPropagator - spanStartOptions []trace.SpanStartOption - readEvent bool - writeEvent bool - filters []Filter - spanNameFormatter func(string, *http.Request) string - publicEndpoint bool - publicEndpointFn func(*http.Request) bool + tracer trace.Tracer + propagators propagation.TextMapPropagator + spanStartOptions []trace.SpanStartOption + readEvent bool + writeEvent bool + filters []Filter + spanNameFormatter func(string, *http.Request) string + publicEndpoint bool + publicEndpointFn func(*http.Request) bool + metricAttributesFn func(*http.Request) []attribute.KeyValue semconv semconv.HTTPServer } @@ -79,6 +81,7 @@ func (h *middleware) configure(c *config) { h.publicEndpointFn = c.PublicEndpointFn h.server = c.ServerName h.semconv = semconv.NewHTTPServer(c.Meter) + h.metricAttributesFn = c.MetricAttributesFn } // serveHTTP sets up tracing and calls the given next http.Handler with the span @@ -189,14 +192,16 @@ func (h *middleware) serveHTTP(w http.ResponseWriter, r *http.Request, next http // Use floating point division here for higher precision (instead of Millisecond method). elapsedTime := float64(time.Since(requestStartTime)) / float64(time.Millisecond) + metricAttributes := semconv.MetricAttributes{ + Req: r, + StatusCode: statusCode, + AdditionalAttributes: append(labeler.Get(), h.metricAttributesFromRequest(r)...), + } + h.semconv.RecordMetrics(ctx, semconv.ServerMetricData{ - ServerName: h.server, - ResponseSize: bytesWritten, - MetricAttributes: semconv.MetricAttributes{ - Req: r, - StatusCode: statusCode, - AdditionalAttributes: labeler.Get(), - }, + ServerName: h.server, + ResponseSize: bytesWritten, + MetricAttributes: metricAttributes, MetricData: semconv.MetricData{ RequestSize: bw.BytesRead(), ElapsedTime: elapsedTime, @@ -204,6 +209,14 @@ func (h *middleware) serveHTTP(w http.ResponseWriter, r *http.Request, next http }) } +func (h *middleware) metricAttributesFromRequest(r *http.Request) []attribute.KeyValue { + var attributeForRequest []attribute.KeyValue + if h.metricAttributesFn != nil { + attributeForRequest = h.metricAttributesFn(r) + } + return attributeForRequest +} + // WithRouteTag annotates spans and metrics with the provided route name // with HTTP route attribute. func WithRouteTag(route string, h http.Handler) http.Handler { diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/env.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/env.go index 3b036f8a37..eaf4c37967 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/env.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/env.go @@ -1,3 +1,6 @@ +// Code created by gotmpl. DO NOT MODIFY. +// source: internal/shared/semconv/env.go.tmpl + // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 @@ -16,6 +19,10 @@ import ( "go.opentelemetry.io/otel/metric" ) +// OTelSemConvStabilityOptIn is an environment variable. +// That can be set to "old" or "http/dup" to opt into the new HTTP semantic conventions. +const OTelSemConvStabilityOptIn = "OTEL_SEMCONV_STABILITY_OPT_IN" + type ResponseTelemetry struct { StatusCode int ReadBytes int64 @@ -31,6 +38,11 @@ type HTTPServer struct { requestBytesCounter metric.Int64Counter responseBytesCounter metric.Int64Counter serverLatencyMeasure metric.Float64Histogram + + // New metrics + requestBodySizeHistogram metric.Int64Histogram + responseBodySizeHistogram metric.Int64Histogram + requestDurationHistogram metric.Float64Histogram } // RequestTraceAttrs returns trace attributes for an HTTP request received by a @@ -103,38 +115,56 @@ type MetricData struct { ElapsedTime float64 } -var metricAddOptionPool = &sync.Pool{ - New: func() interface{} { - return &[]metric.AddOption{} - }, -} +var ( + metricAddOptionPool = &sync.Pool{ + New: func() interface{} { + return &[]metric.AddOption{} + }, + } -func (s HTTPServer) RecordMetrics(ctx context.Context, md ServerMetricData) { - if s.requestBytesCounter == nil || s.responseBytesCounter == nil || s.serverLatencyMeasure == nil { - // This will happen if an HTTPServer{} is used instead of NewHTTPServer. - return + metricRecordOptionPool = &sync.Pool{ + New: func() interface{} { + return &[]metric.RecordOption{} + }, } +) - attributes := OldHTTPServer{}.MetricAttributes(md.ServerName, md.Req, md.StatusCode, md.AdditionalAttributes) - o := metric.WithAttributeSet(attribute.NewSet(attributes...)) - addOpts := metricAddOptionPool.Get().(*[]metric.AddOption) - *addOpts = append(*addOpts, o) - s.requestBytesCounter.Add(ctx, md.RequestSize, *addOpts...) - s.responseBytesCounter.Add(ctx, md.ResponseSize, *addOpts...) - s.serverLatencyMeasure.Record(ctx, md.ElapsedTime, o) - *addOpts = (*addOpts)[:0] - metricAddOptionPool.Put(addOpts) +func (s HTTPServer) RecordMetrics(ctx context.Context, md ServerMetricData) { + if s.requestBytesCounter != nil && s.responseBytesCounter != nil && s.serverLatencyMeasure != nil { + attributes := OldHTTPServer{}.MetricAttributes(md.ServerName, md.Req, md.StatusCode, md.AdditionalAttributes) + o := metric.WithAttributeSet(attribute.NewSet(attributes...)) + addOpts := metricAddOptionPool.Get().(*[]metric.AddOption) + *addOpts = append(*addOpts, o) + s.requestBytesCounter.Add(ctx, md.RequestSize, *addOpts...) + s.responseBytesCounter.Add(ctx, md.ResponseSize, *addOpts...) + s.serverLatencyMeasure.Record(ctx, md.ElapsedTime, o) + *addOpts = (*addOpts)[:0] + metricAddOptionPool.Put(addOpts) + } - // TODO: Duplicate Metrics + if s.duplicate && s.requestDurationHistogram != nil && s.requestBodySizeHistogram != nil && s.responseBodySizeHistogram != nil { + attributes := CurrentHTTPServer{}.MetricAttributes(md.ServerName, md.Req, md.StatusCode, md.AdditionalAttributes) + o := metric.WithAttributeSet(attribute.NewSet(attributes...)) + recordOpts := metricRecordOptionPool.Get().(*[]metric.RecordOption) + *recordOpts = append(*recordOpts, o) + s.requestBodySizeHistogram.Record(ctx, md.RequestSize, *recordOpts...) + s.responseBodySizeHistogram.Record(ctx, md.ResponseSize, *recordOpts...) + s.requestDurationHistogram.Record(ctx, md.ElapsedTime, o) + *recordOpts = (*recordOpts)[:0] + metricRecordOptionPool.Put(recordOpts) + } } func NewHTTPServer(meter metric.Meter) HTTPServer { - env := strings.ToLower(os.Getenv("OTEL_SEMCONV_STABILITY_OPT_IN")) + env := strings.ToLower(os.Getenv(OTelSemConvStabilityOptIn)) duplicate := env == "http/dup" server := HTTPServer{ duplicate: duplicate, } server.requestBytesCounter, server.responseBytesCounter, server.serverLatencyMeasure = OldHTTPServer{}.createMeasures(meter) + if duplicate { + server.requestBodySizeHistogram, server.responseBodySizeHistogram, server.requestDurationHistogram = CurrentHTTPServer{}.createMeasures(meter) + } return server } @@ -145,14 +175,23 @@ type HTTPClient struct { requestBytesCounter metric.Int64Counter responseBytesCounter metric.Int64Counter latencyMeasure metric.Float64Histogram + + // new metrics + requestBodySize metric.Int64Histogram + requestDuration metric.Float64Histogram } func NewHTTPClient(meter metric.Meter) HTTPClient { - env := strings.ToLower(os.Getenv("OTEL_SEMCONV_STABILITY_OPT_IN")) + env := strings.ToLower(os.Getenv(OTelSemConvStabilityOptIn)) + duplicate := env == "http/dup" client := HTTPClient{ - duplicate: env == "http/dup", + duplicate: duplicate, } client.requestBytesCounter, client.responseBytesCounter, client.latencyMeasure = OldHTTPClient{}.createMeasures(meter) + if duplicate { + client.requestBodySize, client.requestDuration = CurrentHTTPClient{}.createMeasures(meter) + } + return client } @@ -204,34 +243,48 @@ func (o MetricOpts) AddOptions() metric.AddOption { return o.addOptions } -func (c HTTPClient) MetricOptions(ma MetricAttributes) MetricOpts { +func (c HTTPClient) MetricOptions(ma MetricAttributes) map[string]MetricOpts { + opts := map[string]MetricOpts{} + attributes := OldHTTPClient{}.MetricAttributes(ma.Req, ma.StatusCode, ma.AdditionalAttributes) - // TODO: Duplicate Metrics set := metric.WithAttributeSet(attribute.NewSet(attributes...)) - return MetricOpts{ + opts["old"] = MetricOpts{ measurement: set, addOptions: set, } + + if c.duplicate { + attributes := CurrentHTTPClient{}.MetricAttributes(ma.Req, ma.StatusCode, ma.AdditionalAttributes) + set := metric.WithAttributeSet(attribute.NewSet(attributes...)) + opts["new"] = MetricOpts{ + measurement: set, + addOptions: set, + } + } + + return opts } -func (s HTTPClient) RecordMetrics(ctx context.Context, md MetricData, opts MetricOpts) { +func (s HTTPClient) RecordMetrics(ctx context.Context, md MetricData, opts map[string]MetricOpts) { if s.requestBytesCounter == nil || s.latencyMeasure == nil { // This will happen if an HTTPClient{} is used instead of NewHTTPClient(). return } - s.requestBytesCounter.Add(ctx, md.RequestSize, opts.AddOptions()) - s.latencyMeasure.Record(ctx, md.ElapsedTime, opts.MeasurementOption()) + s.requestBytesCounter.Add(ctx, md.RequestSize, opts["old"].AddOptions()) + s.latencyMeasure.Record(ctx, md.ElapsedTime, opts["old"].MeasurementOption()) - // TODO: Duplicate Metrics + if s.duplicate { + s.requestBodySize.Record(ctx, md.RequestSize, opts["new"].MeasurementOption()) + s.requestDuration.Record(ctx, md.ElapsedTime, opts["new"].MeasurementOption()) + } } -func (s HTTPClient) RecordResponseSize(ctx context.Context, responseData int64, opts metric.AddOption) { +func (s HTTPClient) RecordResponseSize(ctx context.Context, responseData int64, opts map[string]MetricOpts) { if s.responseBytesCounter == nil { // This will happen if an HTTPClient{} is used instead of NewHTTPClient(). return } - s.responseBytesCounter.Add(ctx, responseData, opts) - // TODO: Duplicate Metrics + s.responseBytesCounter.Add(ctx, responseData, opts["old"].AddOptions()) } diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/gen.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/gen.go new file mode 100644 index 0000000000..32630864bf --- /dev/null +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/gen.go @@ -0,0 +1,14 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package semconv // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv" + +// Generate semconv package: +//go:generate gotmpl --body=../../../../../../internal/shared/semconv/bench_test.go.tmpl "--data={}" --out=bench_test.go +//go:generate gotmpl --body=../../../../../../internal/shared/semconv/env.go.tmpl "--data={}" --out=env.go +//go:generate gotmpl --body=../../../../../../internal/shared/semconv/env_test.go.tmpl "--data={}" --out=env_test.go +//go:generate gotmpl --body=../../../../../../internal/shared/semconv/httpconv.go.tmpl "--data={}" --out=httpconv.go +//go:generate gotmpl --body=../../../../../../internal/shared/semconv/httpconv_test.go.tmpl "--data={}" --out=httpconv_test.go +//go:generate gotmpl --body=../../../../../../internal/shared/semconv/util.go.tmpl "--data={}" --out=util.go +//go:generate gotmpl --body=../../../../../../internal/shared/semconv/util_test.go.tmpl "--data={}" --out=util_test.go +//go:generate gotmpl --body=../../../../../../internal/shared/semconv/v1.20.0.go.tmpl "--data={}" --out=v1.20.0.go diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/httpconv.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/httpconv.go index dc9ec7bc39..8c3c627513 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/httpconv.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/httpconv.go @@ -1,3 +1,6 @@ +// Code created by gotmpl. DO NOT MODIFY. +// source: internal/shared/semconv/httpconv.go.tmpl + // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 @@ -7,10 +10,13 @@ import ( "fmt" "net/http" "reflect" + "slices" "strconv" "strings" "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/noop" semconvNew "go.opentelemetry.io/otel/semconv/v1.26.0" ) @@ -199,6 +205,86 @@ func (n CurrentHTTPServer) Route(route string) attribute.KeyValue { return semconvNew.HTTPRoute(route) } +func (n CurrentHTTPServer) createMeasures(meter metric.Meter) (metric.Int64Histogram, metric.Int64Histogram, metric.Float64Histogram) { + if meter == nil { + return noop.Int64Histogram{}, noop.Int64Histogram{}, noop.Float64Histogram{} + } + + var err error + requestBodySizeHistogram, err := meter.Int64Histogram( + semconvNew.HTTPServerRequestBodySizeName, + metric.WithUnit(semconvNew.HTTPServerRequestBodySizeUnit), + metric.WithDescription(semconvNew.HTTPServerRequestBodySizeDescription), + ) + handleErr(err) + + responseBodySizeHistogram, err := meter.Int64Histogram( + semconvNew.HTTPServerResponseBodySizeName, + metric.WithUnit(semconvNew.HTTPServerResponseBodySizeUnit), + metric.WithDescription(semconvNew.HTTPServerResponseBodySizeDescription), + ) + handleErr(err) + requestDurationHistogram, err := meter.Float64Histogram( + semconvNew.HTTPServerRequestDurationName, + metric.WithUnit(semconvNew.HTTPServerRequestDurationUnit), + metric.WithDescription(semconvNew.HTTPServerRequestDurationDescription), + ) + handleErr(err) + + return requestBodySizeHistogram, responseBodySizeHistogram, requestDurationHistogram +} + +func (n CurrentHTTPServer) MetricAttributes(server string, req *http.Request, statusCode int, additionalAttributes []attribute.KeyValue) []attribute.KeyValue { + num := len(additionalAttributes) + 3 + var host string + var p int + if server == "" { + host, p = SplitHostPort(req.Host) + } else { + // Prioritize the primary server name. + host, p = SplitHostPort(server) + if p < 0 { + _, p = SplitHostPort(req.Host) + } + } + hostPort := requiredHTTPPort(req.TLS != nil, p) + if hostPort > 0 { + num++ + } + protoName, protoVersion := netProtocol(req.Proto) + if protoName != "" { + num++ + } + if protoVersion != "" { + num++ + } + + if statusCode > 0 { + num++ + } + + attributes := slices.Grow(additionalAttributes, num) + attributes = append(attributes, + semconvNew.HTTPRequestMethodKey.String(standardizeHTTPMethod(req.Method)), + n.scheme(req.TLS != nil), + semconvNew.ServerAddress(host)) + + if hostPort > 0 { + attributes = append(attributes, semconvNew.ServerPort(hostPort)) + } + if protoName != "" { + attributes = append(attributes, semconvNew.NetworkProtocolName(protoName)) + } + if protoVersion != "" { + attributes = append(attributes, semconvNew.NetworkProtocolVersion(protoVersion)) + } + + if statusCode > 0 { + attributes = append(attributes, semconvNew.HTTPResponseStatusCode(statusCode)) + } + return attributes +} + type CurrentHTTPClient struct{} // RequestTraceAttrs returns trace attributes for an HTTP request made by a client. @@ -343,6 +429,91 @@ func (n CurrentHTTPClient) method(method string) (attribute.KeyValue, attribute. return semconvNew.HTTPRequestMethodGet, orig } +func (n CurrentHTTPClient) createMeasures(meter metric.Meter) (metric.Int64Histogram, metric.Float64Histogram) { + if meter == nil { + return noop.Int64Histogram{}, noop.Float64Histogram{} + } + + var err error + requestBodySize, err := meter.Int64Histogram( + semconvNew.HTTPClientRequestBodySizeName, + metric.WithUnit(semconvNew.HTTPClientRequestBodySizeUnit), + metric.WithDescription(semconvNew.HTTPClientRequestBodySizeDescription), + ) + handleErr(err) + + requestDuration, err := meter.Float64Histogram( + semconvNew.HTTPClientRequestDurationName, + metric.WithUnit(semconvNew.HTTPClientRequestDurationUnit), + metric.WithDescription(semconvNew.HTTPClientRequestDurationDescription), + ) + handleErr(err) + + return requestBodySize, requestDuration +} + +func (n CurrentHTTPClient) MetricAttributes(req *http.Request, statusCode int, additionalAttributes []attribute.KeyValue) []attribute.KeyValue { + num := len(additionalAttributes) + 2 + var h string + if req.URL != nil { + h = req.URL.Host + } + var requestHost string + var requestPort int + for _, hostport := range []string{h, req.Header.Get("Host")} { + requestHost, requestPort = SplitHostPort(hostport) + if requestHost != "" || requestPort > 0 { + break + } + } + + port := requiredHTTPPort(req.URL != nil && req.URL.Scheme == "https", requestPort) + if port > 0 { + num++ + } + + protoName, protoVersion := netProtocol(req.Proto) + if protoName != "" { + num++ + } + if protoVersion != "" { + num++ + } + + if statusCode > 0 { + num++ + } + + attributes := slices.Grow(additionalAttributes, num) + attributes = append(attributes, + semconvNew.HTTPRequestMethodKey.String(standardizeHTTPMethod(req.Method)), + semconvNew.ServerAddress(requestHost), + n.scheme(req.TLS != nil), + ) + + if port > 0 { + attributes = append(attributes, semconvNew.ServerPort(port)) + } + if protoName != "" { + attributes = append(attributes, semconvNew.NetworkProtocolName(protoName)) + } + if protoVersion != "" { + attributes = append(attributes, semconvNew.NetworkProtocolVersion(protoVersion)) + } + + if statusCode > 0 { + attributes = append(attributes, semconvNew.HTTPResponseStatusCode(statusCode)) + } + return attributes +} + +func (n CurrentHTTPClient) scheme(https bool) attribute.KeyValue { // nolint:revive + if https { + return semconvNew.URLScheme("https") + } + return semconvNew.URLScheme("http") +} + func isErrorStatusCode(code int) bool { return code >= 400 || code < 100 } diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/util.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/util.go index 93e8d0f94c..558efd0594 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/util.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/util.go @@ -1,3 +1,6 @@ +// Code created by gotmpl. DO NOT MODIFY. +// source: internal/shared/semconv/util.go.tmpl + // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 @@ -96,3 +99,13 @@ func handleErr(err error) { otel.Handle(err) } } + +func standardizeHTTPMethod(method string) string { + method = strings.ToUpper(method) + switch method { + case http.MethodConnect, http.MethodDelete, http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPatch, http.MethodPost, http.MethodPut, http.MethodTrace: + default: + method = "_OTHER" + } + return method +} diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/v1.20.0.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/v1.20.0.go index c042249dd7..57d1507b62 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/v1.20.0.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/v1.20.0.go @@ -1,3 +1,6 @@ +// Code created by gotmpl. DO NOT MODIFY. +// source: internal/shared/semconv/v120.0.go.tmpl + // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 @@ -8,7 +11,6 @@ import ( "io" "net/http" "slices" - "strings" "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil" "go.opentelemetry.io/otel/attribute" @@ -144,7 +146,7 @@ func (o OldHTTPServer) MetricAttributes(server string, req *http.Request, status attributes := slices.Grow(additionalAttributes, n) attributes = append(attributes, - standardizeHTTPMethodMetric(req.Method), + semconv.HTTPMethod(standardizeHTTPMethod(req.Method)), o.scheme(req.TLS != nil), semconv.NetHostName(host)) @@ -214,7 +216,7 @@ func (o OldHTTPClient) MetricAttributes(req *http.Request, statusCode int, addit attributes := slices.Grow(additionalAttributes, n) attributes = append(attributes, - standardizeHTTPMethodMetric(req.Method), + semconv.HTTPMethod(standardizeHTTPMethod(req.Method)), semconv.NetPeerName(requestHost), ) @@ -262,13 +264,3 @@ func (o OldHTTPClient) createMeasures(meter metric.Meter) (metric.Int64Counter, return requestBytesCounter, responseBytesCounter, latencyMeasure } - -func standardizeHTTPMethodMetric(method string) attribute.KeyValue { - method = strings.ToUpper(method) - switch method { - case http.MethodConnect, http.MethodDelete, http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPatch, http.MethodPost, http.MethodPut, http.MethodTrace: - default: - method = "_OTHER" - } - return semconv.HTTPMethod(method) -} diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/transport.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/transport.go index 39681ad4b0..44b86ad860 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/transport.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/transport.go @@ -153,7 +153,7 @@ func (t *Transport) RoundTrip(r *http.Request) (*http.Response, error) { // For handling response bytes we leverage a callback when the client reads the http response readRecordFunc := func(n int64) { - t.semconv.RecordResponseSize(ctx, n, metricOpts.AddOptions()) + t.semconv.RecordResponseSize(ctx, n, metricOpts) } // traces diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go index 353e43b91f..386f09e1b7 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go @@ -5,7 +5,7 @@ package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http // Version is the current release version of the otelhttp instrumentation. func Version() string { - return "0.58.0" + return "0.59.0" // This string is updated by the pre_release.sh script during release } diff --git a/vendor/go.opentelemetry.io/otel/CHANGELOG.md b/vendor/go.opentelemetry.io/otel/CHANGELOG.md index a30988f25d..599d59cd13 100644 --- a/vendor/go.opentelemetry.io/otel/CHANGELOG.md +++ b/vendor/go.opentelemetry.io/otel/CHANGELOG.md @@ -8,6 +8,21 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm ## [Unreleased] + + + +## [1.34.0/0.56.0/0.10.0] 2025-01-17 + +### Changed + +- Remove the notices from `Logger` to make the whole Logs API user-facing in `go.opentelemetry.io/otel/log`. (#6167) + +### Fixed + +- Relax minimum Go version to 1.22.0 in various modules. (#6073) +- The `Type` name logged for the `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc` client is corrected from `otlphttpgrpc` to `otlptracegrpc`. (#6143) +- The `Type` name logged for the `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlphttpgrpc` client is corrected from `otlphttphttp` to `otlptracehttp`. (#6143) + ## [1.33.0/0.55.0/0.9.0/0.0.12] 2024-12-12 ### Added @@ -37,9 +52,6 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm - Fix attribute value truncation in `go.opentelemetry.io/otel/sdk/trace`. (#5997) - Fix attribute value truncation in `go.opentelemetry.io/otel/sdk/log`. (#6032) - - - ## [1.32.0/0.54.0/0.8.0/0.0.11] 2024-11-08 ### Added @@ -3185,7 +3197,8 @@ It contains api and sdk for trace and meter. - CircleCI build CI manifest files. - CODEOWNERS file to track owners of this project. -[Unreleased]: https://github.com/open-telemetry/opentelemetry-go/compare/v1.33.0...HEAD +[Unreleased]: https://github.com/open-telemetry/opentelemetry-go/compare/v1.34.0...HEAD +[1.34.0/0.56.0/0.10.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.34.0 [1.33.0/0.55.0/0.9.0/0.0.12]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.33.0 [1.32.0/0.54.0/0.8.0/0.0.11]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.32.0 [1.31.0/0.53.0/0.7.0/0.0.10]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.31.0 diff --git a/vendor/go.opentelemetry.io/otel/README.md b/vendor/go.opentelemetry.io/otel/README.md index efec278905..d9a1920762 100644 --- a/vendor/go.opentelemetry.io/otel/README.md +++ b/vendor/go.opentelemetry.io/otel/README.md @@ -1,6 +1,6 @@ # OpenTelemetry-Go -[![CI](https://github.com/open-telemetry/opentelemetry-go/workflows/ci/badge.svg)](https://github.com/open-telemetry/opentelemetry-go/actions?query=workflow%3Aci+branch%3Amain) +[![ci](https://github.com/open-telemetry/opentelemetry-go/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/open-telemetry/opentelemetry-go/actions/workflows/ci.yml) [![codecov.io](https://codecov.io/gh/open-telemetry/opentelemetry-go/coverage.svg?branch=main)](https://app.codecov.io/gh/open-telemetry/opentelemetry-go?branch=main) [![PkgGoDev](https://pkg.go.dev/badge/go.opentelemetry.io/otel)](https://pkg.go.dev/go.opentelemetry.io/otel) [![Go Report Card](https://goreportcard.com/badge/go.opentelemetry.io/otel)](https://goreportcard.com/report/go.opentelemetry.io/otel) diff --git a/vendor/go.opentelemetry.io/otel/RELEASING.md b/vendor/go.opentelemetry.io/otel/RELEASING.md index ffa9b61258..4ebef4f9dd 100644 --- a/vendor/go.opentelemetry.io/otel/RELEASING.md +++ b/vendor/go.opentelemetry.io/otel/RELEASING.md @@ -130,6 +130,6 @@ Importantly, bump any package versions referenced to be the latest one you just Bump the dependencies in the following Go services: -- [`accountingservice`](https://github.com/open-telemetry/opentelemetry-demo/tree/main/src/accountingservice) -- [`checkoutservice`](https://github.com/open-telemetry/opentelemetry-demo/tree/main/src/checkoutservice) -- [`productcatalogservice`](https://github.com/open-telemetry/opentelemetry-demo/tree/main/src/productcatalogservice) +- [`accounting`](https://github.com/open-telemetry/opentelemetry-demo/tree/main/src/accounting) +- [`checkoutservice`](https://github.com/open-telemetry/opentelemetry-demo/tree/main/src/checkout) +- [`productcatalogservice`](https://github.com/open-telemetry/opentelemetry-demo/tree/main/src/product-catalog) diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/client.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/client.go index 2171bee3c8..8409b5f8f9 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/client.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/client.go @@ -294,7 +294,7 @@ func (c *client) MarshalLog() interface{} { Type string Endpoint string }{ - Type: "otlphttpgrpc", + Type: "otlptracegrpc", Endpoint: c.endpoint, } } diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go index 8ea156a098..f156ee6672 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go @@ -5,5 +5,5 @@ package otlptrace // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace" // Version is the current release version of the OpenTelemetry OTLP trace exporter in use. func Version() string { - return "1.33.0" + return "1.34.0" } diff --git a/vendor/go.opentelemetry.io/otel/renovate.json b/vendor/go.opentelemetry.io/otel/renovate.json index 0a29a2f13d..4f80c898a1 100644 --- a/vendor/go.opentelemetry.io/otel/renovate.json +++ b/vendor/go.opentelemetry.io/otel/renovate.json @@ -14,12 +14,6 @@ "matchDepTypes": ["indirect"], "enabled": true }, - { - "matchFileNames": ["internal/tools/**"], - "matchManagers": ["gomod"], - "matchDepTypes": ["indirect"], - "enabled": false - }, { "matchPackageNames": ["google.golang.org/genproto/googleapis/**"], "groupName": "googleapis" diff --git a/vendor/go.opentelemetry.io/otel/sdk/version.go b/vendor/go.opentelemetry.io/otel/sdk/version.go index ba7db48895..6b40385107 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/version.go +++ b/vendor/go.opentelemetry.io/otel/sdk/version.go @@ -5,5 +5,5 @@ package sdk // import "go.opentelemetry.io/otel/sdk" // Version is the current release version of the OpenTelemetry SDK in use. func Version() string { - return "1.33.0" + return "1.34.0" } diff --git a/vendor/go.opentelemetry.io/otel/version.go b/vendor/go.opentelemetry.io/otel/version.go index fb7d12673e..eb22002d82 100644 --- a/vendor/go.opentelemetry.io/otel/version.go +++ b/vendor/go.opentelemetry.io/otel/version.go @@ -5,5 +5,5 @@ package otel // import "go.opentelemetry.io/otel" // Version is the current release version of OpenTelemetry in use. func Version() string { - return "1.33.0" + return "1.34.0" } diff --git a/vendor/go.opentelemetry.io/otel/versions.yaml b/vendor/go.opentelemetry.io/otel/versions.yaml index 9f878cd1fe..ce4fe59b0e 100644 --- a/vendor/go.opentelemetry.io/otel/versions.yaml +++ b/vendor/go.opentelemetry.io/otel/versions.yaml @@ -3,7 +3,7 @@ module-sets: stable-v1: - version: v1.33.0 + version: v1.34.0 modules: - go.opentelemetry.io/otel - go.opentelemetry.io/otel/bridge/opencensus @@ -23,11 +23,11 @@ module-sets: - go.opentelemetry.io/otel/sdk/metric - go.opentelemetry.io/otel/trace experimental-metrics: - version: v0.55.0 + version: v0.56.0 modules: - go.opentelemetry.io/otel/exporters/prometheus experimental-logs: - version: v0.9.0 + version: v0.10.0 modules: - go.opentelemetry.io/otel/log - go.opentelemetry.io/otel/sdk/log diff --git a/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go b/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go index d7099c35bc..b342a0a940 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go @@ -311,7 +311,8 @@ type ResourceSpans struct { // A list of ScopeSpans that originate from a resource. ScopeSpans []*ScopeSpans `protobuf:"bytes,2,rep,name=scope_spans,json=scopeSpans,proto3" json:"scope_spans,omitempty"` // The Schema URL, if known. This is the identifier of the Schema that the resource data - // is recorded in. To learn more about Schema URL see + // is recorded in. Notably, the last part of the URL path is the version number of the + // schema: http[s]://server[:port]/path/. To learn more about Schema URL see // https://opentelemetry.io/docs/specs/otel/schemas/#schema-url // This schema_url applies to the data in the "resource" field. It does not apply // to the data in the "scope_spans" field which have their own schema_url field. @@ -384,7 +385,8 @@ type ScopeSpans struct { // A list of Spans that originate from an instrumentation scope. Spans []*Span `protobuf:"bytes,2,rep,name=spans,proto3" json:"spans,omitempty"` // The Schema URL, if known. This is the identifier of the Schema that the span data - // is recorded in. To learn more about Schema URL see + // is recorded in. Notably, the last part of the URL path is the version number of the + // schema: http[s]://server[:port]/path/. To learn more about Schema URL see // https://opentelemetry.io/docs/specs/otel/schemas/#schema-url // This schema_url applies to all spans and span events in the "spans" field. SchemaUrl string `protobuf:"bytes,3,opt,name=schema_url,json=schemaUrl,proto3" json:"schema_url,omitempty"` diff --git a/vendor/go.step.sm/crypto/LICENSE b/vendor/go.step.sm/crypto/LICENSE deleted file mode 100644 index 261eeb9e9f..0000000000 --- a/vendor/go.step.sm/crypto/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/go.step.sm/crypto/fingerprint/fingerprint.go b/vendor/go.step.sm/crypto/fingerprint/fingerprint.go deleted file mode 100644 index 6eb174bdb6..0000000000 --- a/vendor/go.step.sm/crypto/fingerprint/fingerprint.go +++ /dev/null @@ -1,78 +0,0 @@ -package fingerprint - -import ( - "crypto" - "encoding/base64" - "encoding/hex" - "fmt" - "strings" - - "go.step.sm/crypto/internal/emoji" -) - -// Encoding defines the supported encodings for certificates and key -// fingerprints. -// -// This type is the base for sshutil.FingerprintEncoding and -// x509util.FingerprintEncoding types. -type Encoding int - -const ( - // HexFingerprint represents the hex encoding of the fingerprint. - // - // This is the default encoding for an X.509 certificate. - HexFingerprint Encoding = iota + 1 - // Base64Fingerprint represents the base64 encoding of the fingerprint. - // - // This is the default encoding for a public key. - Base64Fingerprint - // Base64URLFingerprint represents the base64URL encoding of the fingerprint. - Base64URLFingerprint - // Base64RawFingerprint represents the base64RawStd encoding of the - // fingerprint. - // - // This is the default encoding for an SSH key and certificate. - Base64RawFingerprint - // Base64RawURLFingerprint represents the base64RawURL encoding of the fingerprint. - Base64RawURLFingerprint - // EmojiFingerprint represents the emoji encoding of the fingerprint. - EmojiFingerprint -) - -// New creates a fingerprint of the given data by hashing it and returns it in -// the encoding format. -func New(data []byte, h crypto.Hash, encoding Encoding) (string, error) { - if !h.Available() { - return "", fmt.Errorf("hash function %q is not available", h.String()) - } - hash := h.New() - if _, err := hash.Write(data); err != nil { - return "", fmt.Errorf("error creating hash: %w", err) - } - fp := Fingerprint(hash.Sum(nil), encoding) - if fp == "" { - return "", fmt.Errorf("unknown encoding value %d", encoding) - } - return fp, nil -} - -// Fingerprint encodes the given digest using the encoding format. If an invalid -// encoding is passed, the return value will be an empty string. -func Fingerprint(digest []byte, encoding Encoding) string { - switch encoding { - case HexFingerprint: - return strings.ToLower(hex.EncodeToString(digest)) - case Base64Fingerprint: - return base64.StdEncoding.EncodeToString(digest) - case Base64URLFingerprint: - return base64.URLEncoding.EncodeToString(digest) - case Base64RawFingerprint: - return base64.RawStdEncoding.EncodeToString(digest) - case Base64RawURLFingerprint: - return base64.RawURLEncoding.EncodeToString(digest) - case EmojiFingerprint: - return emoji.Emoji(digest) - default: - return "" - } -} diff --git a/vendor/go.step.sm/crypto/internal/bcrypt_pbkdf/LICENSE b/vendor/go.step.sm/crypto/internal/bcrypt_pbkdf/LICENSE deleted file mode 100644 index b99c5e3b98..0000000000 --- a/vendor/go.step.sm/crypto/internal/bcrypt_pbkdf/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2014 Dmitry Chestnykh -Copyright (c) 2010 The Go Authors -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/go.step.sm/crypto/internal/bcrypt_pbkdf/README b/vendor/go.step.sm/crypto/internal/bcrypt_pbkdf/README deleted file mode 100644 index fb0fc8b70f..0000000000 --- a/vendor/go.step.sm/crypto/internal/bcrypt_pbkdf/README +++ /dev/null @@ -1,22 +0,0 @@ -Go implementation of bcrypt_pbkdf(3) from OpenBSD -(a variant of PBKDF2 with bcrypt-based PRF). - - -USAGE - - func Key(password, salt []byte, rounds, keyLen int) ([]byte, error) - - - Key derives a key from the password, salt and rounds count, returning a - []byte of length keyLen that can be used as cryptographic key. - - Remember to get a good random salt of at least 16 bytes. Using a higher - rounds count will increase the cost of an exhaustive search but will also - make derivation proportionally slower. - - -REFERENCES - -* https://github.com/dchest/bcrypt_pbkdf -* http://www.tedunangst.com/flak/post/bcrypt-pbkdf -* http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/lib/libutil/bcrypt_pbkdf.c diff --git a/vendor/go.step.sm/crypto/internal/bcrypt_pbkdf/bcrypt_pbkdf.go b/vendor/go.step.sm/crypto/internal/bcrypt_pbkdf/bcrypt_pbkdf.go deleted file mode 100644 index be443c8788..0000000000 --- a/vendor/go.step.sm/crypto/internal/bcrypt_pbkdf/bcrypt_pbkdf.go +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2014 Dmitry Chestnykh. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package bcrypt_pbkdf implements password-based key derivation function based -// on bcrypt compatible with bcrypt_pbkdf(3) from OpenBSD. -// -//nolint:revive,stylecheck // ignore underscore in package -package bcrypt_pbkdf - -import ( - "crypto/sha512" - "errors" - - // NOTE! Requires blowfish package version from Aug 1, 2014 or later. - // Will produce incorrect results if the package is older. - // See commit message for details: http://goo.gl/wx6g8O - //nolint:staticcheck // needs insecure package - "golang.org/x/crypto/blowfish" -) - -// Key derives a key from the password, salt and rounds count, returning a -// []byte of length keyLen that can be used as cryptographic key. -// -// Remember to get a good random salt of at least 16 bytes. Using a higher -// rounds count will increase the cost of an exhaustive search but will also -// make derivation proportionally slower. -func Key(password, salt []byte, rounds, keyLen int) ([]byte, error) { - if rounds < 1 { - return nil, errors.New("bcrypt_pbkdf: number of rounds is too small") - } - if len(password) == 0 { - return nil, errors.New("bcrypt_pbkdf: empty password") - } - if len(salt) == 0 || len(salt) > 1<<20 { - return nil, errors.New("bcrypt_pbkdf: bad salt length") - } - if keyLen > 1024 { - return nil, errors.New("bcrypt_pbkdf: keyLen is too large") - } - var shapass, shasalt [sha512.Size]byte - var out, tmp [32]byte - var cnt [4]byte - - numBlocks := (keyLen + len(out) - 1) / len(out) - key := make([]byte, numBlocks*len(out)) - - h := sha512.New() - h.Write(password) - h.Sum(shapass[:0]) - - for block := 1; block <= numBlocks; block++ { - h.Reset() - h.Write(salt) - cnt[0] = byte(block >> 24) - cnt[1] = byte(block >> 16) - cnt[2] = byte(block >> 8) - cnt[3] = byte(block) - h.Write(cnt[:]) - bcryptHash(tmp[:], shapass[:], h.Sum(shasalt[:0])) - copy(out[:], tmp[:]) - - for i := 2; i <= rounds; i++ { - h.Reset() - h.Write(tmp[:]) - bcryptHash(tmp[:], shapass[:], h.Sum(shasalt[:0])) - for j := 0; j < len(out); j++ { - out[j] ^= tmp[j] - } - } - - for i, v := range out { - key[i*numBlocks+(block-1)] = v - } - } - return key[:keyLen], nil -} - -var magic = []byte("OxychromaticBlowfishSwatDynamite") - -func bcryptHash(out, shapass, shasalt []byte) { - c, err := blowfish.NewSaltedCipher(shapass, shasalt) - if err != nil { - panic(err) - } - for i := 0; i < 64; i++ { - blowfish.ExpandKey(shasalt, c) - blowfish.ExpandKey(shapass, c) - } - copy(out, magic) - for i := 0; i < 32; i += 8 { - for j := 0; j < 64; j++ { - c.Encrypt(out[i:i+8], out[i:i+8]) - } - } - // Swap bytes due to different endianness. - for i := 0; i < 32; i += 4 { - out[i+3], out[i+2], out[i+1], out[i] = out[i], out[i+1], out[i+2], out[i+3] - } -} diff --git a/vendor/go.step.sm/crypto/internal/emoji/emoji.go b/vendor/go.step.sm/crypto/internal/emoji/emoji.go deleted file mode 100644 index 7235cff1f5..0000000000 --- a/vendor/go.step.sm/crypto/internal/emoji/emoji.go +++ /dev/null @@ -1,274 +0,0 @@ -package emoji - -import "strings" - -func Emoji(input []byte) string { - var b strings.Builder - for _, r := range input { - b.WriteString(emojiCodeMap[r]) - } - return b.String() -} - -// emojiCodeMap is a mapping from byte to emoji. -// -// The mapping is based on draft+2 of https://github.com/emojisum/emojisum. -// (see: https://github.com/emojisum/emojisum/releases/tag/draft%2B2) -var emojiCodeMap = []string{ - "\U0001f44d", // 👍 :+1: - "\U0001f3b1", // 🎱 :8ball: - "\u2708\ufe0f", // ✈️ :airplane: - "\U0001f47d", // 👽 :alien: - "\u2693", // ⚓ :anchor: - "\U0001f47c", // 👼 :angel: - "\U0001f620", // 😠 :angry: - "\U0001f41c", // 🐜 :ant: - "\U0001f34e", // 🍎 :apple: - "\U0001f3a8", // 🎨 :art: - "\U0001f476", // 👶 :baby: - "\U0001f37c", // 🍼 :baby_bottle: - "\U0001f519", // 🔙 :back: - "\U0001f38d", // 🎍 :bamboo: - "\U0001f34c", // 🍌 :banana: - "\U0001f488", // 💈 :barber: - "\U0001f6c1", // 🛁 :bathtub: - "\U0001f37a", // 🍺 :beer: - "\U0001f514", // 🔔 :bell: - "\U0001f6b4\u200d\u2642\ufe0f", // 🚴‍♂️ :bicyclist: - "\U0001f426", // 🐦 :bird: - "\U0001f382", // 🎂 :birthday: - "\U0001f33c", // 🌼 :blossom: - "\U0001f699", // 🚙 :blue_car: - "\U0001f417", // 🐗 :boar: - "\U0001f4a3", // 💣 :bomb: - "\U0001f4a5", // 💥 :boom: - "\U0001f647\u200d\u2642\ufe0f", // 🙇‍♂️ :bow: - "\U0001f466", // 👦 :boy: - "\U0001f494", // 💔 :broken_heart: - "\U0001f4a1", // 💡 :bulb: - "\U0001f68c", // 🚌 :bus: - "\U0001f335", // 🌵 :cactus: - "\U0001f4c6", // 📆 :calendar: - "\U0001f4f7", // 📷 :camera: - "\U0001f36c", // 🍬 :candy: - "\U0001f431", // 🐱 :cat: - "\U0001f352", // 🍒 :cherries: - "\U0001f6b8", // 🚸 :children_crossing: - "\U0001f36b", // 🍫 :chocolate_bar: - "\U0001f44f", // 👏 :clap: - "\u2601\ufe0f", // ☁️ :cloud: - "\u2663\ufe0f", // ♣️ :clubs: - "\U0001f1e8\U0001f1f3", // 🇨🇳 :cn: - "\u2615", // ☕ :coffee: - "\U0001f6a7", // 🚧 :construction: - "\U0001f36a", // 🍪 :cookie: - "\u00a9\ufe0f", // ©️ :copyright: - "\U0001f33d", // 🌽 :corn: - "\U0001f42e", // 🐮 :cow: - "\U0001f319", // 🌙 :crescent_moon: - "\U0001f451", // 👑 :crown: - "\U0001f622", // 😢 :cry: - "\U0001f52e", // 🔮 :crystal_ball: - "\u27b0", // ➰ :curly_loop: - "\U0001f46f\u200d\u2640\ufe0f", // 👯‍♀️ :dancers: - "\U0001f4a8", // 💨 :dash: - "\U0001f1e9\U0001f1ea", // 🇩🇪 :de: - "\u2666\ufe0f", // ♦️ :diamonds: - "\U0001f436", // 🐶 :dog: - "\U0001f369", // 🍩 :doughnut: - "\U0001f409", // 🐉 :dragon: - "\U0001f4c0", // 📀 :dvd: - "\U0001f442", // 👂 :ear: - "\U0001f346", // 🍆 :eggplant: - "\U0001f418", // 🐘 :elephant: - "\U0001f51a", // 🔚 :end: - "\u2709", // ✉ :envelope: - "\U0001f1ea\U0001f1f8", // 🇪🇸 :es: - "\U0001f440", // 👀 :eyes: - "\U0001f44a", // 👊 :facepunch: - "\U0001f468\u200d\U0001f469\u200d\U0001f466", // 👨‍👩‍👦 :family: - "\U0001f3a1", // 🎡 :ferris_wheel: - "\U0001f630", // 😰 :cold_sweat: - "\U0001f525", // 🔥 :fire: - "\U0001f386", // 🎆 :fireworks: - "\U0001f4be", // 💾 :floppy_disk: - "\U0001f3c8", // 🏈 :football: - "\U0001f374", // 🍴 :fork_and_knife: - "\U0001f340", // 🍀 :four_leaf_clover: - "\U0001f1eb\U0001f1f7", // 🇫🇷 :fr: - "\U0001f35f", // 🍟 :fries: - "\U0001f95c", // 🥜 :peanuts: - "\U0001f595", // 🖕 :fu: - "\U0001f315", // 🌕 :full_moon: - "\U0001f3b2", // 🎲 :game_die: - "\U0001f1ea\U0001f1fa", // 🇪🇺 :eu: - "\U0001f48e", // 💎 :gem: - "\U0001f467", // 👧 :girl: - "\U0001f410", // 🐐 :goat: - "\U0001f62c", // 😬 :grimacing: - "\U0001f601", // 😁 :grin: - "\U0001f482\u200d\u2642\ufe0f", // 💂‍♂️ :guardsman: - "\U0001f3b8", // 🎸 :guitar: - "\U0001f52b", // 🔫 :gun: - "\U0001f354", // 🍔 :hamburger: - "\U0001f528", // 🔨 :hammer: - "\U0001f439", // 🐹 :hamster: - "\U0001f649", // 🙉 :hear_no_evil: - "\u2764\ufe0f", // ❤️ :heart: - "\U0001f63b", // 😻 :heart_eyes_cat: - "\u2763\ufe0f", // ❣️ :heavy_heart_exclamation: - "\u2714\ufe0f", // ✔️ :heavy_check_mark: - "\U0001f5ff", // 🗿 :moyai: - "\U0001f3ee", // 🏮 :izakaya_lantern: - "\U0001f681", // 🚁 :helicopter: - "\U0001f52a", // 🔪 :hocho: - "\U0001f41d", // 🐝 :honeybee: - "\U0001f434", // 🐴 :horse: - "\U0001f3c7", // 🏇 :horse_racing: - "\u231b", // ⌛ :hourglass: - "\U0001f3e0", // 🏠 :house: - "\U0001f575\ufe0f\u200d\u2640\ufe0f", // 🕵️‍♀️ :female_detective: - "\U0001f366", // 🍦 :icecream: - "\U0001f47f", // 👿 :imp: - "\U0001f1ee\U0001f1f9", // 🇮🇹 :it: - "\U0001f383", // 🎃 :jack_o_lantern: - "\U0001f47a", // 👺 :japanese_goblin: - "\U0001f1ef\U0001f1f5", // 🇯🇵 :jp: - "\U0001f511", // 🔑 :key: - "\U0001f48b", // 💋 :kiss: - "\U0001f63d", // 😽 :kissing_cat: - "\U0001f428", // 🐨 :koala: - "\U0001f1f0\U0001f1f7", // 🇰🇷 :kr: - "\U0001f34b", // 🍋 :lemon: - "\U0001f484", // 💄 :lipstick: - "\U0001f512", // 🔒 :lock: - "\U0001f36d", // 🍭 :lollipop: - "\U0001f468", // 👨 :man: - "\U0001f341", // 🍁 :maple_leaf: - "\U0001f637", // 😷 :mask: - "\U0001f918", // 🤘 :metal: - "\U0001f52c", // 🔬 :microscope: - "\U0001f4b0", // 💰 :moneybag: - "\U0001f412", // 🐒 :monkey: - "\U0001f5fb", // 🗻 :mount_fuji: - "\U0001f4aa", // 💪 :muscle: - "\U0001f344", // 🍄 :mushroom: - "\U0001f3b9", // 🎹 :musical_keyboard: - "\U0001f3bc", // 🎼 :musical_score: - "\U0001f485", // 💅 :nail_care: - "\U0001f311", // 🌑 :new_moon: - "\u26d4", // ⛔ :no_entry: - "\U0001f443", // 👃 :nose: - "\U0001f39b\ufe0f", // 🎛️ :control_knobs: - "\U0001f529", // 🔩 :nut_and_bolt: - "\u2b55", // ⭕ :o: - "\U0001f30a", // 🌊 :ocean: - "\U0001f44c", // 👌 :ok_hand: - "\U0001f51b", // 🔛 :on: - "\U0001f4e6", // 📦 :package: - "\U0001f334", // 🌴 :palm_tree: - "\U0001f43c", // 🐼 :panda_face: - "\U0001f4ce", // 📎 :paperclip: - "\u26c5", // ⛅ :partly_sunny: - "\U0001f6c2", // 🛂 :passport_control: - "\U0001f43e", // 🐾 :paw_prints: - "\U0001f351", // 🍑 :peach: - "\U0001f427", // 🐧 :penguin: - "\u260e\ufe0f", // ☎️ :phone: - "\U0001f437", // 🐷 :pig: - "\U0001f48a", // 💊 :pill: - "\U0001f34d", // 🍍 :pineapple: - "\U0001f355", // 🍕 :pizza: - "\U0001f448", // 👈 :point_left: - "\U0001f449", // 👉 :point_right: - "\U0001f4a9", // 💩 :poop: - "\U0001f357", // 🍗 :poultry_leg: - "\U0001f64f", // 🙏 :pray: - "\U0001f478", // 👸 :princess: - "\U0001f45b", // 👛 :purse: - "\U0001f4cc", // 📌 :pushpin: - "\U0001f430", // 🐰 :rabbit: - "\U0001f308", // 🌈 :rainbow: - "\u270b", // ✋ :raised_hand: - "\u267b\ufe0f", // ♻️ :recycle: - "\U0001f697", // 🚗 :red_car: - "\u00ae\ufe0f", // ®️ :registered: - "\U0001f380", // 🎀 :ribbon: - "\U0001f35a", // 🍚 :rice: - "\U0001f680", // 🚀 :rocket: - "\U0001f3a2", // 🎢 :roller_coaster: - "\U0001f413", // 🐓 :rooster: - "\U0001f1f7\U0001f1fa", // 🇷🇺 :ru: - "\u26f5", // ⛵ :sailboat: - "\U0001f385", // 🎅 :santa: - "\U0001f6f0\ufe0f", // 🛰️ :satellite: - "\U0001f606", // 😆 :satisfied: - "\U0001f3b7", // 🎷 :saxophone: - "\u2702\ufe0f", // ✂️ :scissors: - "\U0001f648", // 🙈 :see_no_evil: - "\U0001f411", // 🐑 :sheep: - "\U0001f41a", // 🐚 :shell: - "\U0001f45e", // 👞 :shoe: - "\U0001f3bf", // 🎿 :ski: - "\U0001f480", // 💀 :skull: - "\U0001f62a", // 😪 :sleepy: - "\U0001f604", // 😄 :smile: - "\U0001f63a", // 😺 :smiley_cat: - "\U0001f60f", // 😏 :smirk: - "\U0001f6ac", // 🚬 :smoking: - "\U0001f40c", // 🐌 :snail: - "\U0001f40d", // 🐍 :snake: - "\u2744\ufe0f", // ❄️ :snowflake: - "\u26bd", // ⚽ :soccer: - "\U0001f51c", // 🔜 :soon: - "\U0001f47e", // 👾 :space_invader: - "\u2660\ufe0f", // ♠️ :spades: - "\U0001f64a", // 🙊 :speak_no_evil: - "\u2b50", // ⭐ :star: - "\u26f2", // ⛲ :fountain: - "\U0001f5fd", // 🗽 :statue_of_liberty: - "\U0001f682", // 🚂 :steam_locomotive: - "\U0001f33b", // 🌻 :sunflower: - "\U0001f60e", // 😎 :sunglasses: - "\u2600\ufe0f", // ☀️ :sunny: - "\U0001f305", // 🌅 :sunrise: - "\U0001f3c4\u200d\u2642\ufe0f", // 🏄‍♂️ :surfer: - "\U0001f3ca\u200d\u2642\ufe0f", // 🏊‍♂️ :swimmer: - "\U0001f489", // 💉 :syringe: - "\U0001f389", // 🎉 :tada: - "\U0001f34a", // 🍊 :tangerine: - "\U0001f695", // 🚕 :taxi: - "\U0001f3be", // 🎾 :tennis: - "\u26fa", // ⛺ :tent: - "\U0001f4ad", // 💭 :thought_balloon: - "\u2122\ufe0f", // ™️ :tm: - "\U0001f6bd", // 🚽 :toilet: - "\U0001f445", // 👅 :tongue: - "\U0001f3a9", // 🎩 :tophat: - "\U0001f69c", // 🚜 :tractor: - "\U0001f68e", // 🚎 :trolleybus: - "\U0001f922", // 🤢 :nauseated_face: - "\U0001f3c6", // 🏆 :trophy: - "\U0001f3ba", // 🎺 :trumpet: - "\U0001f422", // 🐢 :turtle: - "\U0001f3a0", // 🎠 :carousel_horse: - "\U0001f46d", // 👭 :two_women_holding_hands: - "\U0001f1ec\U0001f1e7", // 🇬🇧 :uk: - "\u2602\ufe0f", // ☂️ :umbrella: - "\U0001f513", // 🔓 :unlock: - "\U0001f1fa\U0001f1f8", // 🇺🇸 :us: - "\u270c\ufe0f", // ✌️ :v: - "\U0001f4fc", // 📼 :vhs: - "\U0001f3bb", // 🎻 :violin: - "\u26a0\ufe0f", // ⚠️ :warning: - "\U0001f349", // 🍉 :watermelon: - "\U0001f44b", // 👋 :wave: - "\u3030\ufe0f", // 〰️ :wavy_dash: - "\U0001f6be", // 🚾 :wc: - "\u267f", // ♿ :wheelchair: - "\U0001f469", // 👩 :woman: - "\u274c", // ❌ :x: - "\U0001f60b", // 😋 :yum: - "\u26a1", // ⚡ :zap: - "\U0001f4a4", // 💤 :zzz: -} diff --git a/vendor/go.step.sm/crypto/internal/utils/io.go b/vendor/go.step.sm/crypto/internal/utils/io.go deleted file mode 100644 index ccccf5f94f..0000000000 --- a/vendor/go.step.sm/crypto/internal/utils/io.go +++ /dev/null @@ -1,70 +0,0 @@ -package utils - -import ( - "bytes" - "io" - "os" - "unicode" - - "github.com/pkg/errors" - - "go.step.sm/crypto/internal/utils/utfbom" -) - -func maybeUnwrap(err error) error { - if wrapped := errors.Unwrap(err); wrapped != nil { - return wrapped - } - return err -} - -// stdinFilename is the name of the file that is used in many command -// line utilities to denote input is to be read from STDIN. -const stdinFilename = "-" - -// stdin points to STDIN through os.Stdin. -var stdin = os.Stdin - -// ReadFile reads the file identified by filename and returns -// the contents. If filename is equal to "-", it will read from -// STDIN. -func ReadFile(filename string) (b []byte, err error) { - if filename == stdinFilename { - filename = "/dev/stdin" - b, err = io.ReadAll(stdin) - } else { - var contents []byte - contents, err = os.ReadFile(filename) - if err != nil { - return nil, errors.Wrapf(maybeUnwrap(err), "error reading %q", filename) - } - b, err = io.ReadAll(utfbom.SkipOnly(bytes.NewReader(contents))) - } - if err != nil { - return nil, errors.Wrapf(maybeUnwrap(err), "error reading %q", filename) - } - return -} - -// ReadPasswordFromFile reads and returns the password from the given filename. -// The contents of the file will be trimmed at the right. -func ReadPasswordFromFile(filename string) ([]byte, error) { - password, err := ReadFile(filename) - if err != nil { - return nil, errors.Wrapf(err, "error reading %s", filename) - } - password = bytes.TrimRightFunc(password, unicode.IsSpace) - return password, nil -} - -// WriteFile writes data to a file named by filename. -// If the file does not exist, WriteFile creates it with permissions perm -// (before umask); otherwise WriteFile truncates it before writing. -// -// It wraps os.WriteFile wrapping the errors. -func WriteFile(filename string, data []byte, perm os.FileMode) error { - if err := os.WriteFile(filename, data, perm); err != nil { - return errors.Wrapf(maybeUnwrap(err), "error writing %s", filename) - } - return nil -} diff --git a/vendor/go.step.sm/crypto/internal/utils/utfbom/LICENSE b/vendor/go.step.sm/crypto/internal/utils/utfbom/LICENSE deleted file mode 100644 index 6279cb87f4..0000000000 --- a/vendor/go.step.sm/crypto/internal/utils/utfbom/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright (c) 2018-2020, Dmitrij Koniajev (dimchansky@gmail.com) - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/go.step.sm/crypto/internal/utils/utfbom/README.md b/vendor/go.step.sm/crypto/internal/utils/utfbom/README.md deleted file mode 100644 index 8ece280089..0000000000 --- a/vendor/go.step.sm/crypto/internal/utils/utfbom/README.md +++ /dev/null @@ -1,66 +0,0 @@ -# utfbom [![Godoc](https://godoc.org/github.com/dimchansky/utfbom?status.png)](https://godoc.org/github.com/dimchansky/utfbom) [![License](https://img.shields.io/:license-apache-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![Build Status](https://travis-ci.org/dimchansky/utfbom.svg?branch=master)](https://travis-ci.org/dimchansky/utfbom) [![Go Report Card](https://goreportcard.com/badge/github.com/dimchansky/utfbom)](https://goreportcard.com/report/github.com/dimchansky/utfbom) [![Coverage Status](https://coveralls.io/repos/github/dimchansky/utfbom/badge.svg?branch=master)](https://coveralls.io/github/dimchansky/utfbom?branch=master) - -The package utfbom implements the detection of the BOM (Unicode Byte Order Mark) and removing as necessary. It can also return the encoding detected by the BOM. - -## Installation - - go get -u github.com/dimchansky/utfbom - -## Example - -```go -package main - -import ( - "bytes" - "fmt" - "io/ioutil" - - "github.com/dimchansky/utfbom" -) - -func main() { - trySkip([]byte("\xEF\xBB\xBFhello")) - trySkip([]byte("hello")) -} - -func trySkip(byteData []byte) { - fmt.Println("Input:", byteData) - - // just skip BOM - output, err := ioutil.ReadAll(utfbom.SkipOnly(bytes.NewReader(byteData))) - if err != nil { - fmt.Println(err) - return - } - fmt.Println("ReadAll with BOM skipping", output) - - // skip BOM and detect encoding - sr, enc := utfbom.Skip(bytes.NewReader(byteData)) - fmt.Printf("Detected encoding: %s\n", enc) - output, err = ioutil.ReadAll(sr) - if err != nil { - fmt.Println(err) - return - } - fmt.Println("ReadAll with BOM detection and skipping", output) - fmt.Println() -} -``` - -Output: - -``` -$ go run main.go -Input: [239 187 191 104 101 108 108 111] -ReadAll with BOM skipping [104 101 108 108 111] -Detected encoding: UTF8 -ReadAll with BOM detection and skipping [104 101 108 108 111] - -Input: [104 101 108 108 111] -ReadAll with BOM skipping [104 101 108 108 111] -Detected encoding: Unknown -ReadAll with BOM detection and skipping [104 101 108 108 111] -``` - - diff --git a/vendor/go.step.sm/crypto/internal/utils/utfbom/utfbom.go b/vendor/go.step.sm/crypto/internal/utils/utfbom/utfbom.go deleted file mode 100644 index 93a144fd2c..0000000000 --- a/vendor/go.step.sm/crypto/internal/utils/utfbom/utfbom.go +++ /dev/null @@ -1,195 +0,0 @@ -// Package utfbom implements the detection of the BOM (Unicode Byte Order Mark) and removing as necessary. -// It wraps an io.Reader object, creating another object (Reader) that also implements the io.Reader -// interface but provides automatic BOM checking and removing as necessary. -// -// This package was copied from https://github.com/dimchansky/utfbom. Only minor changes -// were made to not depend on the io/ioutil package and to make our linters pass. -package utfbom - -import ( - "errors" - "io" -) - -// Encoding is type alias for detected UTF encoding. -type Encoding int - -// Constants to identify detected UTF encodings. -const ( - // Unknown encoding, returned when no BOM was detected - Unknown Encoding = iota - - // UTF8, BOM bytes: EF BB BF - UTF8 - - // UTF-16, big-endian, BOM bytes: FE FF - UTF16BigEndian - - // UTF-16, little-endian, BOM bytes: FF FE - UTF16LittleEndian - - // UTF-32, big-endian, BOM bytes: 00 00 FE FF - UTF32BigEndian - - // UTF-32, little-endian, BOM bytes: FF FE 00 00 - UTF32LittleEndian -) - -// String returns a user-friendly string representation of the encoding. Satisfies fmt.Stringer interface. -func (e Encoding) String() string { - switch e { - case UTF8: - return "UTF8" - case UTF16BigEndian: - return "UTF16BigEndian" - case UTF16LittleEndian: - return "UTF16LittleEndian" - case UTF32BigEndian: - return "UTF32BigEndian" - case UTF32LittleEndian: - return "UTF32LittleEndian" - default: - return "Unknown" - } -} - -const maxConsecutiveEmptyReads = 100 - -// Skip creates Reader which automatically detects BOM (Unicode Byte Order Mark) and removes it as necessary. -// It also returns the encoding detected by the BOM. -// If the detected encoding is not needed, you can call the SkipOnly function. -func Skip(rd io.Reader) (*Reader, Encoding) { - // Is it already a Reader? - b, ok := rd.(*Reader) - if ok { - return b, Unknown - } - - enc, left, err := detectUtf(rd) - return &Reader{ - rd: rd, - buf: left, - err: err, - }, enc -} - -// SkipOnly creates Reader which automatically detects BOM (Unicode Byte Order Mark) and removes it as necessary. -func SkipOnly(rd io.Reader) *Reader { - r, _ := Skip(rd) - return r -} - -// Reader implements automatic BOM (Unicode Byte Order Mark) checking and -// removing as necessary for an io.Reader object. -type Reader struct { - rd io.Reader // reader provided by the client - buf []byte // buffered data - err error // last error -} - -// Read is an implementation of io.Reader interface. -// The bytes are taken from the underlying Reader, but it checks for BOMs, removing them as necessary. -func (r *Reader) Read(p []byte) (n int, err error) { - if len(p) == 0 { - return 0, nil - } - - if r.buf == nil { - if r.err != nil { - return 0, r.readErr() - } - - return r.rd.Read(p) - } - - // copy as much as we can - n = copy(p, r.buf) - r.buf = nilIfEmpty(r.buf[n:]) - return n, nil -} - -func (r *Reader) readErr() error { - err := r.err - r.err = nil - return err -} - -var errNegativeRead = errors.New("utfbom: reader returned negative count from Read") - -func detectUtf(rd io.Reader) (enc Encoding, buf []byte, err error) { - buf, err = readBOM(rd) - - if len(buf) >= 4 { - if isUTF32BigEndianBOM4(buf) { - return UTF32BigEndian, nilIfEmpty(buf[4:]), err - } - if isUTF32LittleEndianBOM4(buf) { - return UTF32LittleEndian, nilIfEmpty(buf[4:]), err - } - } - - if len(buf) > 2 && isUTF8BOM3(buf) { - return UTF8, nilIfEmpty(buf[3:]), err - } - - if (err != nil && !errors.Is(err, io.EOF)) || (len(buf) < 2) { - return Unknown, nilIfEmpty(buf), err - } - - if isUTF16BigEndianBOM2(buf) { - return UTF16BigEndian, nilIfEmpty(buf[2:]), err - } - if isUTF16LittleEndianBOM2(buf) { - return UTF16LittleEndian, nilIfEmpty(buf[2:]), err - } - - return Unknown, nilIfEmpty(buf), err -} - -func readBOM(rd io.Reader) (buf []byte, err error) { - const maxBOMSize = 4 - var bom [maxBOMSize]byte // used to read BOM - - // read as many bytes as possible - for nEmpty, n := 0, 0; err == nil && len(buf) < maxBOMSize; buf = bom[:len(buf)+n] { //nolint:wastedassign // copied code - if n, err = rd.Read(bom[len(buf):]); n < 0 { - return nil, errNegativeRead - } - if n > 0 { - nEmpty = 0 - } else { - nEmpty++ - if nEmpty >= maxConsecutiveEmptyReads { - err = io.ErrNoProgress - } - } - } - return -} - -func isUTF32BigEndianBOM4(buf []byte) bool { - return buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0xFE && buf[3] == 0xFF -} - -func isUTF32LittleEndianBOM4(buf []byte) bool { - return buf[0] == 0xFF && buf[1] == 0xFE && buf[2] == 0x00 && buf[3] == 0x00 -} - -func isUTF8BOM3(buf []byte) bool { - return buf[0] == 0xEF && buf[1] == 0xBB && buf[2] == 0xBF -} - -func isUTF16BigEndianBOM2(buf []byte) bool { - return buf[0] == 0xFE && buf[1] == 0xFF -} - -func isUTF16LittleEndianBOM2(buf []byte) bool { - return buf[0] == 0xFF && buf[1] == 0xFE -} - -func nilIfEmpty(buf []byte) (res []byte) { - if len(buf) > 0 { - res = buf - } - return -} diff --git a/vendor/go.step.sm/crypto/jose/encrypt.go b/vendor/go.step.sm/crypto/jose/encrypt.go deleted file mode 100644 index 9b61a5f448..0000000000 --- a/vendor/go.step.sm/crypto/jose/encrypt.go +++ /dev/null @@ -1,135 +0,0 @@ -package jose - -import ( - "encoding/json" - - "github.com/pkg/errors" - "go.step.sm/crypto/randutil" -) - -// MaxDecryptTries is the maximum number of attempts to decrypt a file. -const MaxDecryptTries = 3 - -// PasswordPrompter defines the function signature for the PromptPassword -// callback. -type PasswordPrompter func(s string) ([]byte, error) - -// PromptPassword is a method used to prompt for a password to decode encrypted -// keys. If this method is not defined and the key or password are not passed, -// the parse of the key will fail. -var PromptPassword PasswordPrompter - -// Encrypt returns the given data encrypted with the default encryption -// algorithm (PBES2-HS256+A128KW). -func Encrypt(data []byte, opts ...Option) (*JSONWebEncryption, error) { - ctx, err := new(context).apply(opts...) - if err != nil { - return nil, err - } - - var passphrase []byte - switch { - case len(ctx.password) > 0: - passphrase = ctx.password - case ctx.passwordPrompter != nil: - if passphrase, err = ctx.passwordPrompter(ctx.passwordPrompt); err != nil { - return nil, err - } - case PromptPassword != nil: - if passphrase, err = PromptPassword("Please enter the password to encrypt the data"); err != nil { - return nil, err - } - default: - return nil, errors.New("failed to encrypt the data: missing password") - } - - salt, err := randutil.Salt(PBKDF2SaltSize) - if err != nil { - return nil, err - } - - // Encrypt private key using PBES2 - recipient := Recipient{ - Algorithm: PBES2_HS256_A128KW, - Key: passphrase, - PBES2Count: PBKDF2Iterations, - PBES2Salt: salt, - } - - encrypterOptions := new(EncrypterOptions) - if ctx.contentType != "" { - encrypterOptions.WithContentType(ContentType(ctx.contentType)) - } - - encrypter, err := NewEncrypter(DefaultEncAlgorithm, recipient, encrypterOptions) - if err != nil { - return nil, errors.Wrap(err, "error creating cipher") - } - - jwe, err := encrypter.Encrypt(data) - if err != nil { - return nil, errors.Wrap(err, "error encrypting data") - } - - return jwe, nil -} - -// EncryptJWK returns the given JWK encrypted with the default encryption -// algorithm (PBES2-HS256+A128KW). -func EncryptJWK(jwk *JSONWebKey, passphrase []byte) (*JSONWebEncryption, error) { - b, err := json.Marshal(jwk) - if err != nil { - return nil, errors.Wrap(err, "error marshaling JWK") - } - - return Encrypt(b, WithPassword(passphrase), WithContentType("jwk+json")) -} - -// Decrypt returns the decrypted version of the given data if it's encrypted, -// it will return the raw data if it's not encrypted or the format is not -// valid. -func Decrypt(data []byte, opts ...Option) ([]byte, error) { - ctx, err := new(context).apply(opts...) - if err != nil { - return nil, err - } - - enc, err := ParseEncrypted(string(data)) - if err != nil { - return data, nil //nolint:nilerr // Return the given data if we cannot parse it as encrypted. - } - - // Try with the given password. - if len(ctx.password) > 0 { - if data, err = enc.Decrypt(ctx.password); err == nil { - return data, nil - } - return nil, errors.New("failed to decrypt JWE: invalid password") - } - - // Try with a given password prompter. - if ctx.passwordPrompter != nil || PromptPassword != nil { - var pass []byte - for i := 0; i < MaxDecryptTries; i++ { - switch { - case ctx.passwordPrompter != nil: - if pass, err = ctx.passwordPrompter(ctx.passwordPrompt); err != nil { - return nil, err - } - case ctx.filename != "": - if pass, err = PromptPassword("Please enter the password to decrypt " + ctx.filename); err != nil { - return nil, err - } - default: - if pass, err = PromptPassword("Please enter the password to decrypt the JWE"); err != nil { - return nil, err - } - } - if data, err = enc.Decrypt(pass); err == nil { - return data, nil - } - } - } - - return nil, errors.New("failed to decrypt JWE: invalid password") -} diff --git a/vendor/go.step.sm/crypto/jose/generate.go b/vendor/go.step.sm/crypto/jose/generate.go deleted file mode 100644 index 4bdc6c44dc..0000000000 --- a/vendor/go.step.sm/crypto/jose/generate.go +++ /dev/null @@ -1,204 +0,0 @@ -package jose - -import ( - "crypto" - "crypto/ecdsa" - "crypto/ed25519" - "crypto/rsa" - "crypto/x509" - "encoding/base64" - - "github.com/pkg/errors" - "go.step.sm/crypto/keyutil" - "go.step.sm/crypto/pemutil" - "go.step.sm/crypto/x25519" -) - -const ( - jwksUsageSig = "sig" - jwksUsageEnc = "enc" - // defaultKeyType is the default type of the one-time token key. - defaultKeyType = EC - // defaultKeyCurve is the default curve of the one-time token key. - defaultKeyCurve = P256 - // defaultKeyAlg is the default algorithm of the one-time token key. - defaultKeyAlg = ES256 - // defaultKeySize is the default size of the one-time token key. - defaultKeySize = 0 -) - -var ( - errAmbiguousCertKeyUsage = errors.New("jose/generate: certificate's key usage is ambiguous, it should be for signature or encipherment, but not both (use --subtle to ignore usage field)") - errNoCertKeyUsage = errors.New("jose/generate: certificate doesn't contain any key usage (use --subtle to ignore usage field)") -) - -// Thumbprint computes the JWK Thumbprint of a key using SHA256 as the hash -// algorithm. It returns the hash encoded in the Base64 raw url encoding. -func Thumbprint(jwk *JSONWebKey) (string, error) { - var sum []byte - var err error - switch key := jwk.Key.(type) { - case x25519.PublicKey: - sum, err = x25519Thumbprint(key, crypto.SHA256) - case x25519.PrivateKey: - var pub x25519.PublicKey - if pub, err = key.PublicKey(); err == nil { - sum, err = x25519Thumbprint(pub, crypto.SHA256) - } - case OpaqueSigner: - sum, err = key.Public().Thumbprint(crypto.SHA256) - default: - sum, err = jwk.Thumbprint(crypto.SHA256) - } - if err != nil { - return "", errors.Wrap(err, "error generating JWK thumbprint") - } - return base64.RawURLEncoding.EncodeToString(sum), nil -} - -// GenerateDefaultKeyPair generates an asymmetric public/private key pair. -// Returns the public key as a JWK and the private key as an encrypted JWE. -func GenerateDefaultKeyPair(passphrase []byte) (*JSONWebKey, *JSONWebEncryption, error) { - if len(passphrase) == 0 { - return nil, nil, errors.New("step-jose: password cannot be empty when encryptying a JWK") - } - - // Generate the OTT key - jwk, err := GenerateJWK(defaultKeyType, defaultKeyCurve, defaultKeyAlg, jwksUsageSig, "", defaultKeySize) - if err != nil { - return nil, nil, err - } - - jwk.KeyID, err = Thumbprint(jwk) - if err != nil { - return nil, nil, err - } - - jwe, err := EncryptJWK(jwk, passphrase) - if err != nil { - return nil, nil, err - } - - public := jwk.Public() - return &public, jwe, nil -} - -// GenerateJWK generates a JWK given the key type, curve, alg, use, kid and -// the size of the RSA or oct keys if necessary. -func GenerateJWK(kty, crv, alg, use, kid string, size int) (jwk *JSONWebKey, err error) { - if kty == "OKP" && use == "enc" && (crv == "" || crv == "Ed25519") { - return nil, errors.New("invalid algorithm: Ed25519 cannot be used for encryption") - } - - switch { - case kty == "EC" && crv == "": - crv = P256 - case kty == "OKP" && crv == "": - crv = Ed25519 - case kty == "RSA" && size == 0: - size = DefaultRSASize - case kty == "oct" && size == 0: - size = DefaultOctSize - } - - key, err := keyutil.GenerateKey(kty, crv, size) - if err != nil { - return nil, err - } - jwk = &JSONWebKey{ - Key: key, - KeyID: kid, - Use: use, - Algorithm: alg, - } - guessJWKAlgorithm(&context{alg: alg}, jwk) - if jwk.KeyID == "" && kty != "oct" { - jwk.KeyID, err = Thumbprint(jwk) - } - return jwk, err -} - -// GenerateJWKFromPEM returns an incomplete JSONWebKey using the key from a -// PEM file. -func GenerateJWKFromPEM(filename string, subtle bool) (*JSONWebKey, error) { - key, err := pemutil.Read(filename) - if err != nil { - return nil, err - } - - switch key := key.(type) { - case *rsa.PrivateKey, *rsa.PublicKey: - return &JSONWebKey{ - Key: key, - }, nil - case *ecdsa.PrivateKey, *ecdsa.PublicKey, ed25519.PrivateKey, ed25519.PublicKey: - return &JSONWebKey{ - Key: key, - Algorithm: algForKey(key), - }, nil - case *x509.Certificate: - var use string - if !subtle { - use, err = keyUsageForCert(key) - if err != nil { - return nil, err - } - } - return &JSONWebKey{ - Key: key.PublicKey, - Certificates: []*x509.Certificate{key}, - Algorithm: algForKey(key.PublicKey), - Use: use, - }, nil - default: - return nil, errors.Errorf("error parsing %s: unsupported key type '%T'", filename, key) - } -} - -func algForKey(key crypto.PublicKey) string { - switch key := key.(type) { - case *ecdsa.PrivateKey: - return getECAlgorithm(key.Curve) - case *ecdsa.PublicKey: - return getECAlgorithm(key.Curve) - case ed25519.PrivateKey, ed25519.PublicKey: - return EdDSA - default: - return "" - } -} - -func keyUsageForCert(cert *x509.Certificate) (string, error) { - isDigitalSignature := containsUsage(cert.KeyUsage, - x509.KeyUsageDigitalSignature, - x509.KeyUsageContentCommitment, - x509.KeyUsageCertSign, - x509.KeyUsageCRLSign, - ) - isEncipherment := containsUsage(cert.KeyUsage, - x509.KeyUsageKeyEncipherment, - x509.KeyUsageDataEncipherment, - x509.KeyUsageKeyAgreement, - x509.KeyUsageEncipherOnly, - x509.KeyUsageDecipherOnly, - ) - if isDigitalSignature && isEncipherment { - return "", errAmbiguousCertKeyUsage - } - if isDigitalSignature { - return jwksUsageSig, nil - } - if isEncipherment { - return jwksUsageEnc, nil - } - return "", errNoCertKeyUsage -} - -func containsUsage(usage x509.KeyUsage, queries ...x509.KeyUsage) bool { - for _, query := range queries { - if usage&query == query { - return true - } - } - return false -} diff --git a/vendor/go.step.sm/crypto/jose/options.go b/vendor/go.step.sm/crypto/jose/options.go deleted file mode 100644 index e1e1393b48..0000000000 --- a/vendor/go.step.sm/crypto/jose/options.go +++ /dev/null @@ -1,125 +0,0 @@ -package jose - -import ( - "go.step.sm/crypto/internal/utils" -) - -type context struct { - filename string - use, alg, kid string - subtle, insecure bool - noDefaults bool - password []byte - passwordPrompt string - passwordPrompter PasswordPrompter - contentType string -} - -// apply the options to the context and returns an error if one of the options -// fails. -func (ctx *context) apply(opts ...Option) (*context, error) { - for _, opt := range opts { - if err := opt(ctx); err != nil { - return nil, err - } - } - return ctx, nil -} - -// Option is the type used to add attributes to the context. -type Option func(ctx *context) error - -// WithFilename adds the given filename to the context. -func WithFilename(filename string) Option { - return func(ctx *context) error { - ctx.filename = filename - return nil - } -} - -// WithUse adds the use claim to the context. -func WithUse(use string) Option { - return func(ctx *context) error { - ctx.use = use - return nil - } -} - -// WithAlg adds the alg claim to the context. -func WithAlg(alg string) Option { - return func(ctx *context) error { - ctx.alg = alg - return nil - } -} - -// WithKid adds the kid property to the context. -func WithKid(kid string) Option { - return func(ctx *context) error { - ctx.kid = kid - return nil - } -} - -// WithSubtle marks the context as subtle. -func WithSubtle(subtle bool) Option { - return func(ctx *context) error { - ctx.subtle = subtle - return nil - } -} - -// WithInsecure marks the context as insecure. -func WithInsecure(insecure bool) Option { - return func(ctx *context) error { - ctx.insecure = insecure - return nil - } -} - -// WithNoDefaults avoids that the parser loads defaults values, specially the -// default algorithms. -func WithNoDefaults(val bool) Option { - return func(ctx *context) error { - ctx.noDefaults = val - return nil - } -} - -// WithPassword is a method that adds the given password to the context. -func WithPassword(pass []byte) Option { - return func(ctx *context) error { - ctx.password = pass - return nil - } -} - -// WithPasswordFile is a method that adds the password in a file to the context. -func WithPasswordFile(filename string) Option { - return func(ctx *context) error { - b, err := utils.ReadPasswordFromFile(filename) - if err != nil { - return err - } - ctx.password = b - return nil - } -} - -// WithPasswordPrompter defines a method that can be used to prompt for the -// password to decrypt an encrypted JWE. -func WithPasswordPrompter(prompt string, fn PasswordPrompter) Option { - return func(ctx *context) error { - ctx.passwordPrompt = prompt - ctx.passwordPrompter = fn - return nil - } -} - -// WithContentType adds the content type when encrypting data. -func WithContentType(cty string) Option { - return func(ctx *context) error { - ctx.contentType = cty - return nil - } -} diff --git a/vendor/go.step.sm/crypto/jose/parse.go b/vendor/go.step.sm/crypto/jose/parse.go deleted file mode 100644 index 760c4f161f..0000000000 --- a/vendor/go.step.sm/crypto/jose/parse.go +++ /dev/null @@ -1,411 +0,0 @@ -package jose - -import ( - "bytes" - "crypto" - "crypto/ecdsa" - "crypto/ed25519" - "crypto/elliptic" - "crypto/rsa" - "crypto/x509" - "encoding/base64" - "encoding/json" - "io" - "net/http" - "os" - "strings" - "time" - - "github.com/pkg/errors" - "go.step.sm/crypto/pemutil" - "go.step.sm/crypto/x25519" -) - -type keyType int - -const ( - jwkKeyType keyType = iota - pemKeyType - octKeyType -) - -// read returns the bytes from reading a file, or from a url if the filename has -// the prefix https:// -func read(filename string) ([]byte, error) { - if strings.HasPrefix(filename, "https://") { - resp, err := http.Get(filename) //nolint:gosec // no SSRF - if err != nil { - return nil, errors.Wrapf(err, "error retrieving %s", filename) - } - defer resp.Body.Close() - - if resp.StatusCode >= 400 { - return nil, errors.Errorf("error retrieving %s: status code %d", filename, resp.StatusCode) - } - b, err := io.ReadAll(resp.Body) - return b, errors.Wrapf(err, "error retrieving %s", filename) - } - - b, err := os.ReadFile(filename) - if err != nil { - return nil, errors.Wrapf(err, "error reading %s", filename) - } - return b, nil -} - -// ReadKey returns a JSONWebKey from the given JWK or PEM file. If the file is -// password protected, and no password or prompt password function is given it -// will fail. -func ReadKey(filename string, opts ...Option) (*JSONWebKey, error) { - b, err := read(filename) - if err != nil { - return nil, err - } - opts = append(opts, WithFilename(filename)) - return ParseKey(b, opts...) -} - -// ParseKey returns a JSONWebKey from the given JWK file or a PEM file. If the -// file is password protected, and no password or prompt password function is -// given it will fail. -func ParseKey(b []byte, opts ...Option) (*JSONWebKey, error) { - ctx, err := new(context).apply(opts...) - if err != nil { - return nil, err - } - if ctx.filename == "" { - ctx.filename = "key" - } - - jwk := new(JSONWebKey) - switch guessKeyType(ctx, b) { - case jwkKeyType: - // Attempt to parse an encrypted file - if b, err = Decrypt(b, opts...); err != nil { - return nil, err - } - - // Unmarshal the plain (or decrypted JWK) - if err = json.Unmarshal(b, jwk); err != nil { - return nil, errors.Errorf("error reading %s: unsupported format", ctx.filename) - } - - // If KeyID not set by environment, then use the default. - // NOTE: we do not set this value by default in the case of jwkKeyType - // because it is assumed to have been left empty on purpose. - case pemKeyType: - pemOptions := []pemutil.Options{ - pemutil.WithFilename(ctx.filename), - } - if ctx.password != nil { - pemOptions = append(pemOptions, pemutil.WithPassword(ctx.password)) - } - if ctx.passwordPrompter != nil { - pemOptions = append(pemOptions, pemutil.WithPasswordPrompt(ctx.passwordPrompt, pemutil.PasswordPrompter(ctx.passwordPrompter))) - } - if pemutil.PromptPassword == nil && PromptPassword != nil { - pemutil.PromptPassword = pemutil.PasswordPrompter(PromptPassword) - } - - jwk.Key, err = pemutil.ParseKey(b, pemOptions...) - if err != nil { - return nil, err - } - if ctx.kid == "" { - if jwk.KeyID, err = Thumbprint(jwk); err != nil { - return nil, err - } - } - case octKeyType: - jwk.Key = b - } - - // Validate key id - if ctx.kid != "" && jwk.KeyID != "" && ctx.kid != jwk.KeyID { - return nil, errors.Errorf("kid %s does not match the kid on %s", ctx.kid, ctx.filename) - } - if jwk.KeyID == "" { - jwk.KeyID = ctx.kid - } - if jwk.Use == "" { - jwk.Use = ctx.use - } - - // Set the algorithm if empty - guessJWKAlgorithm(ctx, jwk) - - // Validate alg: if the flag '--subtle' is passed we will allow to overwrite it - if !ctx.subtle && ctx.alg != "" && jwk.Algorithm != "" && ctx.alg != jwk.Algorithm { - return nil, errors.Errorf("alg %s does not match the alg on %s", ctx.alg, ctx.filename) - } - if ctx.subtle && ctx.alg != "" { - jwk.Algorithm = ctx.alg - } - - return jwk, nil -} - -// ReadKeySet reads a JWK Set from a URL or filename. URLs must start with -// "https://". -func ReadKeySet(filename string, opts ...Option) (*JSONWebKey, error) { - b, err := read(filename) - if err != nil { - return nil, err - } - opts = append(opts, WithFilename(filename)) - return ParseKeySet(b, opts...) -} - -// ParseKeySet returns the JWK with the given key after parsing a JWKSet from -// a given file. -func ParseKeySet(b []byte, opts ...Option) (*JSONWebKey, error) { - ctx, err := new(context).apply(opts...) - if err != nil { - return nil, err - } - - // Attempt to parse an encrypted file - if b, err = Decrypt(b, opts...); err != nil { - return nil, err - } - - // Unmarshal the plain or decrypted JWKSet - jwkSet := new(JSONWebKeySet) - if err := json.Unmarshal(b, jwkSet); err != nil { - return nil, errors.Errorf("error reading %s: unsupported format", ctx.filename) - } - - jwks := jwkSet.Key(ctx.kid) - switch len(jwks) { - case 0: - return nil, errors.Errorf("cannot find key with kid %s on %s", ctx.kid, ctx.filename) - case 1: - jwk := &jwks[0] - - // Set the algorithm if empty - guessJWKAlgorithm(ctx, jwk) - - // Validate alg: if the flag '--subtle' is passed we will allow the - // overwrite of the alg - if !ctx.subtle && ctx.alg != "" && jwk.Algorithm != "" && ctx.alg != jwk.Algorithm { - return nil, errors.Errorf("alg %s does not match the alg on %s", ctx.alg, ctx.filename) - } - if ctx.subtle && ctx.alg != "" { - jwk.Algorithm = ctx.alg - } - return jwk, nil - default: - return nil, errors.Errorf("multiple keys with kid %s have been found on %s", ctx.kid, ctx.filename) - } -} - -func decodeCerts(l []interface{}) ([]*x509.Certificate, error) { - certs := make([]*x509.Certificate, len(l)) - for i, j := range l { - certStr, ok := j.(string) - if !ok { - return nil, errors.Errorf("wrong type in x5c header list; expected string but %T", i) - } - certB, err := base64.StdEncoding.DecodeString(certStr) - if err != nil { - return nil, errors.Wrap(err, "error decoding base64 encoded x5c cert") - } - cert, err := x509.ParseCertificate(certB) - if err != nil { - return nil, errors.Wrap(err, "error parsing x5c cert") - } - certs[i] = cert - } - return certs, nil -} - -// X5cInsecureKey is the key used to store the x5cInsecure cert chain in the JWT header. -var X5cInsecureKey = "x5cInsecure" - -// GetX5cInsecureHeader extracts the x5cInsecure certificate chain from the token. -func GetX5cInsecureHeader(jwt *JSONWebToken) ([]*x509.Certificate, error) { - x5cVal, ok := jwt.Headers[0].ExtraHeaders[HeaderKey(X5cInsecureKey)] - if !ok { - return nil, errors.New("ssh check-host token missing x5cInsecure header") - } - interfaces, ok := x5cVal.([]interface{}) - if !ok { - return nil, errors.Errorf("ssh check-host token x5cInsecure header has wrong type; expected []string, but got %T", x5cVal) - } - chain, err := decodeCerts(interfaces) - if err != nil { - return nil, errors.Wrap(err, "error decoding x5cInsecure header certs") - } - return chain, nil -} - -// ParseX5cInsecure parses an x5cInsecure token, validates the certificate chain -// in the token, and returns the JWT struct along with all the verified chains. -func ParseX5cInsecure(tok string, roots []*x509.Certificate) (*JSONWebToken, [][]*x509.Certificate, error) { - jwt, err := ParseSigned(tok) - if err != nil { - return nil, nil, errors.Wrapf(err, "error parsing x5cInsecure token") - } - - chain, err := GetX5cInsecureHeader(jwt) - if err != nil { - return nil, nil, errors.Wrap(err, "error extracting x5cInsecure cert chain") - } - leaf := chain[0] - - interPool := x509.NewCertPool() - for _, crt := range chain[1:] { - interPool.AddCert(crt) - } - rootPool := x509.NewCertPool() - for _, crt := range roots { - rootPool.AddCert(crt) - } - // Correctly parse and validate the x5c certificate chain. - verifiedChains, err := leaf.Verify(x509.VerifyOptions{ - Roots: rootPool, - Intermediates: interPool, - // A hack so we skip validity period validation. - CurrentTime: leaf.NotAfter.Add(-1 * time.Minute), - KeyUsages: []x509.ExtKeyUsage{ - x509.ExtKeyUsageClientAuth, - }, - }) - if err != nil { - return nil, nil, errors.Wrap(err, "error verifying x5cInsecure certificate chain") - } - leaf = verifiedChains[0][0] - - if leaf.KeyUsage&x509.KeyUsageDigitalSignature == 0 { - return nil, nil, errors.New("certificate used to sign x5cInsecure token cannot be used for digital signature") - } - - return jwt, verifiedChains, nil -} - -// guessKeyType returns the key type of the given data. Key types are JWK, PEM -// or oct. -func guessKeyType(ctx *context, data []byte) keyType { - switch ctx.alg { - // jwk or file with oct data - case "HS256", "HS384", "HS512": - // Encrypted JWK ? - if _, err := ParseEncrypted(string(data)); err == nil { - return jwkKeyType - } - // JSON JWK ? - if err := json.Unmarshal(data, &JSONWebKey{}); err == nil { - return jwkKeyType - } - // Default to oct - return octKeyType - default: - // PEM or default to JWK - if bytes.HasPrefix(data, []byte("-----BEGIN ")) { - return pemKeyType - } - return jwkKeyType - } -} - -// guessJWKAlgorithm set the algorithm if it's not set and we can guess it -func guessJWKAlgorithm(ctx *context, jwk *JSONWebKey) { - if jwk.Algorithm == "" { - // Force default algorithm if passed. - if ctx.alg != "" { - jwk.Algorithm = ctx.alg - return - } - - // Guess only fixed algorithms if no defaults is enabled - if ctx.noDefaults { - guessKnownJWKAlgorithm(ctx, jwk) - return - } - - // Use defaults for each key type - switch k := jwk.Key.(type) { - case []byte: - if jwk.Use == "enc" { - jwk.Algorithm = string(DefaultOctKeyAlgorithm) - } else { - jwk.Algorithm = string(DefaultOctSigAlgorithm) - } - case *ecdsa.PrivateKey: - if jwk.Use == "enc" { - jwk.Algorithm = string(DefaultECKeyAlgorithm) - } else { - jwk.Algorithm = getECAlgorithm(k.Curve) - } - case *ecdsa.PublicKey: - if jwk.Use == "enc" { - jwk.Algorithm = string(DefaultECKeyAlgorithm) - } else { - jwk.Algorithm = getECAlgorithm(k.Curve) - } - case *rsa.PrivateKey, *rsa.PublicKey: - if jwk.Use == "enc" { - jwk.Algorithm = string(DefaultRSAKeyAlgorithm) - } else { - jwk.Algorithm = string(DefaultRSASigAlgorithm) - } - // Ed25519 can only be used for signing operations - case ed25519.PrivateKey, ed25519.PublicKey: - jwk.Algorithm = EdDSA - case x25519.PrivateKey, x25519.PublicKey: - jwk.Algorithm = XEdDSA - } - } -} - -// guessSignatureAlgorithm returns the signature algorithm for a given private key. -func guessSignatureAlgorithm(key crypto.PrivateKey) SignatureAlgorithm { - switch k := key.(type) { - case []byte: - return DefaultOctSigAlgorithm - case *ecdsa.PrivateKey: - return SignatureAlgorithm(getECAlgorithm(k.Curve)) - case *rsa.PrivateKey: - return DefaultRSASigAlgorithm - case ed25519.PrivateKey: - return EdDSA - case x25519.PrivateKey, X25519Signer: - return XEdDSA - default: - return "" - } -} - -// guessKnownJWKAlgorithm sets the algorithm for keys that only have one -// possible algorithm. -func guessKnownJWKAlgorithm(_ *context, jwk *JSONWebKey) { - if jwk.Algorithm == "" && jwk.Use != "enc" { - switch k := jwk.Key.(type) { - case *ecdsa.PrivateKey: - jwk.Algorithm = getECAlgorithm(k.Curve) - case *ecdsa.PublicKey: - jwk.Algorithm = getECAlgorithm(k.Curve) - case ed25519.PrivateKey, ed25519.PublicKey: - jwk.Algorithm = EdDSA - case x25519.PrivateKey, x25519.PublicKey: - jwk.Algorithm = XEdDSA - } - } -} - -// getECAlgorithm returns the JWA algorithm name for the given elliptic curve. -// If the curve is not supported it will return an empty string. -// -// Supported curves are P-256, P-384, and P-521. -func getECAlgorithm(crv elliptic.Curve) string { - switch crv.Params().Name { - case P256: - return ES256 - case P384: - return ES384 - case P521: - return ES512 - default: - return "" - } -} diff --git a/vendor/go.step.sm/crypto/jose/types.go b/vendor/go.step.sm/crypto/jose/types.go deleted file mode 100644 index f034763850..0000000000 --- a/vendor/go.step.sm/crypto/jose/types.go +++ /dev/null @@ -1,310 +0,0 @@ -// Package jose is a wrapper for github.com/go-jose/go-jose/v3 and implements -// utilities to parse and generate JWT, JWK and JWKSets. -package jose - -import ( - "crypto" - "errors" - "strings" - "time" - - jose "github.com/go-jose/go-jose/v3" - "github.com/go-jose/go-jose/v3/cryptosigner" - "github.com/go-jose/go-jose/v3/jwt" - "go.step.sm/crypto/x25519" -) - -// SupportsPBKDF2 constant to know if the underlaying library supports -// password based cryptography algorithms. -const SupportsPBKDF2 = true - -// PBKDF2SaltSize is the default size of the salt for PBKDF2, 128-bit salt. -const PBKDF2SaltSize = 16 - -// PBKDF2Iterations is the default number of iterations for PBKDF2. -// -// 600k is the current OWASP recommendation (Dec 2022) -// https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2 -// -// Nist recommends at least 10k (800-63B), 1Password increased in 2023 the -// number of iterations from 100k to 650k. -const PBKDF2Iterations = 600000 - -// JSONWebSignature represents a signed JWS object after parsing. -type JSONWebSignature = jose.JSONWebSignature - -// JSONWebToken represents a JSON Web Token (as specified in RFC7519). -type JSONWebToken = jwt.JSONWebToken - -// JSONWebKey represents a public or private key in JWK format. -type JSONWebKey = jose.JSONWebKey - -// JSONWebKeySet represents a JWK Set object. -type JSONWebKeySet = jose.JSONWebKeySet - -// JSONWebEncryption represents an encrypted JWE object after parsing. -type JSONWebEncryption = jose.JSONWebEncryption - -// Recipient represents an algorithm/key to encrypt messages to. -type Recipient = jose.Recipient - -// EncrypterOptions represents options that can be set on new encrypters. -type EncrypterOptions = jose.EncrypterOptions - -// Encrypter represents an encrypter which produces an encrypted JWE object. -type Encrypter = jose.Encrypter - -// ContentType represents type of the contained data. -type ContentType = jose.ContentType - -// KeyAlgorithm represents a key management algorithm. -type KeyAlgorithm = jose.KeyAlgorithm - -// ContentEncryption represents a content encryption algorithm. -type ContentEncryption = jose.ContentEncryption - -// SignatureAlgorithm represents a signature (or MAC) algorithm. -type SignatureAlgorithm = jose.SignatureAlgorithm - -// Signature represents a signature. -type Signature = jose.Signature - -// ErrCryptoFailure indicates an error in a cryptographic primitive. -var ErrCryptoFailure = jose.ErrCryptoFailure - -// Claims represents public claim values (as specified in RFC 7519). -type Claims = jwt.Claims - -// Builder is a utility for making JSON Web Tokens. Calls can be chained, and -// errors are accumulated until the final call to CompactSerialize/FullSerialize. -type Builder = jwt.Builder - -// NumericDate represents date and time as the number of seconds since the -// epoch, including leap seconds. Non-integer values can be represented -// in the serialized format, but we round to the nearest second. -type NumericDate = jwt.NumericDate - -// Audience represents the recipients that the token is intended for. -type Audience = jwt.Audience - -// Expected defines values used for protected claims validation. -// If field has zero value then validation is skipped. -type Expected = jwt.Expected - -// Signer represents a signer which takes a payload and produces a signed JWS object. -type Signer = jose.Signer - -// OpaqueSigner represents a jose.Signer that wraps a crypto.Signer -type OpaqueSigner = jose.OpaqueSigner - -// SigningKey represents an algorithm/key used to sign a message. -type SigningKey = jose.SigningKey - -// SignerOptions represents options that can be set when creating signers. -type SignerOptions = jose.SignerOptions - -// Header represents the read-only JOSE header for JWE/JWS objects. -type Header = jose.Header - -// HeaderKey represents the type used as a key in the protected header of a JWS -// object. -type HeaderKey = jose.HeaderKey - -// ErrInvalidIssuer indicates invalid iss claim. -var ErrInvalidIssuer = jwt.ErrInvalidIssuer - -// ErrInvalidAudience indicated invalid aud claim. -var ErrInvalidAudience = jwt.ErrInvalidAudience - -// ErrNotValidYet indicates that token is used before time indicated in nbf claim. -var ErrNotValidYet = jwt.ErrNotValidYet - -// ErrExpired indicates that token is used after expiry time indicated in exp claim. -var ErrExpired = jwt.ErrExpired - -// ErrInvalidSubject indicates invalid sub claim. -var ErrInvalidSubject = jwt.ErrInvalidSubject - -// ErrInvalidID indicates invalid jti claim. -var ErrInvalidID = jwt.ErrInvalidID - -// ErrIssuedInTheFuture indicates that the iat field is in the future. -var ErrIssuedInTheFuture = jwt.ErrIssuedInTheFuture - -// Key management algorithms -// -//nolint:stylecheck,revive // use standard names in upper-case -const ( - RSA1_5 = KeyAlgorithm("RSA1_5") // RSA-PKCS1v1.5 - RSA_OAEP = KeyAlgorithm("RSA-OAEP") // RSA-OAEP-SHA1 - RSA_OAEP_256 = KeyAlgorithm("RSA-OAEP-256") // RSA-OAEP-SHA256 - A128KW = KeyAlgorithm("A128KW") // AES key wrap (128) - A192KW = KeyAlgorithm("A192KW") // AES key wrap (192) - A256KW = KeyAlgorithm("A256KW") // AES key wrap (256) - DIRECT = KeyAlgorithm("dir") // Direct encryption - ECDH_ES = KeyAlgorithm("ECDH-ES") // ECDH-ES - ECDH_ES_A128KW = KeyAlgorithm("ECDH-ES+A128KW") // ECDH-ES + AES key wrap (128) - ECDH_ES_A192KW = KeyAlgorithm("ECDH-ES+A192KW") // ECDH-ES + AES key wrap (192) - ECDH_ES_A256KW = KeyAlgorithm("ECDH-ES+A256KW") // ECDH-ES + AES key wrap (256) - A128GCMKW = KeyAlgorithm("A128GCMKW") // AES-GCM key wrap (128) - A192GCMKW = KeyAlgorithm("A192GCMKW") // AES-GCM key wrap (192) - A256GCMKW = KeyAlgorithm("A256GCMKW") // AES-GCM key wrap (256) - PBES2_HS256_A128KW = KeyAlgorithm("PBES2-HS256+A128KW") // PBES2 + HMAC-SHA256 + AES key wrap (128) - PBES2_HS384_A192KW = KeyAlgorithm("PBES2-HS384+A192KW") // PBES2 + HMAC-SHA384 + AES key wrap (192) - PBES2_HS512_A256KW = KeyAlgorithm("PBES2-HS512+A256KW") // PBES2 + HMAC-SHA512 + AES key wrap (256) -) - -// Signature algorithms -const ( - HS256 = "HS256" // HMAC using SHA-256 - HS384 = "HS384" // HMAC using SHA-384 - HS512 = "HS512" // HMAC using SHA-512 - RS256 = "RS256" // RSASSA-PKCS-v1.5 using SHA-256 - RS384 = "RS384" // RSASSA-PKCS-v1.5 using SHA-384 - RS512 = "RS512" // RSASSA-PKCS-v1.5 using SHA-512 - ES256 = "ES256" // ECDSA using P-256 and SHA-256 - ES384 = "ES384" // ECDSA using P-384 and SHA-384 - ES512 = "ES512" // ECDSA using P-521 and SHA-512 - PS256 = "PS256" // RSASSA-PSS using SHA256 and MGF1-SHA256 - PS384 = "PS384" // RSASSA-PSS using SHA384 and MGF1-SHA384 - PS512 = "PS512" // RSASSA-PSS using SHA512 and MGF1-SHA512 - EdDSA = "EdDSA" // Ed25519 with EdDSA signature schema - XEdDSA = "XEdDSA" // X25519 with XEdDSA signature schema -) - -// Content encryption algorithms -// -//nolint:revive,stylecheck // use standard names in upper-case -const ( - A128CBC_HS256 = ContentEncryption("A128CBC-HS256") // AES-CBC + HMAC-SHA256 (128) - A192CBC_HS384 = ContentEncryption("A192CBC-HS384") // AES-CBC + HMAC-SHA384 (192) - A256CBC_HS512 = ContentEncryption("A256CBC-HS512") // AES-CBC + HMAC-SHA512 (256) - A128GCM = ContentEncryption("A128GCM") // AES-GCM (128) - A192GCM = ContentEncryption("A192GCM") // AES-GCM (192) - A256GCM = ContentEncryption("A256GCM") // AES-GCM (256) -) - -// Elliptic curves -const ( - P256 = "P-256" // P-256 curve (FIPS 186-3) - P384 = "P-384" // P-384 curve (FIPS 186-3) - P521 = "P-521" // P-521 curve (FIPS 186-3) -) - -// Key types -const ( - EC = "EC" // Elliptic curves - RSA = "RSA" // RSA - OKP = "OKP" // Ed25519 - OCT = "oct" // Octet sequence -) - -// Ed25519 is the EdDSA signature scheme using SHA-512/256 and Curve25519 -const Ed25519 = "Ed25519" - -// Default key management, signature, and content encryption algorithms to use if none is specified. -const ( - // Key management algorithms - DefaultECKeyAlgorithm = ECDH_ES - DefaultRSAKeyAlgorithm = RSA_OAEP_256 - DefaultOctKeyAlgorithm = A256GCMKW - // Signature algorithms - DefaultRSASigAlgorithm = RS256 - DefaultOctSigAlgorithm = HS256 - // Content encryption algorithm - DefaultEncAlgorithm = A256GCM -) - -// Default sizes -const ( - DefaultRSASize = 2048 - DefaultOctSize = 32 -) - -// ParseEncrypted parses an encrypted message in compact or full serialization format. -func ParseEncrypted(input string) (*JSONWebEncryption, error) { - return jose.ParseEncrypted(input) -} - -// NewEncrypter creates an appropriate encrypter based on the key type. -func NewEncrypter(enc ContentEncryption, rcpt Recipient, opts *EncrypterOptions) (Encrypter, error) { - return jose.NewEncrypter(enc, rcpt, opts) -} - -// NewNumericDate constructs NumericDate from time.Time value. -func NewNumericDate(t time.Time) *NumericDate { - return jwt.NewNumericDate(t) -} - -// UnixNumericDate returns a NumericDate from the given seconds since the UNIX -// Epoch time. For backward compatibility is s is 0, a nil value will be returned. -func UnixNumericDate(s int64) *NumericDate { - if s == 0 { - return nil - } - out := NumericDate(s) - return &out -} - -// NewSigner creates an appropriate signer based on the key type -func NewSigner(sig SigningKey, opts *SignerOptions) (Signer, error) { - if k, ok := sig.Key.(x25519.PrivateKey); ok { - sig.Key = X25519Signer(k) - } - if sig.Algorithm == "" { - sig.Algorithm = guessSignatureAlgorithm(sig.Key) - } - return jose.NewSigner(sig, opts) -} - -// NewOpaqueSigner creates a new OpaqueSigner for JWT signing from a crypto.Signer -func NewOpaqueSigner(signer crypto.Signer) OpaqueSigner { - return cryptosigner.Opaque(signer) -} - -// Verify validates the token payload with the given public key and deserializes -// the token into the destination. -func Verify(token *JSONWebToken, publicKey interface{}, dest ...interface{}) error { - if k, ok := publicKey.(x25519.PublicKey); ok { - publicKey = X25519Verifier(k) - } - return token.Claims(publicKey, dest...) -} - -// ParseSigned parses token from JWS form. -func ParseSigned(s string) (*JSONWebToken, error) { - return jwt.ParseSigned(s) -} - -// Signed creates builder for signed tokens. -func Signed(sig Signer) Builder { - return jwt.Signed(sig) -} - -// ParseJWS parses a signed message in compact or full serialization format. -func ParseJWS(s string) (*JSONWebSignature, error) { - return jose.ParseSigned(s) -} - -// Determine whether a JSONWebKey is symmetric -func IsSymmetric(k *JSONWebKey) bool { - switch k.Key.(type) { - case []byte: - return true - default: - return false - } -} - -// Determine whether a JSONWebKey is asymmetric -func IsAsymmetric(k *JSONWebKey) bool { - return !IsSymmetric(k) -} - -// TrimPrefix removes the string "go-jose/go-jose" from all errors. -func TrimPrefix(err error) error { - if err == nil { - return nil - } - return errors.New(strings.TrimPrefix(err.Error(), "go-jose/go-jose: ")) -} diff --git a/vendor/go.step.sm/crypto/jose/validate.go b/vendor/go.step.sm/crypto/jose/validate.go deleted file mode 100644 index 6a904167e7..0000000000 --- a/vendor/go.step.sm/crypto/jose/validate.go +++ /dev/null @@ -1,221 +0,0 @@ -package jose - -import ( - "crypto" - "crypto/ecdsa" - "crypto/ed25519" - "crypto/rsa" - "crypto/sha1" //nolint:gosec // RFC 7515 - X.509 Certificate SHA-1 Thumbprint - "crypto/x509" - "encoding/base64" - "fmt" - "os" - - "github.com/pkg/errors" - "go.step.sm/crypto/keyutil" - "golang.org/x/crypto/ssh" -) - -// ValidateSSHPOP validates the given SSH certificate and key for use in an -// sshpop header. -func ValidateSSHPOP(certFile string, key interface{}) (string, error) { - if certFile == "" { - return "", errors.New("ssh certfile cannot be empty") - } - certBytes, err := os.ReadFile(certFile) - if err != nil { - return "", errors.Wrapf(err, "error reading ssh certificate from %s", certFile) - } - sshpub, _, _, _, err := ssh.ParseAuthorizedKey(certBytes) - if err != nil { - return "", errors.Wrapf(err, "error parsing ssh public key from %s", certFile) - } - cert, ok := sshpub.(*ssh.Certificate) - if !ok { - return "", errors.New("error casting ssh public key to ssh certificate") - } - pubkey, err := keyutil.ExtractKey(cert) - if err != nil { - return "", errors.Wrap(err, "error extracting public key from ssh public key interface") - } - if err = validateKeyPair(pubkey, key); err != nil { - return "", errors.Wrap(err, "error verifying ssh key pair") - } - - return base64.StdEncoding.EncodeToString(cert.Marshal()), nil -} - -func validateKeyPair(pub crypto.PublicKey, priv crypto.PrivateKey) error { - switch key := priv.(type) { - case *JSONWebKey: - return keyutil.VerifyPair(pub, key.Key) - case OpaqueSigner: - if !keyutil.Equal(pub, key.Public().Key) { - return errors.New("private key does not match public key") - } - return nil - default: - return keyutil.VerifyPair(pub, priv) - } -} - -func validateX5(certs []*x509.Certificate, key interface{}) error { - if len(certs) == 0 { - return errors.New("certs cannot be empty") - } - - if err := validateKeyPair(certs[0].PublicKey, key); err != nil { - return errors.Wrap(err, "error verifying certificate and key") - } - - if certs[0].KeyUsage&x509.KeyUsageDigitalSignature == 0 { - return errors.New("certificate/private-key pair used to sign " + - "token is not approved for digital signature") - } - return nil -} - -// ValidateX5C validates the given certificate chain and key for use as a token -// signer and x5t header. -func ValidateX5C(certs []*x509.Certificate, key interface{}) ([]string, error) { - if err := validateX5(certs, key); err != nil { - return nil, errors.Wrap(err, "ValidateX5C") - } - strs := make([]string, len(certs)) - for i, cert := range certs { - strs[i] = base64.StdEncoding.EncodeToString(cert.Raw) - } - return strs, nil -} - -// ValidateX5T validates the given certificate and key for use as a token signer -// and x5t header. -func ValidateX5T(certs []*x509.Certificate, key interface{}) (string, error) { - if err := validateX5(certs, key); err != nil { - return "", errors.Wrap(err, "ValidateX5T") - } - // x5t is the base64 URL encoded SHA1 thumbprint - // (see https://tools.ietf.org/html/rfc7515#section-4.1.7) - //nolint:gosec // RFC 7515 - X.509 Certificate SHA-1 Thumbprint - fingerprint := sha1.Sum(certs[0].Raw) - return base64.URLEncoding.EncodeToString(fingerprint[:]), nil -} - -// ValidateJWK validates the given JWK. -func ValidateJWK(jwk *JSONWebKey) error { - switch jwk.Use { - case "sig": - return validateSigJWK(jwk) - case "enc": - return validateEncJWK(jwk) - default: - return validateGeneric(jwk) - } -} - -// validateSigJWK validates the given JWK for signature operations. -func validateSigJWK(jwk *JSONWebKey) error { - if jwk.Algorithm == "" { - return errors.New("flag '--alg' is required with the given key") - } - errctx := "the given key" - - switch k := jwk.Key.(type) { - case []byte: - switch jwk.Algorithm { - case HS256, HS384, HS512: - return nil - } - errctx = "kty 'oct'" - case *rsa.PrivateKey, *rsa.PublicKey: - switch jwk.Algorithm { - case RS256, RS384, RS512: - return nil - case PS256, PS384, PS512: - return nil - } - errctx = "kty 'RSA'" - case *ecdsa.PrivateKey: - curve := k.Params().Name - switch { - case jwk.Algorithm == ES256 && curve == P256: - return nil - case jwk.Algorithm == ES384 && curve == P384: - return nil - case jwk.Algorithm == ES512 && curve == P521: - return nil - } - errctx = fmt.Sprintf("kty 'EC' and crv '%s'", curve) - case *ecdsa.PublicKey: - curve := k.Params().Name - switch { - case jwk.Algorithm == ES256 && curve == P256: - return nil - case jwk.Algorithm == ES384 && curve == P384: - return nil - case jwk.Algorithm == ES512 && curve == P521: - return nil - } - errctx = fmt.Sprintf("kty 'EC' and crv '%s'", curve) - case ed25519.PrivateKey, ed25519.PublicKey: - if jwk.Algorithm == EdDSA { - return nil - } - errctx = "kty 'OKP' and crv 'Ed25519'" - case OpaqueSigner: - for _, alg := range k.Algs() { - if jwk.Algorithm == string(alg) { - return nil - } - } - } - - return errors.Errorf("alg '%s' is not compatible with %s", jwk.Algorithm, errctx) -} - -// validatesEncJWK validates the given JWK for encryption operations. -func validateEncJWK(jwk *JSONWebKey) error { - alg := KeyAlgorithm(jwk.Algorithm) - var kty string - - switch jwk.Key.(type) { - case []byte: - switch alg { - case DIRECT, A128GCMKW, A192GCMKW, A256GCMKW, A128KW, A192KW, A256KW: - return nil - } - kty = "oct" - case *rsa.PrivateKey, *rsa.PublicKey: - switch alg { - case RSA1_5, RSA_OAEP, RSA_OAEP_256: - return nil - } - kty = "RSA" - case *ecdsa.PrivateKey, *ecdsa.PublicKey: - switch alg { - case ECDH_ES, ECDH_ES_A128KW, ECDH_ES_A192KW, ECDH_ES_A256KW: - return nil - } - kty = "EC" - case ed25519.PrivateKey, ed25519.PublicKey: - return errors.New("key Ed25519 cannot be used for encryption") - } - - return errors.Errorf("alg '%s' is not compatible with kty '%s'", jwk.Algorithm, kty) -} - -// validateGeneric validates just the supported key types. -func validateGeneric(jwk *JSONWebKey) error { - switch jwk.Key.(type) { - case []byte: - return nil - case *rsa.PrivateKey, *rsa.PublicKey: - return nil - case *ecdsa.PrivateKey, *ecdsa.PublicKey: - return nil - case ed25519.PrivateKey, ed25519.PublicKey: - return nil - } - - return errors.Errorf("unsupported key type '%T'", jwk.Key) -} diff --git a/vendor/go.step.sm/crypto/jose/x25519.go b/vendor/go.step.sm/crypto/jose/x25519.go deleted file mode 100644 index 25e90e8ad7..0000000000 --- a/vendor/go.step.sm/crypto/jose/x25519.go +++ /dev/null @@ -1,66 +0,0 @@ -package jose - -import ( - "crypto" - "crypto/rand" - "encoding/base64" - "fmt" - - "github.com/pkg/errors" - "go.step.sm/crypto/x25519" -) - -const x25519ThumbprintTemplate = `{"crv":"X25519","kty":"OKP","x":%q}` - -func x25519Thumbprint(key x25519.PublicKey, hash crypto.Hash) ([]byte, error) { - if len(key) != 32 { - return nil, errors.New("invalid elliptic key") - } - h := hash.New() - fmt.Fprintf(h, x25519ThumbprintTemplate, base64.RawURLEncoding.EncodeToString(key)) - return h.Sum(nil), nil -} - -// X25519Signer implements the jose.OpaqueSigner using an X25519 key and XEdDSA -// as the signing algorithm. -type X25519Signer x25519.PrivateKey - -// Public returns the public key of the current signing key. -func (s X25519Signer) Public() *JSONWebKey { - return &JSONWebKey{ - Key: x25519.PrivateKey(s).Public(), - } -} - -// Algs returns a list of supported signing algorithms, in this case only -// XEdDSA. -func (s X25519Signer) Algs() []SignatureAlgorithm { - return []SignatureAlgorithm{ - XEdDSA, - } -} - -// SignPayload signs a payload with the current signing key using the given -// algorithm, it will fail if it's not XEdDSA. -func (s X25519Signer) SignPayload(payload []byte, alg SignatureAlgorithm) ([]byte, error) { - if alg != XEdDSA { - return nil, errors.Errorf("x25519 key does not support the signature algorithm %s", alg) - } - return x25519.PrivateKey(s).Sign(rand.Reader, payload, crypto.Hash(0)) -} - -// X25519Verifier implements the jose.OpaqueVerifier interface using an X25519 -// key and XEdDSA as a signing algorithm. -type X25519Verifier x25519.PublicKey - -// VerifyPayload verifies the given signature using the X25519 public key, it -// will fail if the signature algorithm is not XEdDSA. -func (v X25519Verifier) VerifyPayload(payload, signature []byte, alg SignatureAlgorithm) error { - if alg != XEdDSA { - return errors.Errorf("x25519 key does not support the signature algorithm %s", alg) - } - if !x25519.Verify(x25519.PublicKey(v), payload, signature) { - return errors.New("failed to verify XEdDSA signature") - } - return nil -} diff --git a/vendor/go.step.sm/crypto/keyutil/fingerprint.go b/vendor/go.step.sm/crypto/keyutil/fingerprint.go deleted file mode 100644 index 4447ff31e7..0000000000 --- a/vendor/go.step.sm/crypto/keyutil/fingerprint.go +++ /dev/null @@ -1,74 +0,0 @@ -package keyutil - -import ( - "crypto" - "crypto/sha256" - "crypto/x509" - "crypto/x509/pkix" - "encoding/asn1" - "fmt" - - "go.step.sm/crypto/fingerprint" -) - -// FingerprintEncoding defines the supported encodings in certificate -// fingerprints. -type FingerprintEncoding = fingerprint.Encoding - -// Supported fingerprint encodings. -const ( - // DefaultFingerprint represents the base64 encoding of the fingerprint. - DefaultFingerprint = FingerprintEncoding(0) - // HexFingerprint represents the hex encoding of the fingerprint. - HexFingerprint = fingerprint.HexFingerprint - // Base64Fingerprint represents the base64 encoding of the fingerprint. - Base64Fingerprint = fingerprint.Base64Fingerprint - // Base64URLFingerprint represents the base64URL encoding of the fingerprint. - Base64URLFingerprint = fingerprint.Base64URLFingerprint - // Base64RawFingerprint represents the base64RawStd encoding of the fingerprint. - Base64RawFingerprint = fingerprint.Base64RawFingerprint - // Base64RawURLFingerprint represents the base64RawURL encoding of the fingerprint. - Base64RawURLFingerprint = fingerprint.Base64RawURLFingerprint - // EmojiFingerprint represents the emoji encoding of the fingerprint. - EmojiFingerprint = fingerprint.EmojiFingerprint -) - -// subjectPublicKeyInfo is a PKIX public key structure defined in RFC 5280. -type subjectPublicKeyInfo struct { - Algorithm pkix.AlgorithmIdentifier - SubjectPublicKey asn1.BitString -} - -// Fingerprint returns the SHA-256 fingerprint of an public key. -// -// The fingerprint is calculated from the encoding of the key according to RFC -// 5280 section 4.2.1.2, but using SHA-256 instead of SHA-1. -func Fingerprint(pub crypto.PublicKey) (string, error) { - return EncodedFingerprint(pub, DefaultFingerprint) -} - -// EncodedFingerprint returns the SHA-256 hash of the certificate using the -// specified encoding. -// -// The fingerprint is calculated from the encoding of the key according to RFC -// 5280 section 4.2.1.2, but using SHA-256 instead of SHA-1. -func EncodedFingerprint(pub crypto.PublicKey, encoding FingerprintEncoding) (string, error) { - b, err := x509.MarshalPKIXPublicKey(pub) - if err != nil { - return "", fmt.Errorf("error marshaling public key: %w", err) - } - var info subjectPublicKeyInfo - if _, err = asn1.Unmarshal(b, &info); err != nil { - return "", fmt.Errorf("error unmarshaling public key: %w", err) - } - if encoding == DefaultFingerprint { - encoding = Base64Fingerprint - } - - sum := sha256.Sum256(info.SubjectPublicKey.Bytes) - fp := fingerprint.Fingerprint(sum[:], encoding) - if fp == "" { - return "", fmt.Errorf("error formatting fingerprint: unsupported encoding") - } - return "SHA256:" + fp, nil -} diff --git a/vendor/go.step.sm/crypto/keyutil/key.go b/vendor/go.step.sm/crypto/keyutil/key.go deleted file mode 100644 index 171cdf3f6e..0000000000 --- a/vendor/go.step.sm/crypto/keyutil/key.go +++ /dev/null @@ -1,265 +0,0 @@ -// Package keyutil implements utilities to generate cryptographic keys. -package keyutil - -import ( - "bytes" - "crypto" - "crypto/ecdsa" - "crypto/ed25519" - "crypto/elliptic" - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "math/big" - "sync/atomic" - - "github.com/pkg/errors" - "go.step.sm/crypto/x25519" - "golang.org/x/crypto/ssh" -) - -var ( - // DefaultKeyType is the default type of a private key. - DefaultKeyType = "EC" - // DefaultKeySize is the default size (in # of bits) of a private key. - DefaultKeySize = 2048 - // DefaultKeyCurve is the default curve of a private key. - DefaultKeyCurve = "P-256" - // DefaultSignatureAlgorithm is the default signature algorithm used on a - // certificate with the default key type. - DefaultSignatureAlgorithm = x509.ECDSAWithSHA256 - // MinRSAKeyBytes is the minimum acceptable size (in bytes) for RSA keys - // signed by the authority. - MinRSAKeyBytes = 256 -) - -type atomicBool int32 - -func (b *atomicBool) isSet() bool { return atomic.LoadInt32((*int32)(b)) != 0 } -func (b *atomicBool) setTrue() { atomic.StoreInt32((*int32)(b), 1) } -func (b *atomicBool) setFalse() { atomic.StoreInt32((*int32)(b), 0) } - -var insecureMode atomicBool - -// Insecure enables the insecure mode in this package and returns a function to -// revert the configuration. The insecure mode removes the minimum limits when -// generating RSA keys. -func Insecure() (revert func()) { - insecureMode.setTrue() - return func() { - insecureMode.setFalse() - } -} - -// PublicKey extracts a public key from a private key. -func PublicKey(priv interface{}) (crypto.PublicKey, error) { - switch k := priv.(type) { - case *rsa.PrivateKey: - return &k.PublicKey, nil - case *ecdsa.PrivateKey: - return &k.PublicKey, nil - case ed25519.PrivateKey: - return k.Public(), nil - case x25519.PrivateKey: - return k.Public(), nil - case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey, x25519.PublicKey: - return k, nil - case crypto.Signer: - return k.Public(), nil - default: - return nil, errors.Errorf("unrecognized key type: %T", priv) - } -} - -// GenerateDefaultKey generates a public/private key pair using sane defaults -// for key type, curve, and size. -func GenerateDefaultKey() (crypto.PrivateKey, error) { - return GenerateKey(DefaultKeyType, DefaultKeyCurve, DefaultKeySize) -} - -// GenerateDefaultKeyPair generates a public/private key pair using configured -// default values for key type, curve, and size. -func GenerateDefaultKeyPair() (crypto.PublicKey, crypto.PrivateKey, error) { - return GenerateKeyPair(DefaultKeyType, DefaultKeyCurve, DefaultKeySize) -} - -// GenerateKey generates a key of the given type (kty). -func GenerateKey(kty, crv string, size int) (crypto.PrivateKey, error) { - switch kty { - case "EC", "RSA", "OKP": - return GenerateSigner(kty, crv, size) - case "oct": - return generateOctKey(size) - default: - return nil, errors.Errorf("unrecognized key type: %s", kty) - } -} - -// GenerateKeyPair creates an asymmetric crypto keypair using input -// configuration. -func GenerateKeyPair(kty, crv string, size int) (crypto.PublicKey, crypto.PrivateKey, error) { - signer, err := GenerateSigner(kty, crv, size) - if err != nil { - return nil, nil, err - } - return signer.Public(), signer, nil -} - -// GenerateDefaultSigner returns an asymmetric crypto key that implements -// crypto.Signer using sane defaults. -func GenerateDefaultSigner() (crypto.Signer, error) { - return GenerateSigner(DefaultKeyType, DefaultKeyCurve, DefaultKeySize) -} - -// GenerateSigner creates an asymmetric crypto key that implements -// crypto.Signer. -func GenerateSigner(kty, crv string, size int) (crypto.Signer, error) { - switch kty { - case "EC": - return generateECKey(crv) - case "RSA": - return generateRSAKey(size) - case "OKP": - return generateOKPKey(crv) - default: - return nil, errors.Errorf("unrecognized key type: %s", kty) - } -} - -// ExtractKey returns the given public or private key or extracts the public key -// if a x509.Certificate or x509.CertificateRequest is given. -func ExtractKey(in interface{}) (interface{}, error) { - switch k := in.(type) { - case *rsa.PublicKey, *rsa.PrivateKey, - *ecdsa.PublicKey, *ecdsa.PrivateKey, - ed25519.PublicKey, ed25519.PrivateKey, - x25519.PublicKey, x25519.PrivateKey: - return in, nil - case []byte: - return in, nil - case *x509.Certificate: - return k.PublicKey, nil - case *x509.CertificateRequest: - return k.PublicKey, nil - case ssh.CryptoPublicKey: - return k.CryptoPublicKey(), nil - case *ssh.Certificate: - return ExtractKey(k.Key) - default: - return nil, errors.Errorf("cannot extract the key from type '%T'", k) - } -} - -// VerifyPair that the public key matches the given private key. -func VerifyPair(pub crypto.PublicKey, priv crypto.PrivateKey) error { - signer, ok := priv.(crypto.Signer) - if !ok { - return errors.New("private key type does implement crypto.Signer") - } - if !Equal(pub, signer.Public()) { - return errors.New("private key does not match public key") - } - return nil -} - -// Equal reports if x and y are the same key. -func Equal(x, y any) bool { - switch xx := x.(type) { - case *ecdsa.PublicKey: - yy, ok := y.(*ecdsa.PublicKey) - return ok && xx.Equal(yy) - case *ecdsa.PrivateKey: - yy, ok := y.(*ecdsa.PrivateKey) - return ok && xx.Equal(yy) - case *rsa.PublicKey: - yy, ok := y.(*rsa.PublicKey) - return ok && xx.Equal(yy) - case *rsa.PrivateKey: - yy, ok := y.(*rsa.PrivateKey) - return ok && xx.Equal(yy) - case ed25519.PublicKey: - yy, ok := y.(ed25519.PublicKey) - return ok && xx.Equal(yy) - case ed25519.PrivateKey: - yy, ok := y.(ed25519.PrivateKey) - return ok && xx.Equal(yy) - case x25519.PublicKey: - yy, ok := y.(x25519.PublicKey) - return ok && xx.Equal(yy) - case x25519.PrivateKey: - yy, ok := y.(x25519.PrivateKey) - return ok && xx.Equal(yy) - case []byte: // special case for symmetric keys - yy, ok := y.([]byte) - return ok && bytes.Equal(xx, yy) - default: - return false - } -} - -func generateECKey(crv string) (crypto.Signer, error) { - var c elliptic.Curve - switch crv { - case "P-256": - c = elliptic.P256() - case "P-384": - c = elliptic.P384() - case "P-521": - c = elliptic.P521() - default: - return nil, errors.Errorf("invalid value for argument crv (crv: '%s')", crv) - } - - key, err := ecdsa.GenerateKey(c, rand.Reader) - if err != nil { - return nil, errors.Wrap(err, "error generating EC key") - } - - return key, nil -} - -func generateRSAKey(bits int) (crypto.Signer, error) { - if minBits := MinRSAKeyBytes * 8; !insecureMode.isSet() && bits < minBits { - return nil, errors.Errorf("the size of the RSA key should be at least %d bits", minBits) - } - - key, err := rsa.GenerateKey(rand.Reader, bits) - if err != nil { - return nil, errors.Wrap(err, "error generating RSA key") - } - - return key, nil -} - -func generateOKPKey(crv string) (crypto.Signer, error) { - switch crv { - case "Ed25519": - _, key, err := ed25519.GenerateKey(rand.Reader) - if err != nil { - return nil, errors.Wrap(err, "error generating Ed25519 key") - } - return key, nil - case "X25519": - _, key, err := x25519.GenerateKey(rand.Reader) - if err != nil { - return nil, errors.Wrap(err, "error generating X25519 key") - } - return key, nil - default: - return nil, errors.Errorf("missing or invalid value for argument 'crv'. "+ - "expected 'Ed25519' or 'X25519', but got '%s'", crv) - } -} - -func generateOctKey(size int) (interface{}, error) { - const chars = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" - result := make([]byte, size) - for i := range result { - num, err := rand.Int(rand.Reader, big.NewInt(int64(len(chars)))) - if err != nil { - return nil, err - } - result[i] = chars[num.Int64()] - } - return result, nil -} diff --git a/vendor/go.step.sm/crypto/pemutil/cosign.go b/vendor/go.step.sm/crypto/pemutil/cosign.go deleted file mode 100644 index d28c9f7d70..0000000000 --- a/vendor/go.step.sm/crypto/pemutil/cosign.go +++ /dev/null @@ -1,79 +0,0 @@ -package pemutil - -import ( - "crypto" - "crypto/x509" - "encoding/json" - - "github.com/pkg/errors" - "golang.org/x/crypto/nacl/secretbox" - "golang.org/x/crypto/scrypt" -) - -type cosignEnvelope struct { - KDF cosignKDF `json:"kdf"` - Cipher cosignCipher `json:"cipher"` - Ciphertext []byte `json:"ciphertext"` -} - -type cosignKDF struct { - Name string `json:"name"` - Params cosignScryptParams `json:"params"` - Salt []byte `json:"salt"` -} - -type cosignScryptParams struct { - N int `json:"N"` - R int `json:"r"` - P int `json:"p"` -} - -type cosignCipher struct { - Name string `json:"name"` - Nonce []byte `json:"nonce"` -} - -// ParseCosignPrivateKey returns the private key encoded using cosign envelope. -// If an incorrect password is detected an x509.IncorrectPasswordError is -// returned. -// -// Cosign keys are encrypted under a password using scrypt as a KDF and -// nacl/secretbox for encryption. -func ParseCosignPrivateKey(data, password []byte) (crypto.PrivateKey, error) { - var env cosignEnvelope - if err := json.Unmarshal(data, &env); err != nil { - return nil, errors.Wrap(err, "error unmarshaling key") - } - if env.KDF.Name != "scrypt" { - return nil, errors.Errorf("error parsing key: unsupported kdf %s", env.KDF.Name) - } - if env.Cipher.Name != "nacl/secretbox" { - return nil, errors.Errorf("error parsing key: unsupported cipher %s", env.Cipher.Name) - } - if len(env.Cipher.Nonce) != 24 { - return nil, errors.New("error parsing key: nonce must be 24 bytes long") - } - - params := env.KDF.Params - k, err := scrypt.Key(password, env.KDF.Salt, params.N, params.R, params.P, 32) - if err != nil { - return nil, errors.Wrap(err, "error generating key") - } - - var nonce [24]byte - var key [32]byte - copy(nonce[:], env.Cipher.Nonce) - copy(key[:], k) - - out, ok := secretbox.Open(nil, env.Ciphertext, &nonce, &key) - if !ok { - return nil, x509.IncorrectPasswordError - } - - priv, err := x509.ParsePKCS8PrivateKey(out) - if err != nil { - return nil, errors.Wrap(err, "error parsing pkcs8 key") - } - - return priv, nil -} diff --git a/vendor/go.step.sm/crypto/pemutil/pem.go b/vendor/go.step.sm/crypto/pemutil/pem.go deleted file mode 100644 index 9202510d2d..0000000000 --- a/vendor/go.step.sm/crypto/pemutil/pem.go +++ /dev/null @@ -1,856 +0,0 @@ -// Package pemutil implements utilities to parse keys and certificates. It also -// includes a method to serialize keys, X.509 certificates and certificate -// requests to PEM. -package pemutil - -import ( - "bytes" - "crypto/ecdh" - "crypto/ecdsa" - "crypto/ed25519" - "crypto/elliptic" - "crypto/rand" - "crypto/rsa" - "crypto/sha256" - "crypto/x509" - "encoding/pem" - "fmt" - "math/big" - "os" - "strings" - - "github.com/pkg/errors" - "go.step.sm/crypto/internal/utils" - "go.step.sm/crypto/keyutil" - "go.step.sm/crypto/x25519" - "golang.org/x/crypto/ssh" -) - -// DefaultEncCipher is the default algorithm used when encrypting sensitive -// data in the PEM format. -var DefaultEncCipher = x509.PEMCipherAES256 - -// PasswordPrompter defines the function signature for the PromptPassword -// callback. -type PasswordPrompter func(s string) ([]byte, error) - -// FileWriter defines the function signature for the WriteFile callback. -type FileWriter func(filename string, data []byte, perm os.FileMode) error - -// PromptPassword is a method used to prompt for a password to decode encrypted -// keys. If this method is not defined and the key or password are not passed, -// the parse of the key will fail. -var PromptPassword PasswordPrompter - -// WriteFile is a method used to write a file, by default it uses a wrapper over -// ioutil.WriteFile, but it can be set to a custom method, that for example can -// check if a file exists and prompts the user if it should be overwritten. -var WriteFile FileWriter = utils.WriteFile - -// PEMBlockHeader is the expected header for any PEM formatted block. -var PEMBlockHeader = []byte("-----BEGIN ") - -// context add options to the pem methods. -type context struct { - filename string - perm os.FileMode - password []byte - pkcs8 bool - openSSH bool - comment string - firstBlock bool - passwordPrompt string - passwordPrompter PasswordPrompter -} - -// newContext initializes the context with a filename. -func newContext(name string) *context { - return &context{ - filename: name, - perm: 0600, - } -} - -// apply the context options and return the first error if exists. -func (c *context) apply(opts []Options) error { - for _, fn := range opts { - if err := fn(c); err != nil { - return err - } - } - return nil -} - -// promptPassword returns the password or prompts for one. -func (c *context) promptPassword() ([]byte, error) { - switch { - case len(c.password) > 0: - return c.password, nil - case c.passwordPrompter != nil: - return c.passwordPrompter(c.passwordPrompt) - case PromptPassword != nil: - return PromptPassword(fmt.Sprintf("Please enter the password to decrypt %s", c.filename)) - default: - return nil, errors.Errorf("error decoding %s: key is password protected", c.filename) - } -} - -// promptEncryptPassword returns the password or prompts for one if -// WithPassword, WithPasswordFile or WithPasswordPrompt have been used. This -// method is used to encrypt keys, and it will only use the options passed, it -// will not use the global PromptPassword. -func (c *context) promptEncryptPassword() ([]byte, error) { - switch { - case len(c.password) > 0: - return c.password, nil - case c.passwordPrompter != nil: - return c.passwordPrompter(c.passwordPrompt) - default: - return nil, nil - } -} - -// Options is the type to add attributes to the context. -type Options func(o *context) error - -// withContext replaces the context with the given one. -func withContext(c *context) Options { - return func(ctx *context) error { - *ctx = *c - return nil - } -} - -// WithFilename is a method that adds the given filename to the context. -func WithFilename(name string) Options { - return func(ctx *context) error { - ctx.filename = name - // Default perm mode if not set - if ctx.perm == 0 { - ctx.perm = 0600 - } - return nil - } -} - -// ToFile is a method that adds the given filename and permissions to the -// context. It is used in the Serialize to store PEM in disk. -func ToFile(name string, perm os.FileMode) Options { - return func(ctx *context) error { - ctx.filename = name - ctx.perm = perm - return nil - } -} - -// WithPassword is a method that adds the given password to the context. -func WithPassword(pass []byte) Options { - return func(ctx *context) error { - ctx.password = pass - return nil - } -} - -// WithPasswordFile is a method that adds the password in a file to the context. -func WithPasswordFile(filename string) Options { - return func(ctx *context) error { - b, err := utils.ReadPasswordFromFile(filename) - if err != nil { - return err - } - ctx.password = b - return nil - } -} - -// WithPasswordPrompt ask the user for a password and adds it to the context. -func WithPasswordPrompt(prompt string, fn PasswordPrompter) Options { - return func(ctx *context) error { - ctx.passwordPrompt = prompt - ctx.passwordPrompter = fn - return nil - } -} - -// WithPKCS8 with v set to true returns an option used in the Serialize method -// to use the PKCS#8 encoding form on the private keys. With v set to false -// default form will be used. -func WithPKCS8(v bool) Options { - return func(ctx *context) error { - ctx.pkcs8 = v - return nil - } -} - -// WithOpenSSH is an option used in the Serialize method to use OpenSSH encoding -// form on the private keys. With v set to false default form will be used. -func WithOpenSSH(v bool) Options { - return func(ctx *context) error { - ctx.openSSH = v - return nil - } -} - -// WithComment is an option used in the Serialize method to add a comment in the -// OpenSSH private keys. WithOpenSSH must be set to true too. -func WithComment(comment string) Options { - return func(ctx *context) error { - ctx.comment = comment - return nil - } -} - -// WithFirstBlock will avoid failing if a PEM contains more than one block or -// certificate and it will only look at the first. -func WithFirstBlock() Options { - return func(ctx *context) error { - ctx.firstBlock = true - return nil - } -} - -// ParseCertificate extracts the first certificate from the given pem. -func ParseCertificate(pemData []byte) (*x509.Certificate, error) { - var block *pem.Block - for len(pemData) > 0 { - block, pemData = pem.Decode(pemData) - if block == nil { - return nil, errors.New("error decoding pem block") - } - if block.Type != "CERTIFICATE" || len(block.Headers) != 0 { - continue - } - - cert, err := x509.ParseCertificate(block.Bytes) - if err != nil { - return nil, errors.Wrap(err, "error parsing certificate") - } - return cert, nil - } - - return nil, errors.New("error parsing certificate: no certificate found") -} - -// ParseCertificateBundle returns a list of *x509.Certificate parsed from -// the given bytes. -// -// - supports PEM and DER certificate formats -// - If a DER-formatted file is given only one certificate will be returned. -func ParseCertificateBundle(data []byte) ([]*x509.Certificate, error) { - var err error - - // PEM format - if bytes.Contains(data, PEMBlockHeader) { - var block *pem.Block - var bundle []*x509.Certificate - for len(data) > 0 { - block, data = pem.Decode(data) - if block == nil { - break - } - if block.Type != "CERTIFICATE" || len(block.Headers) != 0 { - continue - } - var crt *x509.Certificate - crt, err = x509.ParseCertificate(block.Bytes) - if err != nil { - return nil, &InvalidPEMError{ - Err: err, - Type: PEMTypeCertificate, - } - } - bundle = append(bundle, crt) - } - if len(bundle) == 0 { - return nil, &InvalidPEMError{ - Type: PEMTypeCertificate, - } - } - return bundle, nil - } - - // DER format (binary) - crt, err := x509.ParseCertificate(data) - if err != nil { - return nil, &InvalidPEMError{ - Message: fmt.Sprintf("error parsing certificate as DER format: %v", err), - Type: PEMTypeCertificate, - } - } - return []*x509.Certificate{crt}, nil -} - -// ParseCertificateRequest extracts the first *x509.CertificateRequest -// from the given data. -// -// - supports PEM and DER certificate formats -// - If a DER-formatted file is given only one certificate will be returned. -func ParseCertificateRequest(data []byte) (*x509.CertificateRequest, error) { - // PEM format - if bytes.Contains(data, PEMBlockHeader) { - var block *pem.Block - for len(data) > 0 { - block, data = pem.Decode(data) - if block == nil { - break - } - if !strings.HasSuffix(block.Type, "CERTIFICATE REQUEST") { - continue - } - csr, err := x509.ParseCertificateRequest(block.Bytes) - if err != nil { - return nil, &InvalidPEMError{ - Type: PEMTypeCertificateRequest, - Err: err, - } - } - - return csr, nil - } - } - - // DER format (binary) - csr, err := x509.ParseCertificateRequest(data) - if err != nil { - return nil, &InvalidPEMError{ - Message: fmt.Sprintf("error parsing certificate request as DER format: %v", err), - Type: PEMTypeCertificateRequest, - } - } - return csr, nil -} - -// PEMType represents a PEM block type. (e.g., CERTIFICATE, CERTIFICATE REQUEST, etc.) -type PEMType int - -func (pt PEMType) String() string { - switch pt { - case PEMTypeCertificate: - return "certificate" - case PEMTypeCertificateRequest: - return "certificate request" - default: - return "undefined" - } -} - -const ( - // PEMTypeUndefined undefined - PEMTypeUndefined = iota - // PEMTypeCertificate CERTIFICATE - PEMTypeCertificate - // PEMTypeCertificateRequest CERTIFICATE REQUEST - PEMTypeCertificateRequest -) - -// InvalidPEMError represents an error that occurs when parsing a file with -// PEM encoded data. -type InvalidPEMError struct { - Type PEMType - File string - Message string - Err error -} - -func (e *InvalidPEMError) Error() string { - switch { - case e.Message != "": - return e.Message - case e.Err != nil: - return fmt.Sprintf("error decoding PEM data: %v", e.Err) - default: - if e.Type == PEMTypeUndefined { - return "does not contain valid PEM encoded data" - } - return fmt.Sprintf("does not contain a valid PEM encoded %s", e.Type) - } -} - -func (e *InvalidPEMError) Unwrap() error { - return e.Err -} - -// ReadCertificate returns a *x509.Certificate from the given filename. It -// supports certificates formats PEM and DER. -func ReadCertificate(filename string, opts ...Options) (*x509.Certificate, error) { - // Populate options - ctx := newContext(filename) - if err := ctx.apply(opts); err != nil { - return nil, err - } - - bundle, err := ReadCertificateBundle(filename) - switch { - case err != nil: - return nil, err - case len(bundle) == 0: - return nil, errors.Errorf("file %s does not contain a valid PEM or DER formatted certificate", filename) - case len(bundle) > 1 && !ctx.firstBlock: - return nil, errors.Errorf("error decoding %s: contains more than one PEM encoded block", filename) - default: - return bundle[0], nil - } -} - -// ReadCertificateBundle reads the given filename and returns a list of -// *x509.Certificate. -// -// - supports PEM and DER certificate formats -// - If a DER-formatted file is given only one certificate will be returned. -func ReadCertificateBundle(filename string) ([]*x509.Certificate, error) { - b, err := utils.ReadFile(filename) - if err != nil { - return nil, err - } - - bundle, err := ParseCertificateBundle(b) - if err != nil { - return nil, fmt.Errorf("error parsing %s: %w", filename, err) - } - return bundle, nil -} - -// ReadCertificateRequest reads the given filename and returns a -// *x509.CertificateRequest. -// -// - supports PEM and DER Certificate formats. -// - supports reading from STDIN with filename `-`. -func ReadCertificateRequest(filename string) (*x509.CertificateRequest, error) { - b, err := utils.ReadFile(filename) - if err != nil { - return nil, err - } - - cr, err := ParseCertificateRequest(b) - if err != nil { - return nil, fmt.Errorf("error parsing %s: %w", filename, err) - } - return cr, nil -} - -// Parse returns the key or certificate PEM-encoded in the given bytes. -func Parse(b []byte, opts ...Options) (interface{}, error) { - // Populate options - ctx := newContext("PEM") - if err := ctx.apply(opts); err != nil { - return nil, err - } - - block, rest := pem.Decode(b) - switch { - case block == nil: - return nil, errors.Errorf("error decoding %s: not a valid PEM encoded block", ctx.filename) - case len(bytes.TrimSpace(rest)) > 0 && !ctx.firstBlock: - return nil, errors.Errorf("error decoding %s: contains more than one PEM encoded block", ctx.filename) - } - - // PEM is encrypted: ask for password - if block.Headers["Proc-Type"] == "4,ENCRYPTED" || block.Type == "ENCRYPTED PRIVATE KEY" { - pass, err := ctx.promptPassword() - if err != nil { - return nil, err - } - - block.Bytes, err = DecryptPEMBlock(block, pass) - if err != nil { - return nil, errors.Wrapf(err, "error decrypting %s", ctx.filename) - } - } - - switch block.Type { - case "PUBLIC KEY": - pub, err := x509.ParsePKIXPublicKey(block.Bytes) - return pub, errors.Wrapf(err, "error parsing %s", ctx.filename) - case "RSA PRIVATE KEY": - priv, err := x509.ParsePKCS1PrivateKey(block.Bytes) - return priv, errors.Wrapf(err, "error parsing %s", ctx.filename) - case "EC PRIVATE KEY": - priv, err := x509.ParseECPrivateKey(block.Bytes) - return priv, errors.Wrapf(err, "error parsing %s", ctx.filename) - case "PRIVATE KEY", "ENCRYPTED PRIVATE KEY": - priv, err := x509.ParsePKCS8PrivateKey(block.Bytes) - return priv, errors.Wrapf(err, "error parsing %s", ctx.filename) - case "OPENSSH PRIVATE KEY": - priv, err := ParseOpenSSHPrivateKey(b, withContext(ctx)) - return priv, errors.Wrapf(err, "error parsing %s", ctx.filename) - case "CERTIFICATE": - crt, err := x509.ParseCertificate(block.Bytes) - return crt, errors.Wrapf(err, "error parsing %s", ctx.filename) - case "CERTIFICATE REQUEST", "NEW CERTIFICATE REQUEST": - csr, err := x509.ParseCertificateRequest(block.Bytes) - return csr, errors.Wrapf(err, "error parsing %s", ctx.filename) - case "ENCRYPTED COSIGN PRIVATE KEY": - pass, err := ctx.promptPassword() - if err != nil { - return nil, err - } - priv, err := ParseCosignPrivateKey(block.Bytes, pass) - return priv, errors.Wrapf(err, "error parsing %s", ctx.filename) - case "NEBULA X25519 PUBLIC KEY": - if len(block.Bytes) != x25519.PublicKeySize { - return nil, errors.Errorf("error parsing %s: key is not 32 bytes", ctx.filename) - } - return x25519.PublicKey(block.Bytes), nil - case "NEBULA X25519 PRIVATE KEY": - if len(block.Bytes) != x25519.PrivateKeySize { - return nil, errors.Errorf("error parsing %s: key is not 32 bytes", ctx.filename) - } - return x25519.PrivateKey(block.Bytes), nil - default: - return nil, errors.Errorf("error decoding %s: contains an unexpected header '%s'", ctx.filename, block.Type) - } -} - -// ParseKey returns the key or the public key of a certificate or certificate -// signing request in the given PEM-encoded bytes. -func ParseKey(b []byte, opts ...Options) (interface{}, error) { - k, err := Parse(b, opts...) - if err != nil { - return nil, err - } - return keyutil.ExtractKey(k) -} - -// Read returns the key or certificate encoded in the given PEM file. -// If the file is encrypted it will ask for a password and it will try -// to decrypt it. -// -// Supported keys algorithms are RSA and EC. Supported standards for private -// keys are PKCS#1, PKCS#8, RFC5915 for EC, and base64-encoded DER for -// certificates and public keys. -func Read(filename string, opts ...Options) (interface{}, error) { - b, err := utils.ReadFile(filename) - if err != nil { - return nil, err - } - - // force given filename - opts = append(opts, WithFilename(filename)) - return Parse(b, opts...) -} - -// Serialize will serialize the input to a PEM formatted block and apply -// modifiers. -func Serialize(in interface{}, opts ...Options) (*pem.Block, error) { - ctx := new(context) - if err := ctx.apply(opts); err != nil { - return nil, err - } - - var p *pem.Block - var isPrivateKey bool - switch k := in.(type) { - case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey: - b, err := x509.MarshalPKIXPublicKey(k) - if err != nil { - return nil, errors.WithStack(err) - } - p = &pem.Block{ - Type: "PUBLIC KEY", - Bytes: b, - } - case *rsa.PrivateKey: - isPrivateKey = true - switch { - case ctx.pkcs8: - b, err := x509.MarshalPKCS8PrivateKey(k) - if err != nil { - return nil, err - } - p = &pem.Block{ - Type: "PRIVATE KEY", - Bytes: b, - } - case ctx.openSSH: - return SerializeOpenSSHPrivateKey(k, withContext(ctx)) - default: - p = &pem.Block{ - Type: "RSA PRIVATE KEY", - Bytes: x509.MarshalPKCS1PrivateKey(k), - } - } - case *ecdsa.PrivateKey: - isPrivateKey = true - switch { - case ctx.pkcs8: - b, err := x509.MarshalPKCS8PrivateKey(k) - if err != nil { - return nil, err - } - p = &pem.Block{ - Type: "PRIVATE KEY", - Bytes: b, - } - case ctx.openSSH: - return SerializeOpenSSHPrivateKey(k, withContext(ctx)) - default: - b, err := x509.MarshalECPrivateKey(k) - if err != nil { - return nil, errors.Wrap(err, "failed to marshal private key") - } - p = &pem.Block{ - Type: "EC PRIVATE KEY", - Bytes: b, - } - } - case ed25519.PrivateKey: - isPrivateKey = true - switch { - case !ctx.pkcs8 && ctx.openSSH: - return SerializeOpenSSHPrivateKey(k, withContext(ctx)) - default: // Ed25519 keys will use pkcs8 by default - ctx.pkcs8 = true - b, err := x509.MarshalPKCS8PrivateKey(k) - if err != nil { - return nil, err - } - p = &pem.Block{ - Type: "PRIVATE KEY", - Bytes: b, - } - } - case *x509.Certificate: - p = &pem.Block{ - Type: "CERTIFICATE", - Bytes: k.Raw, - } - case *x509.CertificateRequest: - p = &pem.Block{ - Type: "CERTIFICATE REQUEST", - Bytes: k.Raw, - } - default: - return nil, errors.Errorf("cannot serialize type '%T', value '%v'", k, k) - } - - if isPrivateKey { - // Request password if needed. - password, err := ctx.promptEncryptPassword() - if err != nil { - return nil, err - } - - // Apply options on the PEM blocks. - if password != nil { - if ctx.pkcs8 { - var err error - p, err = EncryptPKCS8PrivateKey(rand.Reader, p.Bytes, password, DefaultEncCipher) - if err != nil { - return nil, err - } - } else { - var err error - p, err = x509.EncryptPEMBlock(rand.Reader, p.Type, p.Bytes, password, DefaultEncCipher) - if err != nil { - return nil, errors.Wrap(err, "failed to serialize to PEM") - } - } - } - } - - if ctx.filename != "" { - if err := WriteFile(ctx.filename, pem.EncodeToMemory(p), ctx.perm); err != nil { - return nil, err - } - } - - return p, nil -} - -// ParseDER parses the given DER-encoded bytes and results the public or private -// key encoded. -func ParseDER(b []byte) (interface{}, error) { - // Try private keys - key, err := x509.ParsePKCS8PrivateKey(b) - if err != nil { - if key, err = x509.ParseECPrivateKey(b); err != nil { - key, err = x509.ParsePKCS1PrivateKey(b) - } - } - - // Try public key - if err != nil { - if key, err = x509.ParsePKIXPublicKey(b); err != nil { - if key, err = x509.ParsePKCS1PublicKey(b); err != nil { - return nil, errors.New("error decoding DER; bad format") - } - } - } - - return key, nil -} - -// ParseSSH parses parses a public key from an authorized_keys file used in -// OpenSSH according to the sshd(8) manual page. -func ParseSSH(b []byte) (interface{}, error) { - key, _, _, _, err := ssh.ParseAuthorizedKey(b) - if err != nil { - return nil, errors.Wrap(err, "error parsing OpenSSH key") - } - - if cert, ok := key.(*ssh.Certificate); ok { - key = cert.Key - } - - switch key.Type() { - case ssh.KeyAlgoRSA: - var w struct { - Name string - E *big.Int - N *big.Int - } - if err := ssh.Unmarshal(key.Marshal(), &w); err != nil { - return nil, errors.Wrap(err, "error unmarshaling key") - } - - if w.E.BitLen() > 24 { - return nil, errors.New("error unmarshaling key: exponent too large") - } - e := w.E.Int64() - if e < 3 || e&1 == 0 { - return nil, errors.New("error unmarshaling key: incorrect exponent") - } - - key := new(rsa.PublicKey) - key.E = int(e) - key.N = w.N - return key, nil - - case ssh.KeyAlgoECDSA256, ssh.KeyAlgoECDSA384, ssh.KeyAlgoECDSA521: - var w struct { - Name string - ID string - KeyBytes []byte - } - if err := ssh.Unmarshal(key.Marshal(), &w); err != nil { - return nil, errors.Wrap(err, "error unmarshaling key") - } - - var c ecdh.Curve - switch w.Name { - case ssh.KeyAlgoECDSA256: - c = ecdh.P256() - case ssh.KeyAlgoECDSA384: - c = ecdh.P384() - case ssh.KeyAlgoECDSA521: - c = ecdh.P521() - default: - return nil, errors.Errorf("unsupported ecdsa curve %s", w.Name) - } - - var p *ecdh.PublicKey - if p, err = c.NewPublicKey(w.KeyBytes); err != nil { - return nil, errors.Wrapf(err, "failed decoding %s key", w.Name) - } - - // convert ECDH public key to ECDSA public key to keep - // the returned type backwards compatible. - rawKey := p.Bytes() - switch p.Curve() { - case ecdh.P256(): - return &ecdsa.PublicKey{ - Curve: elliptic.P256(), - X: big.NewInt(0).SetBytes(rawKey[1:33]), - Y: big.NewInt(0).SetBytes(rawKey[33:]), - }, nil - case ecdh.P384(): - return &ecdsa.PublicKey{ - Curve: elliptic.P384(), - X: big.NewInt(0).SetBytes(rawKey[1:49]), - Y: big.NewInt(0).SetBytes(rawKey[49:]), - }, nil - case ecdh.P521(): - return &ecdsa.PublicKey{ - Curve: elliptic.P521(), - X: big.NewInt(0).SetBytes(rawKey[1:67]), - Y: big.NewInt(0).SetBytes(rawKey[67:]), - }, nil - default: - return nil, errors.New("cannot convert non-NIST *ecdh.PublicKey to *ecdsa.PublicKey") - } - case ssh.KeyAlgoED25519: - var w struct { - Name string - KeyBytes []byte - } - if err := ssh.Unmarshal(key.Marshal(), &w); err != nil { - return nil, errors.Wrap(err, "error unmarshaling key") - } - return ed25519.PublicKey(w.KeyBytes), nil - case ssh.KeyAlgoDSA: - return nil, errors.Errorf("DSA keys not supported") - default: - return nil, errors.Errorf("unsupported key type %T", key) - } -} - -// BundleCertificate adds PEM-encoded certificates to a PEM-encoded certificate -// bundle if not already in the bundle. -func BundleCertificate(bundlePEM []byte, certsPEM ...[]byte) ([]byte, bool, error) { - bundle, err := ParseCertificateBundle(bundlePEM) - if err != nil { - return nil, false, fmt.Errorf("invalid bundle: %w", err) - } - - sums := make(map[[sha256.Size224]byte]bool, len(bundle)+len(certsPEM)) - for i := range bundle { - sums[sha256.Sum224(bundle[i].Raw)] = true - } - - modified := false - - for i := range certsPEM { - cert, err := ParseCertificate(certsPEM[i]) - if err != nil { - return nil, false, fmt.Errorf("invalid certificate %d: %w", i, err) - } - certSum := sha256.Sum224(cert.Raw) - if sums[certSum] { - continue - } - sums[certSum] = true - bundlePEM = append(bundlePEM, certsPEM[i]...) - modified = true - } - - return bundlePEM, modified, nil -} - -// UnbundleCertificate removes PEM-encoded certificates from a PEM-encoded -// certificate bundle. -func UnbundleCertificate(bundlePEM []byte, certsPEM ...[]byte) ([]byte, bool, error) { - if len(certsPEM) == 0 { - return bundlePEM, false, nil - } - drop := make(map[[sha256.Size224]byte]bool, len(certsPEM)) - for i := range certsPEM { - certs, err := ParseCertificateBundle(certsPEM[i]) - if err != nil { - return nil, false, fmt.Errorf("invalid certificate %d: %w", i, err) - } - for _, cert := range certs { - drop[sha256.Sum224(cert.Raw)] = true - } - } - - var modified bool - var keep []byte - - bundle, err := ParseCertificateBundle(bundlePEM) - if err != nil { - return nil, false, fmt.Errorf("invalid bundle: %w", err) - } - for _, cert := range bundle { - sum := sha256.Sum224(cert.Raw) - if drop[sum] { - modified = true - continue - } - keep = append(keep, pem.EncodeToMemory(&pem.Block{ - Type: "CERTIFICATE", - Bytes: cert.Raw, - })...) - } - - return keep, modified, nil -} diff --git a/vendor/go.step.sm/crypto/pemutil/pkcs8.go b/vendor/go.step.sm/crypto/pemutil/pkcs8.go deleted file mode 100644 index fb6c96c295..0000000000 --- a/vendor/go.step.sm/crypto/pemutil/pkcs8.go +++ /dev/null @@ -1,353 +0,0 @@ -package pemutil - -import ( - "crypto/aes" - "crypto/cipher" - "crypto/des" //nolint:gosec // support for legacy keys - "crypto/sha1" //nolint:gosec // support for legacy keys - "crypto/sha256" - "crypto/x509" - "crypto/x509/pkix" - "encoding/asn1" - "encoding/pem" - "hash" - "io" - - "github.com/pkg/errors" - "golang.org/x/crypto/pbkdf2" -) - -// PBKDF2SaltSize is the default size of the salt for PBKDF2, 128-bit salt. -const PBKDF2SaltSize = 16 - -// PBKDF2Iterations is the default number of iterations for PBKDF2. -// -// 600k is the current OWASP recommendation (Dec 2022) -// https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2 -// -// Nist recommends at least 10k (800-63B), 1Password increased in 2023 the -// number of iterations from 100k to 650k. -const PBKDF2Iterations = 600000 - -// pkcs8 reflects an ASN.1, PKCS#8 PrivateKey. See -// ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-8/pkcs-8v1_2.asn -// and RFC 5208. -type pkcs8 struct { - Version int - Algo pkix.AlgorithmIdentifier - PrivateKey []byte - // optional attributes omitted. -} - -type publicKeyInfo struct { - Raw asn1.RawContent - Algo pkix.AlgorithmIdentifier - PublicKey asn1.BitString -} - -// Encrypted pkcs8 -// Based on https://github.com/youmark/pkcs8 -// MIT license -type prfParam struct { - Algo asn1.ObjectIdentifier - NullParam asn1.RawValue -} - -type pbkdf2Params struct { - Salt []byte - IterationCount int - PrfParam prfParam `asn1:"optional"` -} - -type pbkdf2Algorithms struct { - Algo asn1.ObjectIdentifier - PBKDF2Params pbkdf2Params -} - -type pbkdf2Encs struct { - EncryAlgo asn1.ObjectIdentifier - IV []byte -} - -type pbes2Params struct { - KeyDerivationFunc pbkdf2Algorithms - EncryptionScheme pbkdf2Encs -} - -type encryptedlAlgorithmIdentifier struct { - Algorithm asn1.ObjectIdentifier - Parameters pbes2Params -} - -type encryptedPrivateKeyInfo struct { - Algo encryptedlAlgorithmIdentifier - PrivateKey []byte -} - -var ( - // key derivation functions - oidPKCS5PBKDF2 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 5, 12} - oidPBES2 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 5, 13} - oidHMACWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 113549, 2, 9} - - // encryption - oidAES128CBC = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 1, 2} - oidAES192CBC = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 1, 22} - oidAES256CBC = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 1, 42} - oidDESCBC = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 7} - oidD3DESCBC = asn1.ObjectIdentifier{1, 2, 840, 113549, 3, 7} -) - -// rfc1423Algo holds a method for enciphering a PEM block. -type rfc1423Algo struct { - cipher x509.PEMCipher - name string - cipherFunc func(key []byte) (cipher.Block, error) - keySize int - blockSize int - identifier asn1.ObjectIdentifier -} - -// rfc1423Algos holds a slice of the possible ways to encrypt a PEM -// block. The ivSize numbers were taken from the OpenSSL source. -var rfc1423Algos = []rfc1423Algo{{ - cipher: x509.PEMCipherDES, - name: "DES-CBC", - cipherFunc: des.NewCipher, - keySize: 8, - blockSize: des.BlockSize, - identifier: oidDESCBC, -}, { - cipher: x509.PEMCipher3DES, - name: "DES-EDE3-CBC", - cipherFunc: des.NewTripleDESCipher, - keySize: 24, - blockSize: des.BlockSize, - identifier: oidD3DESCBC, -}, { - cipher: x509.PEMCipherAES128, - name: "AES-128-CBC", - cipherFunc: aes.NewCipher, - keySize: 16, - blockSize: aes.BlockSize, - identifier: oidAES128CBC, -}, { - cipher: x509.PEMCipherAES192, - name: "AES-192-CBC", - cipherFunc: aes.NewCipher, - keySize: 24, - blockSize: aes.BlockSize, - identifier: oidAES192CBC, -}, { - cipher: x509.PEMCipherAES256, - name: "AES-256-CBC", - cipherFunc: aes.NewCipher, - keySize: 32, - blockSize: aes.BlockSize, - identifier: oidAES256CBC, -}, -} - -func cipherByKey(key x509.PEMCipher) *rfc1423Algo { - for i := range rfc1423Algos { - alg := &rfc1423Algos[i] - if alg.cipher == key { - return alg - } - } - return nil -} - -// deriveKey uses a key derivation function to stretch the password into a key -// with the number of bits our cipher requires. This algorithm was derived from -// the OpenSSL source. -func (c rfc1423Algo) deriveKey(password, salt []byte, h func() hash.Hash) []byte { - return pbkdf2.Key(password, salt, PBKDF2Iterations, c.keySize, h) -} - -// DecryptPEMBlock takes a password encrypted PEM block and the password used -// to encrypt it and returns a slice of decrypted DER encoded bytes. -// -// If the PEM blocks has the Proc-Type header set to "4,ENCRYPTED" it uses -// x509.DecryptPEMBlock to decrypt the block. If not it tries to decrypt the -// block using AES-128-CBC, AES-192-CBC, AES-256-CBC, DES, or 3DES using the -// key derived using PBKDF2 over the given password. -func DecryptPEMBlock(block *pem.Block, password []byte) ([]byte, error) { - if block.Headers["Proc-Type"] == "4,ENCRYPTED" { - return x509.DecryptPEMBlock(block, password) - } - - // PKCS#8 header defined in RFC7468 section 11 - if block.Type == "ENCRYPTED PRIVATE KEY" { - return DecryptPKCS8PrivateKey(block.Bytes, password) - } - - return nil, errors.New("unsupported encrypted PEM") -} - -// DecryptPKCS8PrivateKey takes a password encrypted private key using the -// PKCS#8 encoding and returns the decrypted data in PKCS#8 form. If an -// incorrect password is detected an x509.IncorrectPasswordError is returned. -// Because of deficiencies in the format, it's not always possible to detect an -// incorrect password. In these cases no error will be returned but the -// decrypted DER bytes will be random noise. -// -// It supports AES-128-CBC, AES-192-CBC, AES-256-CBC, DES, or 3DES encrypted -// data using the key derived with PBKDF2 over the given password. -func DecryptPKCS8PrivateKey(data, password []byte) ([]byte, error) { - var pki encryptedPrivateKeyInfo - if _, err := asn1.Unmarshal(data, &pki); err != nil { - return nil, errors.Wrap(err, "failed to unmarshal private key") - } - - if !pki.Algo.Algorithm.Equal(oidPBES2) { - return nil, errors.New("unsupported encrypted PEM: only PBES2 is supported") - } - - if !pki.Algo.Parameters.KeyDerivationFunc.Algo.Equal(oidPKCS5PBKDF2) { - return nil, errors.New("unsupported encrypted PEM: only PBKDF2 is supported") - } - - encParam := pki.Algo.Parameters.EncryptionScheme - kdfParam := pki.Algo.Parameters.KeyDerivationFunc.PBKDF2Params - - iv := encParam.IV - salt := kdfParam.Salt - iter := kdfParam.IterationCount - - // pbkdf2 hash function - keyHash := sha1.New - if kdfParam.PrfParam.Algo.Equal(oidHMACWithSHA256) { - keyHash = sha256.New - } - - var symkey []byte - var block cipher.Block - var err error - switch { - // AES-128-CBC, AES-192-CBC, AES-256-CBC - case encParam.EncryAlgo.Equal(oidAES128CBC): - symkey = pbkdf2.Key(password, salt, iter, 16, keyHash) - block, err = aes.NewCipher(symkey) - case encParam.EncryAlgo.Equal(oidAES192CBC): - symkey = pbkdf2.Key(password, salt, iter, 24, keyHash) - block, err = aes.NewCipher(symkey) - case encParam.EncryAlgo.Equal(oidAES256CBC): - symkey = pbkdf2.Key(password, salt, iter, 32, keyHash) - block, err = aes.NewCipher(symkey) - // DES, TripleDES - case encParam.EncryAlgo.Equal(oidDESCBC): - symkey = pbkdf2.Key(password, salt, iter, 8, keyHash) - block, err = des.NewCipher(symkey) //nolint:gosec // support for legacy keys - case encParam.EncryAlgo.Equal(oidD3DESCBC): - symkey = pbkdf2.Key(password, salt, iter, 24, keyHash) - block, err = des.NewTripleDESCipher(symkey) //nolint:gosec // support for legacy keys - default: - return nil, errors.Errorf("unsupported encrypted PEM: unknown algorithm %v", encParam.EncryAlgo) - } - if err != nil { - return nil, err - } - - data = pki.PrivateKey - mode := cipher.NewCBCDecrypter(block, iv) - mode.CryptBlocks(data, data) - - // Blocks are padded using a scheme where the last n bytes of padding are all - // equal to n. It can pad from 1 to blocksize bytes inclusive. See RFC 1423. - // For example: - // [x y z 2 2] - // [x y 7 7 7 7 7 7 7] - // If we detect a bad padding, we assume it is an invalid password. - blockSize := block.BlockSize() - dlen := len(data) - if dlen == 0 || dlen%blockSize != 0 { - return nil, errors.New("error decrypting PEM: invalid padding") - } - - last := int(data[dlen-1]) - if dlen < last { - return nil, x509.IncorrectPasswordError - } - if last == 0 || last > blockSize { - return nil, x509.IncorrectPasswordError - } - for _, val := range data[dlen-last:] { - if int(val) != last { - return nil, x509.IncorrectPasswordError - } - } - - return data[:dlen-last], nil -} - -// EncryptPKCS8PrivateKey returns a PEM block holding the given PKCS#8 encroded -// private key, encrypted with the specified algorithm and a PBKDF2 derived key -// from the given password. -func EncryptPKCS8PrivateKey(rand io.Reader, data, password []byte, alg x509.PEMCipher) (*pem.Block, error) { - ciph := cipherByKey(alg) - if ciph == nil { - return nil, errors.Errorf("failed to encrypt PEM: unknown algorithm %v", alg) - } - - salt := make([]byte, PBKDF2SaltSize) - if _, err := io.ReadFull(rand, salt); err != nil { - return nil, errors.Wrap(err, "failed to generate salt") - } - iv := make([]byte, ciph.blockSize) - if _, err := io.ReadFull(rand, iv); err != nil { - return nil, errors.Wrap(err, "failed to generate IV") - } - - key := ciph.deriveKey(password, salt, sha256.New) - block, err := ciph.cipherFunc(key) - if err != nil { - return nil, errors.Wrap(err, "failed to create cipher") - } - enc := cipher.NewCBCEncrypter(block, iv) - pad := ciph.blockSize - len(data)%ciph.blockSize - encrypted := make([]byte, len(data), len(data)+pad) - // We could save this copy by encrypting all the whole blocks in - // the data separately, but it doesn't seem worth the additional - // code. - copy(encrypted, data) - // See RFC 1423, section 1.1 - for i := 0; i < pad; i++ { - encrypted = append(encrypted, byte(pad)) - } - enc.CryptBlocks(encrypted, encrypted) - - // Build encrypted asn1 data - pki := encryptedPrivateKeyInfo{ - Algo: encryptedlAlgorithmIdentifier{ - Algorithm: oidPBES2, - Parameters: pbes2Params{ - KeyDerivationFunc: pbkdf2Algorithms{ - Algo: oidPKCS5PBKDF2, - PBKDF2Params: pbkdf2Params{ - Salt: salt, - IterationCount: PBKDF2Iterations, - PrfParam: prfParam{ - Algo: oidHMACWithSHA256, - NullParam: asn1.NullRawValue, - }, - }, - }, - EncryptionScheme: pbkdf2Encs{ - EncryAlgo: ciph.identifier, - IV: iv, - }, - }, - }, - PrivateKey: encrypted, - } - - b, err := asn1.Marshal(pki) - if err != nil { - return nil, errors.Wrap(err, "error marshaling encrypted key") - } - return &pem.Block{ - Type: "ENCRYPTED PRIVATE KEY", - Bytes: b, - }, nil -} diff --git a/vendor/go.step.sm/crypto/pemutil/ssh.go b/vendor/go.step.sm/crypto/pemutil/ssh.go deleted file mode 100644 index 00698dae19..0000000000 --- a/vendor/go.step.sm/crypto/pemutil/ssh.go +++ /dev/null @@ -1,299 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pemutil - -import ( - "crypto" - "crypto/aes" - "crypto/cipher" - "crypto/ecdsa" - "crypto/ed25519" - "crypto/rand" - "crypto/rsa" - "encoding/binary" - "encoding/pem" - "math/big" - - "github.com/pkg/errors" - bcryptpbkdf "go.step.sm/crypto/internal/bcrypt_pbkdf" - "go.step.sm/crypto/randutil" - "golang.org/x/crypto/ssh" -) - -const ( - sshMagic = "openssh-key-v1\x00" - sshDefaultKdf = "bcrypt" - sshDefaultCiphername = "aes256-ctr" - sshDefaultKeyLength = 32 - sshDefaultSaltLength = 16 - sshDefaultRounds = 16 -) - -type openSSHPrivateKey struct { - CipherName string - KdfName string - KdfOpts string - NumKeys uint32 - PubKey []byte - PrivKeyBlock []byte -} - -type openSSHPrivateKeyBlock struct { - Check1 uint32 - Check2 uint32 - Keytype string - Rest []byte `ssh:"rest"` -} - -// ParseOpenSSHPrivateKey parses a private key in OpenSSH PEM format. -// -// Implemented based on the documentation at -// https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key -// -// This method is based on the implementation at -// https://github.com/golang/crypto/blob/master/ssh/keys.go -func ParseOpenSSHPrivateKey(pemBytes []byte, opts ...Options) (crypto.PrivateKey, error) { - // Populate options - ctx := newContext("PEM") - if err := ctx.apply(opts); err != nil { - return nil, err - } - - block, _ := pem.Decode(pemBytes) - if block == nil { - return nil, errors.Errorf("error decoding %s: not a valid PEM encoded block", ctx.filename) - } - - if len(block.Bytes) < len(sshMagic) || string(block.Bytes[:len(sshMagic)]) != sshMagic { - return nil, errors.New("invalid openssh private key format") - } - remaining := block.Bytes[len(sshMagic):] - - var w openSSHPrivateKey - if err := ssh.Unmarshal(remaining, &w); err != nil { - return nil, errors.Wrap(err, "error unmarshaling private key") - } - - var err error - var key crypto.PrivateKey - if w.KdfName != "none" || w.CipherName != "none" { - password, err := ctx.promptPassword() - if err != nil { - return nil, err - } - key, err = ssh.ParseRawPrivateKeyWithPassphrase(pemBytes, password) - if err != nil { - return nil, errors.Wrap(err, "error parsing private key") - } - } else { - key, err = ssh.ParseRawPrivateKey(pemBytes) - if err != nil { - return nil, errors.Wrap(err, "error parsing private key") - } - } - - // Convert *ed25519.PrivateKey to ed25519.PrivateKey: - switch k := key.(type) { - case *ed25519.PrivateKey: - return *k, nil - default: - return k, nil - } -} - -// SerializeOpenSSHPrivateKey serialize a private key in the OpenSSH PEM format. -func SerializeOpenSSHPrivateKey(key crypto.PrivateKey, opts ...Options) (*pem.Block, error) { - ctx := new(context) - if err := ctx.apply(opts); err != nil { - return nil, err - } - - // Random check bytes. - var check uint32 - if err := binary.Read(rand.Reader, binary.BigEndian, &check); err != nil { - return nil, errors.Wrap(err, "error generating random check ") - } - - w := openSSHPrivateKey{ - NumKeys: 1, - } - pk1 := openSSHPrivateKeyBlock{ - Check1: check, - Check2: check, - } - - password, err := ctx.promptEncryptPassword() - if err != nil { - return nil, err - } - - var blockSize int - if password == nil { - w.CipherName = "none" - w.KdfName = "none" - blockSize = 8 - } else { - w.CipherName = sshDefaultCiphername - w.KdfName = sshDefaultKdf - blockSize = aes.BlockSize - } - - switch k := key.(type) { - case *rsa.PrivateKey: - e := new(big.Int).SetInt64(int64(k.PublicKey.E)) - // Marshal public key: - // E and N are in reversed order in the public and private key. - pubKey := struct { - KeyType string - E *big.Int - N *big.Int - }{ - ssh.KeyAlgoRSA, - e, k.PublicKey.N, - } - w.PubKey = ssh.Marshal(pubKey) - - // Marshal private key. - key := struct { - N *big.Int - E *big.Int - D *big.Int - Iqmp *big.Int - P *big.Int - Q *big.Int - Comment string - }{ - k.PublicKey.N, e, - k.D, k.Precomputed.Qinv, k.Primes[0], k.Primes[1], - ctx.comment, - } - pk1.Keytype = ssh.KeyAlgoRSA - pk1.Rest = ssh.Marshal(key) - case *ecdsa.PrivateKey: - var curve, keyType string - switch k.Curve.Params().Name { - case "P-256": - curve = "nistp256" - keyType = ssh.KeyAlgoECDSA256 - case "P-384": - curve = "nistp384" - keyType = ssh.KeyAlgoECDSA384 - case "P-521": - curve = "nistp521" - keyType = ssh.KeyAlgoECDSA521 - default: - return nil, errors.Errorf("error serializing key: unsupported curve %s", k.Curve.Params().Name) - } - - p, err := k.PublicKey.ECDH() - if err != nil { - return nil, errors.Wrapf(err, "failed converting *ecdsa.PublicKey to *ecdh.PublicKey") - } - - // Marshal public key. - pubKey := struct { - KeyType string - Curve string - Pub []byte - }{ - keyType, curve, p.Bytes(), - } - w.PubKey = ssh.Marshal(pubKey) - - // Marshal private key. - key := struct { - Curve string - Pub []byte - D *big.Int - Comment string - }{ - curve, p.Bytes(), k.D, - ctx.comment, - } - pk1.Keytype = keyType - pk1.Rest = ssh.Marshal(key) - case ed25519.PrivateKey: - pub := make([]byte, ed25519.PublicKeySize) - priv := make([]byte, ed25519.PrivateKeySize) - copy(pub, k[ed25519.PublicKeySize:]) - copy(priv, k) - - // Marshal public key. - pubKey := struct { - KeyType string - Pub []byte - }{ - ssh.KeyAlgoED25519, pub, - } - w.PubKey = ssh.Marshal(pubKey) - - // Marshal private key. - key := struct { - Pub []byte - Priv []byte - Comment string - }{ - pub, priv, - ctx.comment, - } - pk1.Keytype = ssh.KeyAlgoED25519 - pk1.Rest = ssh.Marshal(key) - default: - return nil, errors.Errorf("unsupported key type %T", k) - } - - w.PrivKeyBlock = ssh.Marshal(pk1) - - // Add padding until the private key block matches the block size, - // 16 with AES encryption, 8 without. - for i, l := 0, len(w.PrivKeyBlock); (l+i)%blockSize != 0; i++ { - w.PrivKeyBlock = append(w.PrivKeyBlock, byte(i+1)) - } - - if password != nil { - // Create encryption key derivation the password. - salt, err := randutil.Salt(sshDefaultSaltLength) - if err != nil { - return nil, err - } - kdfOpts := struct { - Salt []byte - Rounds uint32 - }{salt, sshDefaultRounds} - w.KdfOpts = string(ssh.Marshal(kdfOpts)) - - // Derive key to encrypt the private key block. - k, err := bcryptpbkdf.Key(password, salt, sshDefaultRounds, sshDefaultKeyLength+aes.BlockSize) - if err != nil { - return nil, errors.Wrap(err, "error deriving decryption key") - } - - // Encrypt the private key using the derived secret. - dst := make([]byte, len(w.PrivKeyBlock)) - iv := k[sshDefaultKeyLength : sshDefaultKeyLength+aes.BlockSize] - block, err := aes.NewCipher(k[:sshDefaultKeyLength]) - if err != nil { - return nil, errors.Wrap(err, "error creating cipher") - } - - stream := cipher.NewCTR(block, iv) - stream.XORKeyStream(dst, w.PrivKeyBlock) - w.PrivKeyBlock = dst - } - - b := ssh.Marshal(w) - block := &pem.Block{ - Type: "OPENSSH PRIVATE KEY", - Bytes: append([]byte(sshMagic), b...), - } - - if ctx.filename != "" { - if err := WriteFile(ctx.filename, pem.EncodeToMemory(block), ctx.perm); err != nil { - return nil, err - } - } - - return block, nil -} diff --git a/vendor/go.step.sm/crypto/randutil/random.go b/vendor/go.step.sm/crypto/randutil/random.go deleted file mode 100644 index dce7931b18..0000000000 --- a/vendor/go.step.sm/crypto/randutil/random.go +++ /dev/null @@ -1,113 +0,0 @@ -// Package randutil provides methods to generate random strings and salts. -package randutil - -import ( - "crypto/rand" - "encoding/hex" - "io" - "math/big" - - "github.com/pkg/errors" -) - -var ascii string - -func init() { - // initialize the charcters in ascii - aciiBytes := make([]byte, 94) - for i := range aciiBytes { - aciiBytes[i] = byte(i + 33) - } - ascii = string(aciiBytes) -} - -// Salt generates a new random salt of the given size. -func Salt(size int) ([]byte, error) { - salt := make([]byte, size) - _, err := io.ReadFull(rand.Reader, salt) - if err != nil { - return nil, errors.Wrap(err, "error generating salt") - } - return salt, nil -} - -// Bytes generates a new byte slice of the given size. -func Bytes(size int) ([]byte, error) { - bytes := make([]byte, size) - _, err := io.ReadFull(rand.Reader, bytes) - if err != nil { - return nil, errors.Wrap(err, "error generating bytes") - } - return bytes, nil -} - -// String returns a random string of a given length using the characters in -// the given string. It splits the string on runes to support UTF-8 -// characters. -func String(length int, chars string) (string, error) { - result := make([]rune, length) - runes := []rune(chars) - x := int64(len(runes)) - for i := range result { - num, err := rand.Int(rand.Reader, big.NewInt(x)) - if err != nil { - return "", errors.Wrap(err, "error creating random number") - } - result[i] = runes[num.Int64()] - } - return string(result), nil -} - -// Hex returns a random string of the given length using the hexadecimal -// characters in lower case (0-9+a-f). -func Hex(length int) (string, error) { - return String(length, "0123456789abcdef") -} - -// Alphanumeric returns a random string of the given length using the 62 -// alphanumeric characters in the POSIX/C locale (a-z+A-Z+0-9). -func Alphanumeric(length int) (string, error) { - return String(length, "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") -} - -// ASCII returns a securely generated random ASCII string. It reads random -// numbers from crypto/rand and searches for printable characters. It will -// return an error if the system's secure random number generator fails to -// function correctly, in which case the caller must not continue. -func ASCII(length int) (string, error) { - return String(length, ascii) -} - -// Alphabet returns a random string of the given length using the 52 -// alphabetic characters in the POSIX/C locale (a-z+A-Z). -func Alphabet(length int) (string, error) { - return String(length, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") -} - -// UUIDv4 returns the string representation of a UUID version 4. Because 6 bits -// are used to indicate the version 4 and the variant 10, the randomly generated -// part has 122 bits. -func UUIDv4() (string, error) { - var uuid [16]byte - _, err := io.ReadFull(rand.Reader, uuid[:]) - if err != nil { - return "", errors.Wrap(err, "error generating uuid") - } - uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4 - uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 - return encodeUUID(uuid), nil -} - -func encodeUUID(uuid [16]byte) string { - buf := make([]byte, 36) - hex.Encode(buf, uuid[:4]) - buf[8] = '-' - hex.Encode(buf[9:13], uuid[4:6]) - buf[13] = '-' - hex.Encode(buf[14:18], uuid[6:8]) - buf[18] = '-' - hex.Encode(buf[19:23], uuid[8:10]) - buf[23] = '-' - hex.Encode(buf[24:], uuid[10:]) - return string(buf) -} diff --git a/vendor/go.step.sm/crypto/x25519/x25519.go b/vendor/go.step.sm/crypto/x25519/x25519.go deleted file mode 100644 index c6d239bfe2..0000000000 --- a/vendor/go.step.sm/crypto/x25519/x25519.go +++ /dev/null @@ -1,321 +0,0 @@ -package x25519 - -import ( - "bytes" - "crypto" - "crypto/ed25519" - "crypto/sha512" - "crypto/subtle" - "errors" - "io" - "strconv" - - "filippo.io/edwards25519" - "filippo.io/edwards25519/field" - "golang.org/x/crypto/curve25519" -) - -const ( - // PrivateKeySize is the size in bytes of a X25519 private key. - PrivateKeySize = 32 - - // PublicKeySize is the size in bytes of a X25519 public key. - PublicKeySize = 32 - - SignatureSize = 64 -) - -var one = (&field.Element{}).One() - -// PrivateKey is the type used to represent a X25519 private key. -type PrivateKey []byte - -// PublicKey is the type used to represent a X25519 public key. -type PublicKey []byte - -// GenerateKey generates a public/private key pair using entropy from rand. -func GenerateKey(rand io.Reader) (PublicKey, PrivateKey, error) { - priv := make([]byte, PrivateKeySize) - if _, err := io.ReadFull(rand, priv); err != nil { - return nil, nil, err - } - - pub, err := curve25519.X25519(priv, curve25519.Basepoint) - if err != nil { - return nil, nil, err - } - - return pub, priv, err -} - -// ToEd25519 converts the public key p into a ed25519 key. -// -// (x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1)) -func (p PublicKey) ToEd25519() (ed25519.PublicKey, error) { - a, err := convertMont(p) - if err != nil { - return nil, err - } - return a.Bytes(), nil -} - -// Equal reports whether p and x have the same value. -func (p PublicKey) Equal(x crypto.PublicKey) bool { - xx, ok := x.(PublicKey) - if !ok { - return false - } - return bytes.Equal(p, xx) -} - -// Public returns the public key using scalar multiplication (scalar * point) -// using the Curve25519 basepoint. It will return nil if the private key is not -// a valid one. -func (p PrivateKey) Public() crypto.PublicKey { - pub, _ := p.PublicKey() - return pub -} - -// Equal reports whether p and x have the same value. -func (p PrivateKey) Equal(x crypto.PrivateKey) bool { - xx, ok := x.(PrivateKey) - if !ok { - return false - } - return bytes.Equal(p, xx) -} - -// Public returns the public key using scalar multiplication (scalar * point) -// using the Curve25519 basepoint. -func (p PrivateKey) PublicKey() (PublicKey, error) { - pub, err := curve25519.X25519(p, curve25519.Basepoint) - if err != nil { - return nil, err - } - return pub, nil -} - -// SharedKey returns the result of the scalar multiplication (scalar * point), -// using the PrivateKey as the scalar value and the given key as the point. Both -// scalar and point must be slices of 32 bytes. -func (p PrivateKey) SharedKey(peerPublicKey []byte) ([]byte, error) { - sharedKey, err := curve25519.X25519(p, peerPublicKey) - if err != nil { - return nil, err - } - return sharedKey, nil -} - -// Sign signs the given message with the private key p and returns a signature. -// -// It implements the XEdDSA sign method defined in -// https://signal.org/docs/specifications/xeddsa/#xeddsa -// -// XEdDSA performs two passes over messages to be signed and therefore cannot -// handle pre-hashed messages. Thus opts.HashFunc() must return zero to indicate -// the message hasn't been hashed. This can be achieved by passing -// crypto.Hash(0) as the value for opts. -func (p PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) (signature []byte, err error) { - if opts.HashFunc() != crypto.Hash(0) { - return nil, errors.New("x25519: cannot sign hashed message") - } - - return Sign(rand, p, message) -} - -// Sign signs the message with privateKey and returns a signature. It will panic -// if len(privateKey) is not PrivateKeySize. -// -// It implements the XEdDSA sign method defined in -// https://signal.org/docs/specifications/xeddsa/#xeddsa -// -// xeddsa_sign(k, M, Z): -// A, a = calculate_key_pair(k) -// r = hash1(a || M || Z) (mod q) -// R = rB -// h = hash(R || A || M) (mod q) -// s = r + ha (mod q) -// return R || s -func Sign(rand io.Reader, p PrivateKey, message []byte) (signature []byte, err error) { - if l := len(p); l != PrivateKeySize { - panic("x25519: bad private key length: " + strconv.Itoa(l)) - } - - pub, priv, err := p.calculateKeyPair() - if err != nil { - return nil, err - } - - random := make([]byte, 64) - if _, err := io.ReadFull(rand, random); err != nil { - return nil, err - } - - // Using same prefix in libsignal-protocol-c implementation, but can be any - // 32 byte prefix. Golang's ed25519 implementation uses: - // - // ph := sha512.Sum512(a.Bytes()) - // prefix := ph[32:] - prefix := [32]byte{ - 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - } - - rh := sha512.New() - rh.Write(prefix[:]) - rh.Write(priv.Bytes()) - rh.Write(message) - rh.Write(random) - rDigest := make([]byte, 0, sha512.Size) - rDigest = rh.Sum(rDigest) - - r, err := edwards25519.NewScalar().SetUniformBytes(rDigest) - if err != nil { - return nil, err - } - - R := (&edwards25519.Point{}).ScalarBaseMult(r) //nolint:gocritic // variable names match crypto formulae docs - - hh := sha512.New() - hh.Write(R.Bytes()) - hh.Write(pub) - hh.Write(message) - hDigest := make([]byte, 0, sha512.Size) - hDigest = hh.Sum(hDigest) - h, err := edwards25519.NewScalar().SetUniformBytes(hDigest) - if err != nil { - return nil, err - } - - s := (&edwards25519.Scalar{}).Add(r, h.Multiply(h, priv)) - - sig := make([]byte, 64) - copy(sig[:32], R.Bytes()) - copy(sig[32:], s.Bytes()) - return sig, nil -} - -// Verify reports whether sig is a valid signature of message by publicKey. It -// will panic if len(publicKey) is not PublicKeySize. -// -// It implements the XEdDSA verify method defined in -// https://signal.org/docs/specifications/xeddsa/#xeddsa -// -// xeddsa_verify(u, M, (R || s)): -// if u >= p or R.y >= 2|p| or s >= 2|q|: -// return false -// A = convert_mont(u) -// if not on_curve(A): -// return false -// h = hash(R || A || M) (mod q) -// Rcheck = sB - hA -// if bytes_equal(R, Rcheck): -// return true -// return false -func Verify(publicKey PublicKey, message, sig []byte) bool { - // The following code should be equivalent to: - // - // pub, err := publicKey.ToEd25519() - // if err != nil { - // return false - // } - // return ed25519.Verify(pub, message, sig) - - if l := len(publicKey); l != PublicKeySize { - panic("x25519: bad public key length: " + strconv.Itoa(l)) - } - - if len(sig) != SignatureSize || sig[63]&0xE0 != 0 { - return false - } - - a, err := convertMont(publicKey) - - if err != nil { - return false - } - - hh := sha512.New() - hh.Write(sig[:32]) - hh.Write(a.Bytes()) - hh.Write(message) - hDigest := make([]byte, 0, sha512.Size) - hDigest = hh.Sum(hDigest) - h, err := edwards25519.NewScalar().SetUniformBytes(hDigest) - if err != nil { - return false - } - - s, err := edwards25519.NewScalar().SetCanonicalBytes(sig[32:]) - if err != nil { - return false - } - - minusA := (&edwards25519.Point{}).Negate(a) - r := (&edwards25519.Point{}).VarTimeDoubleScalarBaseMult(h, minusA, s) - return subtle.ConstantTimeCompare(sig[:32], r.Bytes()) == 1 -} - -// calculateKeyPair converts a Montgomery private key k to a twisted Edwards -// public key and private key (A, a) as defined in -// https://signal.org/docs/specifications/xeddsa/#elliptic-curve-conversions -// -// calculate_key_pair(k): -// E = kB -// A.y = E.y -// A.s = 0 -// if E.s == 1: -// a = -k (mod q) -// else: -// a = k (mod q) -// return A, a -func (p PrivateKey) calculateKeyPair() ([]byte, *edwards25519.Scalar, error) { - var pA edwards25519.Point - var sa edwards25519.Scalar - - k, err := (&edwards25519.Scalar{}).SetBytesWithClamping(p) - if err != nil { - return nil, nil, err - } - - pub := pA.ScalarBaseMult(k).Bytes() - signBit := (pub[31] & 0x80) >> 7 - - if signBit == 1 { - sa.Negate(k) - // Set sig bit to 0 - pub[31] &= 0x7F - } else { - sa.Set(k) - } - - return pub, &sa, nil -} - -// convertMont converts from a Montgomery u-coordinate to a twisted Edwards -// point P, according to -// https://signal.org/docs/specifications/xeddsa/#elliptic-curve-conversions -// -// convert_mont(u): -// umasked = u (mod 2|p|) -// P.y = u_to_y(umasked) -// P.s = 0 -// return P -func convertMont(u PublicKey) (*edwards25519.Point, error) { - um, err := (&field.Element{}).SetBytes(u) - if err != nil { - return nil, err - } - - // y = (u - 1)/(u + 1) - a := new(field.Element).Subtract(um, one) - b := new(field.Element).Add(um, one) - y := new(field.Element).Multiply(a, b.Invert(b)).Bytes() - - // Set sign to 0 - y[31] &= 0x7F - - return (&edwards25519.Point{}).SetBytes(y) -} diff --git a/vendor/golang.org/x/oauth2/google/default.go b/vendor/golang.org/x/oauth2/google/default.go index df958359a8..0260935bab 100644 --- a/vendor/golang.org/x/oauth2/google/default.go +++ b/vendor/golang.org/x/oauth2/google/default.go @@ -251,6 +251,12 @@ func FindDefaultCredentials(ctx context.Context, scopes ...string) (*Credentials // a Google Developers service account key file, a gcloud user credentials file (a.k.a. refresh // token JSON), or the JSON configuration file for workload identity federation in non-Google cloud // platforms (see https://cloud.google.com/iam/docs/how-to#using-workload-identity-federation). +// +// Important: If you accept a credential configuration (credential JSON/File/Stream) from an +// external source for authentication to Google Cloud Platform, you must validate it before +// providing it to any Google API or library. Providing an unvalidated credential configuration to +// Google APIs can compromise the security of your systems and data. For more information, refer to +// [Validate credential configurations from external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials). func CredentialsFromJSONWithParams(ctx context.Context, jsonData []byte, params CredentialsParams) (*Credentials, error) { // Make defensive copy of the slices in params. params = params.deepCopy() @@ -294,6 +300,12 @@ func CredentialsFromJSONWithParams(ctx context.Context, jsonData []byte, params } // CredentialsFromJSON invokes CredentialsFromJSONWithParams with the specified scopes. +// +// Important: If you accept a credential configuration (credential JSON/File/Stream) from an +// external source for authentication to Google Cloud Platform, you must validate it before +// providing it to any Google API or library. Providing an unvalidated credential configuration to +// Google APIs can compromise the security of your systems and data. For more information, refer to +// [Validate credential configurations from external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials). func CredentialsFromJSON(ctx context.Context, jsonData []byte, scopes ...string) (*Credentials, error) { var params CredentialsParams params.Scopes = scopes diff --git a/vendor/golang.org/x/oauth2/google/externalaccount/basecredentials.go b/vendor/golang.org/x/oauth2/google/externalaccount/basecredentials.go index ee34924e30..fc106347d8 100644 --- a/vendor/golang.org/x/oauth2/google/externalaccount/basecredentials.go +++ b/vendor/golang.org/x/oauth2/google/externalaccount/basecredentials.go @@ -278,20 +278,52 @@ type Format struct { type CredentialSource struct { // File is the location for file sourced credentials. // One field amongst File, URL, Executable, or EnvironmentID should be provided, depending on the kind of credential in question. + // + // Important: If you accept a credential configuration (credential + // JSON/File/Stream) from an external source for authentication to Google + // Cloud Platform, you must validate it before providing it to any Google + // API or library. Providing an unvalidated credential configuration to + // Google APIs can compromise the security of your systems and data. For + // more information, refer to [Validate credential configurations from + // external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials). File string `json:"file"` // Url is the URL to call for URL sourced credentials. // One field amongst File, URL, Executable, or EnvironmentID should be provided, depending on the kind of credential in question. + // + // Important: If you accept a credential configuration (credential + // JSON/File/Stream) from an external source for authentication to Google + // Cloud Platform, you must validate it before providing it to any Google + // API or library. Providing an unvalidated credential configuration to + // Google APIs can compromise the security of your systems and data. For + // more information, refer to [Validate credential configurations from + // external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials). URL string `json:"url"` // Headers are the headers to attach to the request for URL sourced credentials. Headers map[string]string `json:"headers"` // Executable is the configuration object for executable sourced credentials. // One field amongst File, URL, Executable, or EnvironmentID should be provided, depending on the kind of credential in question. + // + // Important: If you accept a credential configuration (credential + // JSON/File/Stream) from an external source for authentication to Google + // Cloud Platform, you must validate it before providing it to any Google + // API or library. Providing an unvalidated credential configuration to + // Google APIs can compromise the security of your systems and data. For + // more information, refer to [Validate credential configurations from + // external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials). Executable *ExecutableConfig `json:"executable"` // EnvironmentID is the EnvironmentID used for AWS sourced credentials. This should start with "AWS". // One field amongst File, URL, Executable, or EnvironmentID should be provided, depending on the kind of credential in question. + // + // Important: If you accept a credential configuration (credential + // JSON/File/Stream) from an external source for authentication to Google + // Cloud Platform, you must validate it before providing it to any Google + // API or library. Providing an unvalidated credential configuration to + // Google APIs can compromise the security of your systems and data. For + // more information, refer to [Validate credential configurations from + // external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials). EnvironmentID string `json:"environment_id"` // RegionURL is the metadata URL to retrieve the region from for EC2 AWS credentials. RegionURL string `json:"region_url"` diff --git a/vendor/golang.org/x/time/rate/rate.go b/vendor/golang.org/x/time/rate/rate.go index 93a798ab63..ec5f0cdd0c 100644 --- a/vendor/golang.org/x/time/rate/rate.go +++ b/vendor/golang.org/x/time/rate/rate.go @@ -405,8 +405,15 @@ func (limit Limit) durationFromTokens(tokens float64) time.Duration { if limit <= 0 { return InfDuration } - seconds := tokens / float64(limit) - return time.Duration(float64(time.Second) * seconds) + + duration := (tokens / float64(limit)) * float64(time.Second) + + // Cap the duration to the maximum representable int64 value, to avoid overflow. + if duration > float64(math.MaxInt64) { + return InfDuration + } + + return time.Duration(duration) } // tokensFromDuration is a unit conversion function from a time duration to the number of tokens diff --git a/vendor/google.golang.org/api/internal/settings.go b/vendor/google.golang.org/api/internal/settings.go index 4f5b1a0ebe..beec4ea0dd 100644 --- a/vendor/google.golang.org/api/internal/settings.go +++ b/vendor/google.golang.org/api/internal/settings.go @@ -63,6 +63,7 @@ type DialSettings struct { AllowNonDefaultServiceAccount bool DefaultUniverseDomain string UniverseDomain string + AllowHardBoundTokens []string Logger *slog.Logger // Google API system parameters. For more information please read: // https://cloud.google.com/apis/docs/system-parameters diff --git a/vendor/google.golang.org/api/internal/version.go b/vendor/google.golang.org/api/internal/version.go index 6920d53815..3fbe8701ba 100644 --- a/vendor/google.golang.org/api/internal/version.go +++ b/vendor/google.golang.org/api/internal/version.go @@ -5,4 +5,4 @@ package internal // Version is the current tagged release of the library. -const Version = "0.216.0" +const Version = "0.221.0" diff --git a/vendor/google.golang.org/api/option/internaloption/internaloption.go b/vendor/google.golang.org/api/option/internaloption/internaloption.go index c63c0c194a..18fec9c984 100644 --- a/vendor/google.golang.org/api/option/internaloption/internaloption.go +++ b/vendor/google.golang.org/api/option/internaloption/internaloption.go @@ -186,6 +186,33 @@ func (w enableJwtWithScope) Apply(o *internal.DialSettings) { o.EnableJwtWithScope = bool(w) } +// AllowHardBoundTokens returns a ClientOption that allows libraries to request a hard-bound token. +// Obtaining hard-bound tokens requires the connection to be established using either Application +// Layer Transport Security (ALTS) or mutual TLS (mTLS) with S2A. For more information on ALTS, +// see: https://cloud.google.com/docs/security/encryption-in-transit/application-layer-transport-security +// +// The AllowHardBoundTokens option accepts the following values (or a combination thereof): +// +// - "MTLS_S2A": Allows obtaining hard-bound tokens when the connection uses mutual TLS with S2A. +// - "ALTS": Allows obtaining hard-bound tokens when the connection uses ALTS. +// +// For example, to allow obtaining hard-bound tokens with either MTLS_S2A or ALTS, you would +// provide both values (e.g., {"MTLS_S2A","ALTS"}). If no value is provided, hard-bound tokens +// will not be requested. +// +// It should only be used internally by generated clients. +// This is an EXPERIMENTAL API and may be changed or removed in the future. +func AllowHardBoundTokens(protocol ...string) option.ClientOption { + return allowHardBoundTokens(protocol) +} + +type allowHardBoundTokens []string + +func (a allowHardBoundTokens) Apply(o *internal.DialSettings) { + o.AllowHardBoundTokens = make([]string, len(a)) + copy(o.AllowHardBoundTokens, a) +} + // WithCredentials returns a client option to specify credentials which will be used to authenticate API calls. // This credential takes precedence over all other credential options. func WithCredentials(creds *google.Credentials) option.ClientOption { diff --git a/vendor/google.golang.org/api/option/option.go b/vendor/google.golang.org/api/option/option.go index eb54813aae..e3321ca4a6 100644 --- a/vendor/google.golang.org/api/option/option.go +++ b/vendor/google.golang.org/api/option/option.go @@ -44,6 +44,14 @@ func (w withCredFile) Apply(o *internal.DialSettings) { // WithCredentialsFile returns a ClientOption that authenticates // API calls with the given service account or refresh token JSON // credentials file. +// +// Important: If you accept a credential configuration (credential +// JSON/File/Stream) from an external source for authentication to Google +// Cloud Platform, you must validate it before providing it to any Google +// API or library. Providing an unvalidated credential configuration to +// Google APIs can compromise the security of your systems and data. For +// more information, refer to [Validate credential configurations from +// external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials). func WithCredentialsFile(filename string) ClientOption { return withCredFile(filename) } @@ -51,6 +59,14 @@ func WithCredentialsFile(filename string) ClientOption { // WithServiceAccountFile returns a ClientOption that uses a Google service // account credentials file to authenticate. // +// Important: If you accept a credential configuration (credential +// JSON/File/Stream) from an external source for authentication to Google +// Cloud Platform, you must validate it before providing it to any Google +// API or library. Providing an unvalidated credential configuration to +// Google APIs can compromise the security of your systems and data. For +// more information, refer to [Validate credential configurations from +// external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials). +// // Deprecated: Use WithCredentialsFile instead. func WithServiceAccountFile(filename string) ClientOption { return WithCredentialsFile(filename) @@ -59,6 +75,14 @@ func WithServiceAccountFile(filename string) ClientOption { // WithCredentialsJSON returns a ClientOption that authenticates // API calls with the given service account or refresh token JSON // credentials. +// +// Important: If you accept a credential configuration (credential +// JSON/File/Stream) from an external source for authentication to Google +// Cloud Platform, you must validate it before providing it to any Google +// API or library. Providing an unvalidated credential configuration to +// Google APIs can compromise the security of your systems and data. For +// more information, refer to [Validate credential configurations from +// external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials). func WithCredentialsJSON(p []byte) ClientOption { return withCredentialsJSON(p) } diff --git a/vendor/modules.txt b/vendor/modules.txt index c400b9595b..7398fffa91 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,8 +1,8 @@ # cel.dev/expr v0.19.1 ## explicit; go 1.21.1 cel.dev/expr -# cloud.google.com/go/auth v0.13.0 -## explicit; go 1.21 +# cloud.google.com/go/auth v0.14.1 +## explicit; go 1.22.7 cloud.google.com/go/auth cloud.google.com/go/auth/credentials cloud.google.com/go/auth/credentials/idtoken @@ -18,21 +18,21 @@ cloud.google.com/go/auth/internal/credsfile cloud.google.com/go/auth/internal/jwt cloud.google.com/go/auth/internal/transport cloud.google.com/go/auth/internal/transport/cert -# cloud.google.com/go/auth/oauth2adapt v0.2.6 -## explicit; go 1.21 +# cloud.google.com/go/auth/oauth2adapt v0.2.7 +## explicit; go 1.22 cloud.google.com/go/auth/oauth2adapt # cloud.google.com/go/compute/metadata v0.6.0 ## explicit; go 1.21 cloud.google.com/go/compute/metadata -# cuelabs.dev/go/oci/ociregistry v0.0.0-20240404174027-a39bec0462d2 -## explicit; go 1.21 +# cuelabs.dev/go/oci/ociregistry v0.0.0-20241125120445-2c00c104c6e1 +## explicit; go 1.22 cuelabs.dev/go/oci/ociregistry cuelabs.dev/go/oci/ociregistry/internal/ocirequest cuelabs.dev/go/oci/ociregistry/ociauth cuelabs.dev/go/oci/ociregistry/ociclient cuelabs.dev/go/oci/ociregistry/ociref -# cuelang.org/go v0.9.2 -## explicit; go 1.21 +# cuelang.org/go v0.12.0 +## explicit; go 1.22.0 cuelang.org/go/cue cuelang.org/go/cue/ast cuelang.org/go/cue/ast/astutil @@ -53,8 +53,11 @@ cuelang.org/go/encoding/protobuf cuelang.org/go/encoding/protobuf/jsonpb cuelang.org/go/encoding/protobuf/pbinternal cuelang.org/go/encoding/protobuf/textproto +cuelang.org/go/encoding/toml +cuelang.org/go/encoding/yaml cuelang.org/go/internal cuelang.org/go/internal/astinternal +cuelang.org/go/internal/buildattr cuelang.org/go/internal/cli cuelang.org/go/internal/core/adt cuelang.org/go/internal/core/compile @@ -65,6 +68,7 @@ cuelang.org/go/internal/core/eval cuelang.org/go/internal/core/export cuelang.org/go/internal/core/runtime cuelang.org/go/internal/core/subsume +cuelang.org/go/internal/core/toposort cuelang.org/go/internal/core/validate cuelang.org/go/internal/core/walk cuelang.org/go/internal/cueconfig @@ -89,7 +93,6 @@ cuelang.org/go/internal/par cuelang.org/go/internal/pkg cuelang.org/go/internal/source cuelang.org/go/internal/task -cuelang.org/go/internal/third_party/yaml cuelang.org/go/internal/types cuelang.org/go/internal/value cuelang.org/go/mod/modcache @@ -109,6 +112,7 @@ cuelang.org/go/pkg/encoding/base64 cuelang.org/go/pkg/encoding/csv cuelang.org/go/pkg/encoding/hex cuelang.org/go/pkg/encoding/json +cuelang.org/go/pkg/encoding/toml cuelang.org/go/pkg/encoding/yaml cuelang.org/go/pkg/html cuelang.org/go/pkg/list @@ -133,10 +137,6 @@ cuelang.org/go/pkg/uuid # dario.cat/mergo v1.0.1 ## explicit; go 1.13 dario.cat/mergo -# filippo.io/edwards25519 v1.1.0 -## explicit; go 1.20 -filippo.io/edwards25519 -filippo.io/edwards25519/field # github.com/AliyunContainerService/ack-ram-tool/pkg/credentials/provider v0.14.0 ## explicit; go 1.16 github.com/AliyunContainerService/ack-ram-tool/pkg/credentials/provider @@ -209,8 +209,8 @@ github.com/ThalesIgnite/crypto11 # github.com/acobaugh/osrelease v0.1.0 ## explicit; go 1.17 github.com/acobaugh/osrelease -# github.com/agnivade/levenshtein v1.1.1 -## explicit; go 1.13 +# github.com/agnivade/levenshtein v1.2.0 +## explicit; go 1.21 github.com/agnivade/levenshtein # github.com/alibabacloud-go/alibabacloud-gateway-spi v0.0.4 ## explicit; go 1.14 @@ -258,7 +258,7 @@ github.com/aquasecurity/libbpfgo # github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 ## explicit; go 1.13 github.com/asaskevich/govalidator -# github.com/aws/aws-sdk-go-v2 v1.32.7 +# github.com/aws/aws-sdk-go-v2 v1.36.1 ## explicit; go 1.21 github.com/aws/aws-sdk-go-v2/aws github.com/aws/aws-sdk-go-v2/aws/defaults @@ -284,10 +284,10 @@ github.com/aws/aws-sdk-go-v2/internal/shareddefaults github.com/aws/aws-sdk-go-v2/internal/strings github.com/aws/aws-sdk-go-v2/internal/sync/singleflight github.com/aws/aws-sdk-go-v2/internal/timeconv -# github.com/aws/aws-sdk-go-v2/config v1.28.7 +# github.com/aws/aws-sdk-go-v2/config v1.29.6 ## explicit; go 1.21 github.com/aws/aws-sdk-go-v2/config -# github.com/aws/aws-sdk-go-v2/credentials v1.17.48 +# github.com/aws/aws-sdk-go-v2/credentials v1.17.59 ## explicit; go 1.21 github.com/aws/aws-sdk-go-v2/credentials github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds @@ -296,51 +296,51 @@ github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client github.com/aws/aws-sdk-go-v2/credentials/processcreds github.com/aws/aws-sdk-go-v2/credentials/ssocreds github.com/aws/aws-sdk-go-v2/credentials/stscreds -# github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.22 +# github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.28 ## explicit; go 1.21 github.com/aws/aws-sdk-go-v2/feature/ec2/imds github.com/aws/aws-sdk-go-v2/feature/ec2/imds/internal/config -# github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.26 +# github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.32 ## explicit; go 1.21 github.com/aws/aws-sdk-go-v2/internal/configsources -# github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.26 +# github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.32 ## explicit; go 1.21 github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 -# github.com/aws/aws-sdk-go-v2/internal/ini v1.8.1 +# github.com/aws/aws-sdk-go-v2/internal/ini v1.8.2 ## explicit; go 1.21 github.com/aws/aws-sdk-go-v2/internal/ini -# github.com/aws/aws-sdk-go-v2/service/ecr v1.20.2 -## explicit; go 1.15 +# github.com/aws/aws-sdk-go-v2/service/ecr v1.40.3 +## explicit; go 1.21 github.com/aws/aws-sdk-go-v2/service/ecr github.com/aws/aws-sdk-go-v2/service/ecr/internal/endpoints github.com/aws/aws-sdk-go-v2/service/ecr/types -# github.com/aws/aws-sdk-go-v2/service/ecrpublic v1.18.2 -## explicit; go 1.15 +# github.com/aws/aws-sdk-go-v2/service/ecrpublic v1.31.2 +## explicit; go 1.21 github.com/aws/aws-sdk-go-v2/service/ecrpublic github.com/aws/aws-sdk-go-v2/service/ecrpublic/internal/endpoints github.com/aws/aws-sdk-go-v2/service/ecrpublic/types -# github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.1 +# github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.2 ## explicit; go 1.21 github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding -# github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.7 +# github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.13 ## explicit; go 1.21 github.com/aws/aws-sdk-go-v2/service/internal/presigned-url -# github.com/aws/aws-sdk-go-v2/service/sso v1.24.8 +# github.com/aws/aws-sdk-go-v2/service/sso v1.24.15 ## explicit; go 1.21 github.com/aws/aws-sdk-go-v2/service/sso github.com/aws/aws-sdk-go-v2/service/sso/internal/endpoints github.com/aws/aws-sdk-go-v2/service/sso/types -# github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.7 +# github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.14 ## explicit; go 1.21 github.com/aws/aws-sdk-go-v2/service/ssooidc github.com/aws/aws-sdk-go-v2/service/ssooidc/internal/endpoints github.com/aws/aws-sdk-go-v2/service/ssooidc/types -# github.com/aws/aws-sdk-go-v2/service/sts v1.33.3 +# github.com/aws/aws-sdk-go-v2/service/sts v1.33.14 ## explicit; go 1.21 github.com/aws/aws-sdk-go-v2/service/sts github.com/aws/aws-sdk-go-v2/service/sts/internal/endpoints github.com/aws/aws-sdk-go-v2/service/sts/types -# github.com/aws/smithy-go v1.22.1 +# github.com/aws/smithy-go v1.22.2 ## explicit; go 1.21 github.com/aws/smithy-go github.com/aws/smithy-go/auth @@ -365,8 +365,8 @@ github.com/aws/smithy-go/tracing github.com/aws/smithy-go/transport/http github.com/aws/smithy-go/transport/http/internal/io github.com/aws/smithy-go/waiter -# github.com/awslabs/amazon-ecr-credential-helper/ecr-login v0.0.0-20231024185945-8841054dbdb8 -## explicit; go 1.19 +# github.com/awslabs/amazon-ecr-credential-helper/ecr-login v0.9.1 +## explicit; go 1.22 github.com/awslabs/amazon-ecr-credential-helper/ecr-login github.com/awslabs/amazon-ecr-credential-helper/ecr-login/api github.com/awslabs/amazon-ecr-credential-helper/ecr-login/cache @@ -381,21 +381,22 @@ github.com/blang/semver # github.com/blang/semver/v4 v4.0.0 ## explicit; go 1.14 github.com/blang/semver/v4 -# github.com/buildkite/agent/v3 v3.81.0 -## explicit; go 1.22.6 +# github.com/buildkite/agent/v3 v3.92.1 +## explicit; go 1.22.7 github.com/buildkite/agent/v3/api +github.com/buildkite/agent/v3/internal/agenthttp github.com/buildkite/agent/v3/logger github.com/buildkite/agent/v3/version -# github.com/buildkite/go-pipeline v0.13.1 +# github.com/buildkite/go-pipeline v0.13.3 ## explicit; go 1.22.6 github.com/buildkite/go-pipeline github.com/buildkite/go-pipeline/internal/env github.com/buildkite/go-pipeline/ordered github.com/buildkite/go-pipeline/warning -# github.com/buildkite/interpolate v0.1.3 +# github.com/buildkite/interpolate v0.1.5 ## explicit; go 1.22 github.com/buildkite/interpolate -# github.com/buildkite/roko v1.2.0 +# github.com/buildkite/roko v1.3.1 ## explicit; go 1.18 github.com/buildkite/roko # github.com/cenkalti/backoff/v4 v4.3.0 @@ -494,7 +495,7 @@ github.com/dustin/go-humanize ## explicit; go 1.13 github.com/emicklei/go-restful/v3 github.com/emicklei/go-restful/v3/log -# github.com/emicklei/proto v1.12.1 +# github.com/emicklei/proto v1.13.4 ## explicit; go 1.12 github.com/emicklei/proto # github.com/evanphx/json-patch/v5 v5.9.11 @@ -525,7 +526,6 @@ github.com/go-ini/ini ## explicit; go 1.12 github.com/go-jose/go-jose/v3 github.com/go-jose/go-jose/v3/cipher -github.com/go-jose/go-jose/v3/cryptosigner github.com/go-jose/go-jose/v3/json github.com/go-jose/go-jose/v3/jwt # github.com/go-jose/go-jose/v4 v4.0.4 @@ -586,10 +586,10 @@ github.com/go-openapi/swag # github.com/go-openapi/validate v0.24.0 ## explicit; go 1.20 github.com/go-openapi/validate -# github.com/go-piv/piv-go v1.11.0 -## explicit; go 1.16 -github.com/go-piv/piv-go/piv -github.com/go-piv/piv-go/third_party/rsa +# github.com/go-piv/piv-go/v2 v2.3.0 +## explicit; go 1.20 +github.com/go-piv/piv-go/v2/piv +github.com/go-piv/piv-go/v2/third_party/rsa # github.com/gobuffalo/flect v1.0.3 ## explicit; go 1.16 github.com/gobuffalo/flect @@ -646,8 +646,8 @@ github.com/google/cel-go/interpreter github.com/google/cel-go/interpreter/functions github.com/google/cel-go/parser github.com/google/cel-go/parser/gen -# github.com/google/certificate-transparency-go v1.2.1 -## explicit; go 1.21.0 +# github.com/google/certificate-transparency-go v1.3.1 +## explicit; go 1.22.0 github.com/google/certificate-transparency-go github.com/google/certificate-transparency-go/asn1 github.com/google/certificate-transparency-go/client @@ -713,7 +713,7 @@ github.com/google/go-querystring/query ## explicit; go 1.12 github.com/google/gofuzz github.com/google/gofuzz/bytesource -# github.com/google/s2a-go v0.1.8 +# github.com/google/s2a-go v0.1.9 ## explicit; go 1.20 github.com/google/s2a-go github.com/google/s2a-go/fallback @@ -795,9 +795,6 @@ github.com/jedisct1/go-minisign # github.com/jellydator/ttlcache/v3 v3.3.0 ## explicit; go 1.18 github.com/jellydator/ttlcache/v3 -# github.com/jmespath/go-jmespath v0.4.1-0.20220621161143-b0104c826a24 -## explicit; go 1.14 -github.com/jmespath/go-jmespath # github.com/josharian/intern v1.0.0 ## explicit; go 1.5 github.com/josharian/intern @@ -824,7 +821,7 @@ github.com/letsencrypt/boulder/strictyaml # github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de ## explicit github.com/liggitt/tabwriter -# github.com/magiconair/properties v1.8.7 +# github.com/magiconair/properties v1.8.9 ## explicit; go 1.19 github.com/magiconair/properties # github.com/mailru/easyjson v0.9.0 @@ -853,7 +850,7 @@ github.com/mitchellh/go-homedir # github.com/mitchellh/go-wordwrap v1.0.1 ## explicit; go 1.14 github.com/mitchellh/go-wordwrap -# github.com/mitchellh/mapstructure v1.5.0 +# github.com/mitchellh/mapstructure v1.5.1-0.20231216201459-8508981c8b6c ## explicit; go 1.14 github.com/mitchellh/mapstructure # github.com/moby/sys/mountinfo v0.7.2 @@ -899,18 +896,9 @@ github.com/oklog/ulid # github.com/oleiade/reflections v1.1.0 ## explicit; go 1.22.6 github.com/oleiade/reflections -# github.com/open-policy-agent/opa v0.68.0 -## explicit; go 1.21 -github.com/open-policy-agent/opa/ast -github.com/open-policy-agent/opa/ast/internal/scanner -github.com/open-policy-agent/opa/ast/internal/tokens -github.com/open-policy-agent/opa/ast/json -github.com/open-policy-agent/opa/ast/location -github.com/open-policy-agent/opa/bundle +# github.com/open-policy-agent/opa v1.1.0 +## explicit; go 1.22.7 github.com/open-policy-agent/opa/capabilities -github.com/open-policy-agent/opa/config -github.com/open-policy-agent/opa/format -github.com/open-policy-agent/opa/hooks github.com/open-policy-agent/opa/internal/bundle github.com/open-policy-agent/opa/internal/cidr/merge github.com/open-policy-agent/opa/internal/compiler @@ -962,33 +950,43 @@ github.com/open-policy-agent/opa/internal/wasm/opcode github.com/open-policy-agent/opa/internal/wasm/sdk/opa/capabilities github.com/open-policy-agent/opa/internal/wasm/types github.com/open-policy-agent/opa/internal/wasm/util -github.com/open-policy-agent/opa/ir -github.com/open-policy-agent/opa/keys -github.com/open-policy-agent/opa/loader -github.com/open-policy-agent/opa/loader/extension -github.com/open-policy-agent/opa/loader/filter -github.com/open-policy-agent/opa/logging -github.com/open-policy-agent/opa/metrics -github.com/open-policy-agent/opa/plugins -github.com/open-policy-agent/opa/plugins/rest -github.com/open-policy-agent/opa/rego -github.com/open-policy-agent/opa/resolver -github.com/open-policy-agent/opa/resolver/wasm -github.com/open-policy-agent/opa/schemas -github.com/open-policy-agent/opa/storage -github.com/open-policy-agent/opa/storage/inmem -github.com/open-policy-agent/opa/storage/internal/errors -github.com/open-policy-agent/opa/storage/internal/ptr -github.com/open-policy-agent/opa/topdown -github.com/open-policy-agent/opa/topdown/builtins -github.com/open-policy-agent/opa/topdown/cache -github.com/open-policy-agent/opa/topdown/copypropagation -github.com/open-policy-agent/opa/topdown/print -github.com/open-policy-agent/opa/tracing -github.com/open-policy-agent/opa/types -github.com/open-policy-agent/opa/util -github.com/open-policy-agent/opa/util/decoding -github.com/open-policy-agent/opa/version +github.com/open-policy-agent/opa/v1/ast +github.com/open-policy-agent/opa/v1/ast/internal/scanner +github.com/open-policy-agent/opa/v1/ast/internal/tokens +github.com/open-policy-agent/opa/v1/ast/json +github.com/open-policy-agent/opa/v1/ast/location +github.com/open-policy-agent/opa/v1/bundle +github.com/open-policy-agent/opa/v1/capabilities +github.com/open-policy-agent/opa/v1/config +github.com/open-policy-agent/opa/v1/format +github.com/open-policy-agent/opa/v1/hooks +github.com/open-policy-agent/opa/v1/ir +github.com/open-policy-agent/opa/v1/keys +github.com/open-policy-agent/opa/v1/loader +github.com/open-policy-agent/opa/v1/loader/extension +github.com/open-policy-agent/opa/v1/loader/filter +github.com/open-policy-agent/opa/v1/logging +github.com/open-policy-agent/opa/v1/metrics +github.com/open-policy-agent/opa/v1/plugins +github.com/open-policy-agent/opa/v1/plugins/rest +github.com/open-policy-agent/opa/v1/rego +github.com/open-policy-agent/opa/v1/resolver +github.com/open-policy-agent/opa/v1/resolver/wasm +github.com/open-policy-agent/opa/v1/schemas +github.com/open-policy-agent/opa/v1/storage +github.com/open-policy-agent/opa/v1/storage/inmem +github.com/open-policy-agent/opa/v1/storage/internal/errors +github.com/open-policy-agent/opa/v1/storage/internal/ptr +github.com/open-policy-agent/opa/v1/topdown +github.com/open-policy-agent/opa/v1/topdown/builtins +github.com/open-policy-agent/opa/v1/topdown/cache +github.com/open-policy-agent/opa/v1/topdown/copypropagation +github.com/open-policy-agent/opa/v1/topdown/print +github.com/open-policy-agent/opa/v1/tracing +github.com/open-policy-agent/opa/v1/types +github.com/open-policy-agent/opa/v1/util +github.com/open-policy-agent/opa/v1/util/decoding +github.com/open-policy-agent/opa/v1/version # github.com/opencontainers/go-digest v1.0.0 ## explicit; go 1.13 github.com/opencontainers/go-digest @@ -1020,8 +1018,8 @@ github.com/opentracing/opentracing-go/log # github.com/pborman/uuid v1.2.1 ## explicit github.com/pborman/uuid -# github.com/pelletier/go-toml/v2 v2.2.2 -## explicit; go 1.16 +# github.com/pelletier/go-toml/v2 v2.2.3 +## explicit; go 1.21.0 github.com/pelletier/go-toml/v2 github.com/pelletier/go-toml/v2/internal/characters github.com/pelletier/go-toml/v2/internal/danger @@ -1061,7 +1059,7 @@ github.com/prometheus/common/model github.com/prometheus/procfs github.com/prometheus/procfs/internal/fs github.com/prometheus/procfs/internal/util -# github.com/protocolbuffers/txtpbfmt v0.0.0-20231025115547-084445ff1adf +# github.com/protocolbuffers/txtpbfmt v0.0.0-20241112170944-20d2c9ebc01d ## explicit; go 1.18 github.com/protocolbuffers/txtpbfmt/ast github.com/protocolbuffers/txtpbfmt/parser @@ -1069,8 +1067,8 @@ github.com/protocolbuffers/txtpbfmt/unquote # github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 ## explicit github.com/rcrowley/go-metrics -# github.com/rogpeppe/go-internal v1.13.1 -## explicit; go 1.22 +# github.com/rogpeppe/go-internal v1.13.2-0.20241226121412-a5dc8ff20d0a +## explicit; go 1.22.0 github.com/rogpeppe/go-internal/internal/syscall/windows github.com/rogpeppe/go-internal/internal/syscall/windows/sysdll github.com/rogpeppe/go-internal/lockedfile @@ -1104,8 +1102,8 @@ github.com/segmentio/ksuid # github.com/shibumi/go-pathspec v1.3.0 ## explicit; go 1.17 github.com/shibumi/go-pathspec -# github.com/sigstore/cosign/v2 v2.4.1 -## explicit; go 1.22.7 +# github.com/sigstore/cosign/v2 v2.4.3 +## explicit; go 1.23.4 github.com/sigstore/cosign/v2/cmd/cosign/cli/fulcio github.com/sigstore/cosign/v2/cmd/cosign/cli/fulcio/fulcioverifier github.com/sigstore/cosign/v2/cmd/cosign/cli/generate @@ -1161,17 +1159,17 @@ github.com/sigstore/cosign/v2/pkg/providers/google github.com/sigstore/cosign/v2/pkg/providers/spiffe github.com/sigstore/cosign/v2/pkg/signature github.com/sigstore/cosign/v2/pkg/types -# github.com/sigstore/fulcio v1.6.4 -## explicit; go 1.22.6 +# github.com/sigstore/fulcio v1.6.6 +## explicit; go 1.23.3 github.com/sigstore/fulcio/pkg/api -# github.com/sigstore/protobuf-specs v0.3.3 +# github.com/sigstore/protobuf-specs v0.4.0 ## explicit; go 1.22.0 github.com/sigstore/protobuf-specs/gen/pb-go/bundle/v1 github.com/sigstore/protobuf-specs/gen/pb-go/common/v1 github.com/sigstore/protobuf-specs/gen/pb-go/dsse github.com/sigstore/protobuf-specs/gen/pb-go/rekor/v1 github.com/sigstore/protobuf-specs/gen/pb-go/trustroot/v1 -# github.com/sigstore/rekor v1.3.8 +# github.com/sigstore/rekor v1.3.9 ## explicit; go 1.22.0 github.com/sigstore/rekor/pkg/client github.com/sigstore/rekor/pkg/generated/client @@ -1202,7 +1200,7 @@ github.com/sigstore/rekor/pkg/types/rekord github.com/sigstore/rekor/pkg/types/rekord/v0.0.1 github.com/sigstore/rekor/pkg/util github.com/sigstore/rekor/pkg/verify -# github.com/sigstore/sigstore v1.8.12 +# github.com/sigstore/sigstore v1.8.15 ## explicit; go 1.22.0 github.com/sigstore/sigstore/pkg/cryptoutils github.com/sigstore/sigstore/pkg/fulcioroots @@ -1211,11 +1209,15 @@ github.com/sigstore/sigstore/pkg/oauthflow github.com/sigstore/sigstore/pkg/signature github.com/sigstore/sigstore/pkg/signature/dsse github.com/sigstore/sigstore/pkg/signature/kms +github.com/sigstore/sigstore/pkg/signature/kms/cliplugin +github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/common +github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/encoding +github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/internal/signerverifier github.com/sigstore/sigstore/pkg/signature/options github.com/sigstore/sigstore/pkg/signature/payload github.com/sigstore/sigstore/pkg/tuf -# github.com/sigstore/sigstore-go v0.6.1 -## explicit; go 1.22.5 +# github.com/sigstore/sigstore-go v0.7.0 +## explicit; go 1.22.0 github.com/sigstore/sigstore-go/pkg/bundle github.com/sigstore/sigstore-go/pkg/fulcio/certificate github.com/sigstore/sigstore-go/pkg/root @@ -1223,8 +1225,8 @@ github.com/sigstore/sigstore-go/pkg/tlog github.com/sigstore/sigstore-go/pkg/tuf github.com/sigstore/sigstore-go/pkg/util github.com/sigstore/sigstore-go/pkg/verify -# github.com/sigstore/timestamp-authority v1.2.2 -## explicit; go 1.21 +# github.com/sigstore/timestamp-authority v1.2.4 +## explicit; go 1.22.0 github.com/sigstore/timestamp-authority/pkg/verification # github.com/sirupsen/logrus v1.9.3 ## explicit; go 1.13 @@ -1246,7 +1248,7 @@ github.com/spf13/afero/mem # github.com/spf13/cast v1.7.0 ## explicit; go 1.19 github.com/spf13/cast -# github.com/spf13/cobra v1.8.1 +# github.com/spf13/cobra v1.9.1 ## explicit; go 1.15 github.com/spf13/cobra # github.com/spf13/pflag v1.0.6 @@ -1264,8 +1266,8 @@ github.com/spf13/viper/internal/encoding/json github.com/spf13/viper/internal/encoding/toml github.com/spf13/viper/internal/encoding/yaml github.com/spf13/viper/internal/features -# github.com/spiffe/go-spiffe/v2 v2.3.0 -## explicit; go 1.21 +# github.com/spiffe/go-spiffe/v2 v2.5.0 +## explicit; go 1.22.11 github.com/spiffe/go-spiffe/v2/bundle/jwtbundle github.com/spiffe/go-spiffe/v2/bundle/spiffebundle github.com/spiffe/go-spiffe/v2/bundle/x509bundle @@ -1326,7 +1328,7 @@ github.com/theupdateframework/go-tuf/pkg/targets github.com/theupdateframework/go-tuf/sign github.com/theupdateframework/go-tuf/util github.com/theupdateframework/go-tuf/verify -# github.com/theupdateframework/go-tuf/v2 v2.0.1 +# github.com/theupdateframework/go-tuf/v2 v2.0.2 ## explicit; go 1.21 github.com/theupdateframework/go-tuf/v2/metadata github.com/theupdateframework/go-tuf/v2/metadata/config @@ -1354,9 +1356,6 @@ github.com/vbatts/tar-split/archive/tar # github.com/x448/float16 v0.8.4 ## explicit; go 1.11 github.com/x448/float16 -# github.com/xanzy/go-gitlab v0.109.0 -## explicit; go 1.19 -github.com/xanzy/go-gitlab # github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb ## explicit github.com/xeipuuv/gojsonpointer @@ -1369,9 +1368,12 @@ github.com/xrash/smetrics # github.com/yashtewari/glob-intersection v0.2.0 ## explicit; go 1.17 github.com/yashtewari/glob-intersection -# github.com/zeebo/errs v1.3.0 +# github.com/zeebo/errs v1.4.0 ## explicit; go 1.12 github.com/zeebo/errs +# gitlab.com/gitlab-org/api/client-go v0.123.0 +## explicit; go 1.22 +gitlab.com/gitlab-org/api/client-go # go.mongodb.org/mongo-driver v1.14.0 ## explicit; go 1.18 go.mongodb.org/mongo-driver/bson @@ -1385,13 +1387,13 @@ go.mongodb.org/mongo-driver/x/bsonx/bsoncore ## explicit; go 1.22.0 go.opentelemetry.io/auto/sdk go.opentelemetry.io/auto/sdk/internal/telemetry -# go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0 +# go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0 ## explicit; go 1.22.0 go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil -# go.opentelemetry.io/otel v1.33.0 +# go.opentelemetry.io/otel v1.34.0 ## explicit; go 1.22.0 go.opentelemetry.io/otel go.opentelemetry.io/otel/attribute @@ -1407,23 +1409,23 @@ go.opentelemetry.io/otel/semconv/v1.17.0 go.opentelemetry.io/otel/semconv/v1.17.0/httpconv go.opentelemetry.io/otel/semconv/v1.20.0 go.opentelemetry.io/otel/semconv/v1.26.0 -# go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.33.0 -## explicit; go 1.22.7 +# go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.34.0 +## explicit; go 1.22.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform -# go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.33.0 -## explicit; go 1.22.7 +# go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.34.0 +## explicit; go 1.22.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/envconfig go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/otlpconfig go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/retry -# go.opentelemetry.io/otel/metric v1.33.0 +# go.opentelemetry.io/otel/metric v1.34.0 ## explicit; go 1.22.0 go.opentelemetry.io/otel/metric go.opentelemetry.io/otel/metric/embedded go.opentelemetry.io/otel/metric/noop -# go.opentelemetry.io/otel/sdk v1.33.0 +# go.opentelemetry.io/otel/sdk v1.34.0 ## explicit; go 1.22.0 go.opentelemetry.io/otel/sdk go.opentelemetry.io/otel/sdk/instrumentation @@ -1431,29 +1433,17 @@ go.opentelemetry.io/otel/sdk/internal/env go.opentelemetry.io/otel/sdk/internal/x go.opentelemetry.io/otel/sdk/resource go.opentelemetry.io/otel/sdk/trace -# go.opentelemetry.io/otel/trace v1.33.0 +# go.opentelemetry.io/otel/trace v1.34.0 ## explicit; go 1.22.0 go.opentelemetry.io/otel/trace go.opentelemetry.io/otel/trace/embedded go.opentelemetry.io/otel/trace/noop -# go.opentelemetry.io/proto/otlp v1.4.0 -## explicit; go 1.22.7 +# go.opentelemetry.io/proto/otlp v1.5.0 +## explicit; go 1.22.0 go.opentelemetry.io/proto/otlp/collector/trace/v1 go.opentelemetry.io/proto/otlp/common/v1 go.opentelemetry.io/proto/otlp/resource/v1 go.opentelemetry.io/proto/otlp/trace/v1 -# go.step.sm/crypto v0.56.0 -## explicit; go 1.22 -go.step.sm/crypto/fingerprint -go.step.sm/crypto/internal/bcrypt_pbkdf -go.step.sm/crypto/internal/emoji -go.step.sm/crypto/internal/utils -go.step.sm/crypto/internal/utils/utfbom -go.step.sm/crypto/jose -go.step.sm/crypto/keyutil -go.step.sm/crypto/pemutil -go.step.sm/crypto/randutil -go.step.sm/crypto/x25519 # go.uber.org/multierr v1.11.0 ## explicit; go 1.19 go.uber.org/multierr @@ -1528,7 +1518,7 @@ golang.org/x/net/internal/timeseries golang.org/x/net/proxy golang.org/x/net/trace golang.org/x/net/websocket -# golang.org/x/oauth2 v0.25.0 +# golang.org/x/oauth2 v0.26.0 ## explicit; go 1.18 golang.org/x/oauth2 golang.org/x/oauth2/authhandler @@ -1580,7 +1570,7 @@ golang.org/x/text/secure/bidirule golang.org/x/text/transform golang.org/x/text/unicode/bidi golang.org/x/text/unicode/norm -# golang.org/x/time v0.9.0 +# golang.org/x/time v0.10.0 ## explicit; go 1.18 golang.org/x/time/rate # golang.org/x/tools v0.29.0 @@ -1610,8 +1600,8 @@ golang.org/x/tools/internal/versions # gomodules.xyz/jsonpatch/v2 v2.4.0 ## explicit; go 1.20 gomodules.xyz/jsonpatch/v2 -# google.golang.org/api v0.216.0 -## explicit; go 1.22 +# google.golang.org/api v0.221.0 +## explicit; go 1.22.7 google.golang.org/api/googleapi/transport google.golang.org/api/idtoken google.golang.org/api/impersonate @@ -1621,13 +1611,13 @@ google.golang.org/api/internal/impersonate google.golang.org/api/option google.golang.org/api/option/internaloption google.golang.org/api/transport/http -# google.golang.org/genproto/googleapis/api v0.0.0-20241219192143-6b3ec007d9bb -## explicit; go 1.21 +# google.golang.org/genproto/googleapis/api v0.0.0-20250115164207-1a7da9e5054f +## explicit; go 1.22 google.golang.org/genproto/googleapis/api google.golang.org/genproto/googleapis/api/annotations google.golang.org/genproto/googleapis/api/expr/v1alpha1 google.golang.org/genproto/googleapis/api/httpbody -# google.golang.org/genproto/googleapis/rpc v0.0.0-20250102185135-69823020774d +# google.golang.org/genproto/googleapis/rpc v0.0.0-20250207221924-e9438ea467c6 ## explicit; go 1.22 google.golang.org/genproto/googleapis/rpc/errdetails google.golang.org/genproto/googleapis/rpc/status